Sub topic 3
Sorting results with ORDER BY
This chapter assumes you can write a SELECT ... FROM query and filter rows with WHERE. You should also know that NULL means "no value," which differs from zero or an empty string. The examples use an employees table with the columns first_name, last_name, department, salary, and manager_id.
Sorting results with ORDER BY
ORDER BY sorts the rows of a query result. It appears last in the statement, after FROM and WHERE. Without it, a database returns rows in no guaranteed order.
SELECT first_name, salary
FROM employees
ORDER BY salary;Ascending is the default direction. Write ASC to state it explicitly, or DESC for descending order.
Sorting by several columns, ascending and descending
The columns in ORDER BY form a sort key, read from left to right. The second column breaks ties in the first, and each column can have its own direction.
SELECT first_name, last_name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;Within each department, the highest salary appears first.
Where NULL values appear in sorted output
The SQL standard does not fix where NULL sorts, so each database decides. PostgreSQL treats NULL as larger than any value, so it sorts last in ascending order. MySQL and SQLite treat NULL as smaller, so it sorts first in ascending order.
Top-N queries: ORDER BY with LIMIT or FETCH FIRST
A top-N query returns the first N rows after sorting. PostgreSQL, MySQL, and SQLite use LIMIT. The SQL standard form, FETCH FIRST n ROWS ONLY, works in PostgreSQL and in Oracle 12c and later.
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 5;| Database | Five highest salaries |
|---|---|
| PostgreSQL | `LIMIT 5` or `FETCH FIRST 5 ROWS ONLY` |
| MySQL | `LIMIT 5` |
| SQLite | `LIMIT 5` |
| Oracle 12c and later | `FETCH FIRST 5 ROWS ONLY` |
If several rows tie at the cutoff, the database may pick any of them. Add a unique column, such as employee_id, as a final sort key to make the result repeatable.
Why clause order matters: how a query is evaluated
The order you write clauses differs from the order the database evaluates them. Logically, the database processes FROM, then WHERE, then SELECT, then ORDER BY, then LIMIT. This explains why an alias works in ORDER BY but not in WHERE. SELECT names the alias before sorting, but WHERE runs earlier.
SELECT first_name, salary * 12 AS annual_salary
FROM employees
WHERE salary * 12 > 480000
ORDER BY annual_salary DESC;Exercise
Why does WHERE annual_salary > 480000 fail when annual_salary is defined in the SELECT list?
Show answer
WHERE runs before SELECT, so the alias does not exist yet. Repeat the expression salary * 12 in the WHERE clause instead.