ORDER BY
Beginner⏱️ 5 mins read
What You'll Learn
ORDER BY sorts the result set. Default is ASC (ascending, A→Z, 0→9). Use DESC for descending. You can sort by multiple columns — the second sort applies within ties of the first. Without ORDER BY, SQL makes NO guarantee about row order.
Syntax
SELECT cols FROM table ORDER BY col ASC;
SELECT cols FROM table ORDER BY col1 DESC, col2 ASC;Example
-- Highest salary first
SELECT name, salary FROM employees
ORDER BY salary DESC;
-- Multi-column: by dept A-Z, then salary high-low
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;Common Mistakes
Assuming result rows have a guaranteed order without ORDER BY. The database engine may return rows in any order. Never rely on implicit ordering in production queries.
Interview Tips
Sorting by column position (ORDER BY 2) is valid SQL but avoid it in production — column order can change. Interviewers like to ask about NULL ordering: NULLs sort LAST in ASC, FIRST in DESC by default (varies by DB).
Practice
List all products sorted by category alphabetically, then by price from highest to lowest within each category.