The ORDER BY Clause in SQL is used with the select statement to sort the data in ascending order or descending order, based on one or more columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
Syntax
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC;
ASC→ Ascending order (smallest to largest, A to Z)DESC→ Descending order (largest to smallest, Z to A)ASCis the default if no direction is specified.
Example 1: Sort in Ascending Order
Suppose we have an Employees table:
| ID | Name | Salary |
|---|---|---|
| 1 | Mayank | 60000 |
| 2 | Ayush | 45000 |
| 3 | Sakshi | 75000 |
| 4 | Shivansh | 50000 |
SELECT *
FROM Employees
ORDER BY Salary ASC;
Result:
| ID | Name | Salary |
|---|---|---|
| 2 | Ayush | 45000 |
| 4 | Shivnash | 50000 |
| 1 | Mayank | 60000 |
| 3 | Sakshi | 75000 |
Example 2: Sort in Descending Order
SELECT *
FROM Employees
ORDER BY Salary DESC;
Result:
| ID | Name | Salary |
|---|---|---|
| 3 | Sakshi | 75000 |
| 1 | Mayank | 60000 |
| 4 | Shivansh | 50000 |
| 2 | Ayush | 45000 |
Example 3: Sort by Name
SELECT *
FROM Employees
ORDER BY Name ASC;
This sorts employee names alphabetically from A to Z.
ORDER BY with WHERE
ORDER BY can be used along with WHERE:
SELECT *
FROM Employees
WHERE Salary > 40000
ORDER BY Salary DESC;
This first selects employees earning more than 40,000 and then displays them from highest salary to lowest salary.