0
0
SQLquery~5 mins

ORDER BY with ASC and DESC in SQL

Choose your learning style9 modes available
Introduction

We use ORDER BY to sort data in a table. ASC sorts from smallest to largest, DESC sorts from largest to smallest.

When you want to see a list of products sorted by price from low to high.
When you want to find the top scoring students by sorting scores from high to low.
When you want to organize a list of names alphabetically.
When you want to see recent orders first by sorting dates from newest to oldest.
Syntax
SQL
SELECT column1, column2
FROM table_name
ORDER BY column1 ASC | DESC;

ASC means ascending order (smallest to largest).

DESC means descending order (largest to smallest).

Examples
This sorts people by age from youngest to oldest.
SQL
SELECT name, age
FROM people
ORDER BY age ASC;
This sorts products by price from highest to lowest.
SQL
SELECT product, price
FROM products
ORDER BY price DESC;
This sorts cities alphabetically by name.
SQL
SELECT city, population
FROM cities
ORDER BY city ASC;
Sample Program

This creates a table of employees and sorts them by salary from highest to lowest.

SQL
CREATE TABLE employees (id INT, name VARCHAR(20), salary INT);
INSERT INTO employees VALUES
(1, 'Alice', 5000),
(2, 'Bob', 7000),
(3, 'Charlie', 6000);

SELECT name, salary
FROM employees
ORDER BY salary DESC;
OutputSuccess
Important Notes

If you do not specify ASC or DESC, ASC is the default.

You can order by multiple columns by separating them with commas.

Summary

ORDER BY sorts query results.

Use ASC for ascending order, DESC for descending order.

Sorting helps you organize data to find what you need quickly.