ORDER BY Clause
SQL · Sorting Rows
Theory
Tables have no guaranteed row order, so without ORDER BY the database can return rows in any order and that order can change between runs. ORDER BY sorts the final result by one or more columns or expressions. ASC (ascending, the default) goes smallest to largest or A to Z; DESC reverses it.
With several sort keys, the first key decides the order and later keys only break ties. ORDER BY dept ASC, salary DESC groups rows by department and, inside each department, puts the highest salary first. Because ORDER BY runs after SELECT, it can use column aliases. NULLs sort first in some engines (SQLite, MySQL, SQL Server) and last in others (PostgreSQL, Oracle); many engines support NULLS FIRST / NULLS LAST to control it.
Why we use it
Reports, top-N lists, pagination and readable output all need a predictable order. ORDER BY is the only way to guarantee that order; relying on how rows happen to come back leads to flaky results.
When to use it
Use ORDER BY whenever row order matters to the reader or to LIMIT/FETCH. Skip it inside subqueries or views where order is ignored anyway, and avoid sorting huge results you do not need, because sorting costs time.
How it works
- Result rows are ready after SELECT
- Compare rows on the first sort key
- Do two rows tie on that key? Yes: Compare on the next sort key. No: This key decides the order.
- Apply ASC or DESC per key
- Place NULLs first or last as the engine (or NULLS FIRST/LAST) says
- Return sorted rows
Syntax
SELECT columns
FROM table
ORDER BY column [ASC|DESC];Example
SELECT name, salary FROM employees ORDER BY salary DESC;Key points
- ASC is the default direction
- Multiple keys sort in priority order; later keys only break ties
- Can sort by aliases or expressions because it runs after SELECT
- Without ORDER BY, row order is not guaranteed
- NULL placement differs by engine; use NULLS FIRST/LAST where supported