ORDER BY — Sorting Results in SQL
Control the row order of your result
ORDER BY sorts the final result by one or more columns, ascending (ASC, the default) or descending (DESC). Without it, SQL makes no promises about row order — ever. Sort by salary DESC for “top earners first”, or chain columns like ORDER BY department ASC, salary DESC to sort within groups.
Sort keys come first
ORDER BY salary names the column (or expression) that decides the order.
Pick the direction
ASC = low → high (the default), DESC = high → low. One keyword, whole different story.
Chain keys for tie-breaks
ORDER BY department ASC, salary DESC — departments A→Z, salaries high→low inside each.
Sort runs last
After filtering and grouping, on the final result — that is why aliases from SELECT are usable in ORDER BY.
No ORDER BY, no promise
Without it, row order is whatever the engine feels like — "usually insertion order" is a bug waiting to happen.
1SELECT name, department, salary2FROM employees3ORDER BY salary DESC;
| name | department | salary |
|---|---|---|
| Cynthia | Engineering | 91000 |
| Alice | Engineering | 85000 |
| Farid | Engineering | 73000 |
| Elena | Sales | 58000 |
| Bob | Sales | 52000 |
| David | Marketing | 47000 |
Highest salary first. Flip to ASC in the visualization to watch the bars re-sort in the opposite direction — same query, one keyword changed.
Descending — top first
Highest values lead; the leaderboard pattern.
1SELECT name, salary2FROM employees3ORDER BY salary DESC;
| name | salary |
|---|---|
| Cynthia | 91000 |
| Alice | 85000 |
| Farid | 73000 |
| Elena | 58000 |
| Bob | 52000 |
| David | 47000 |
Ascending — default
Lowest first; also what you get with no keyword.
1SELECT name, salary2FROM employees3ORDER BY salary ASC;
| name | salary |
|---|---|
| David | 47000 |
| Bob | 52000 |
| Elena | 58000 |
| Farid | 73000 |
| Alice | 85000 |
| Cynthia | 91000 |
Multi-column sort
Later keys break ties from earlier ones.
1SELECT name, department, salary2FROM employees3ORDER BY department ASC, salary DESC;
| name | department | salary |
|---|---|---|
| Cynthia | Engineering | 91000 |
| Alice | Engineering | 85000 |
| Farid | Engineering | 73000 |
| David | Marketing | 47000 |
| Elena | Sales | 58000 |
| Bob | Sales | 52000 |
Sort by expression
ORDER BY takes any expression, not just bare columns.
1SELECT name, salary2FROM employees3ORDER BY salary * -1;
| name | salary |
|---|---|
| Cynthia | 91000 |
| Alice | 85000 |
| Farid | 73000 |
| Elena | 58000 |
| Bob | 52000 |
| David | 47000 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.