SQL ORDER BY Keyword
📘 SQL ORDER BY Keyword
The ORDER BY keyword in SQL is used to sort query results by one or more columns—either in ascending or descending order.
It is typically placed at the end of a SELECT query.
1. Basic Syntax
-
ASC= ascending (default) -
DESC= descending
2. Example: Sort by One Column
Sort employees by salary (lowest → highest):
Sort employees by salary (highest → lowest):
3. Sorting by Multiple Columns
If the first column has ties, SQL will sort by the next column.
Here:
-
Sort by department alphabetically
-
Within each department, sort by salary descending
4. ORDER BY with Expressions
You can sort using expressions or functions.
Example:
5. ORDER BY with Aliases
Aliases defined in SELECT can be used in ORDER BY.
6. ORDER BY for Text, Numbers, and Dates
SQL sorts based on column data type:
-
Text → alphabetical
-
Numbers → numeric
-
Dates → chronological
Example:
7. ORDER BY with NULL Values
Different databases sort NULLs differently:
| DBMS | ASC | DESC |
|---|---|---|
| PostgreSQL | NULLs first | NULLs last |
| MySQL | NULLs first | NULLs last |
| Oracle | NULLs last | NULLs first |
To control placement:
(Works in PostgreSQL, Oracle)
8. ORDER BY with LIMIT (Pagination)
Common in APIs and dashboards:
9. Real-World Example
Return the 5 highest-paid employees in IT:
