SQL ORDER BY Keyword
The ORDER BY clause in SQL is used to sort the result set of a query based on one or more columns. You can arrange the results in either ascending (ASC) or descending (DESC) order.
Why Use ORDER BY?
Syntax:
- Helps organize query results logically.
- Useful for reporting, analytics, and user-friendly outputs.
- Default sorting is ascending, but you can specify descending as needed.
Syntax:
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC | DESC], column2 [ASC | DESC], ...;
- column1, column2: Columns you want to retrieve.
- table_name: Name of the table.
- ORDER BY: Clause used to sort the result.
- ASC: Ascending order (default).
- DESC: Descending order.
EMPLOYEES Table
ID | Name | Salary |
---|---|---|
1 | Shweta | 12000 |
2 | Raj | 25000 |
3 | Abhi | 18000 |
4 | Roshani | 15000 |
Example: Default Order (Ascending)
SELECT *
FROM employees
ORDER BY salary;
Output:
ID | Name | Header 3 |
---|---|---|
1 | Shweta | 12000 |
4 | Roshani | 15000 |
3 | Abhi | 18000 |
2 | Raj | 25000 |
By default, the ORDER BY clause sorts salaries from lowest to highest.
Example: Descending Order
SELECT *
FROM employees
ORDER BY salary DESC;
Output:
ID | Name | Salary |
---|---|---|
2 | Raj | 25000 |
3 | Abhi | 18000 |
4 | Roshani | 15000 |
1 | Shweta | 12000 |
With DESC, the result is sorted from highest to lowest salary.
Key Point
- You can sort by multiple columns, like:
SELECT * FROM employees ORDER BY age ASC, salary DESC;
- Always appears at the end of a SELECT query.
- Use ASC and DESC explicitly for clarity, even though ASC is the default.