ORDER BY sorts the result set — ascending by default, descending with DESC.
Syntax
SELECT columns
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];
Sample Table: employees
| name | department | salary |
|---|---|---|
| Aman | Engineering | 65000 |
| Riya | Marketing | 52000 |
| Karan | Engineering | 71000 |
Example
SELECT name, salary FROM employees
ORDER BY salary DESC;
Output:
| name | salary |
|---|---|
| Karan | 71000 |
| Aman | 65000 |
| Riya | 52000 |
Sorting by Multiple Columns
SELECT name, department, salary FROM employees
ORDER BY department ASC, salary DESC;
Rows are sorted by department first; within each department, by salary highest-to-lowest. The second column only breaks ties within the first.
Sorting by Column Position (Use Sparingly)
SELECT name, salary FROM employees
ORDER BY 2 DESC; -- sorts by the 2nd selected column (salary)
Works, but is fragile — if the column order in SELECT changes, the sort silently changes too. Naming the column is safer.
Practical Use Case
Leaderboards, "most recent first" feeds, top-N reports — almost any user-facing list needs a defined, intentional order.
Common Mistakes
- Assuming rows come back in a "natural" or insertion order without
ORDER BY— relational databases make no guarantee about row order unless you explicitly sort - Sorting by an alias defined in
SELECTand expecting it to work in every database the same way — most do support it, but it's technically becauseORDER BYexecutes afterSELECTin logical order
Interview Relevance
Q: "If I don't use ORDER BY, what order will my rows come back in?" Correct answer: undefined / implementation-dependent — never rely on it.
Practice Question
Write a query that lists employees sorted by department (A–Z), and within each department, by name (A–Z).