Sub topic 13
Where NULL values appear in sorted output
This chapter covers where rows with a missing value land when you sort. It assumes you can write a basic ORDER BY with ASC and DESC, and that you know NULL marks a missing value that you test with IS NULL. The examples use one small table, so you can run them in PostgreSQL, MySQL, or SQLite and compare the results.
Why NULL ordering needs a decision
Sorting needs a total order, meaning every pair of values can be ranked. NULL is not a value. It means "unknown", so NULL < 5 and NULL > 5 both evaluate to unknown. Yet a sorted result must put NULL rows somewhere.
The SQL standard resolves this in two parts:
- All NULLs are treated as equal to each other for sorting. They form one group, called peers.
- That group sorts either before or after all non-NULL values. The standard does not say which, so each database chooses its own default.
The same query can therefore return rows in a different order on two databases. Code that moves between engines needs to say where NULLs go.
A table to experiment with
Run this setup script first. It works in PostgreSQL, MySQL, and SQLite.
CREATE TABLE employees (
employee_id INTEGER PRIMARY KEY,
first_name VARCHAR(50),
department VARCHAR(50),
salary INTEGER,
manager_id INTEGER
);
INSERT INTO employees (employee_id, first_name, department, salary, manager_id) VALUES
(1, 'Ana', 'Executive', 120000, NULL),
(2, 'Ben', 'Sales', 60000, 1),
(3, 'Cara', 'Sales', NULL, 2),
(4, 'Dev', 'Support', 45000, 2),
(5, 'Eli', 'Support', 52000, 2);Cara has no recorded salary. Ana has no manager, which makes sense for the head of the company.
The default placement differs by database
Run an ascending sort:
SELECT employee_id, first_name, salary
FROM employees
ORDER BY salary ASC;Some databases return Cara last, and others return her first:
| Database | NULLs in ASC order | NULLs in DESC order | Treats NULL as |
|---|---|---|---|
| PostgreSQL | Last | First | Larger than any value |
| Oracle | Last | First | Larger than any value |
| MySQL and MariaDB | First | Last | Smaller than any value |
| SQLite | First | Last | Smaller than any value |
| SQL Server | First | Last | Smaller than any value |
Each engine behaves as if NULL were either the largest or the smallest possible value. Reversing the sort direction then reverses the NULL position along with everything else.
On PostgreSQL, the query above gives this:
| employee_id | first_name | salary |
|---|---|---|
| 4 | Dev | 45000 |
| 5 | Eli | 52000 |
| 2 | Ben | 60000 |
| 1 | Ana | 120000 |
| 3 | Cara | NULL |
On MySQL or SQLite, the rows are the same except that Cara comes first.
Controlling placement with NULLS FIRST and NULLS LAST
The standard form is a modifier after the sort direction:
SELECT employee_id, first_name, salary
FROM employees
ORDER BY salary DESC NULLS LAST, employee_id;This works in PostgreSQL, Oracle, and SQLite 3.30.0 or later. The result puts Ana (120000), Ben (60000), Eli (52000), and Dev (45000) first and Cara (NULL) last, on every one of those engines.
You can set the modifier separately for each sort key:
SELECT first_name, department, manager_id
FROM employees
ORDER BY department ASC, manager_id ASC NULLS FIRST;MySQL, MariaDB, and SQL Server do not accept NULLS FIRST or NULLS LAST. Using the syntax there raises a syntax error. The next section gives a portable alternative.
A portable workaround for any database
You can sort on a computed flag before the real column. Use a CASE expression that returns 1 for NULL and 0 otherwise:
SELECT employee_id, first_name, salary
FROM employees
ORDER BY CASE WHEN salary IS NULL THEN 1 ELSE 0 END ASC,
salary DESC,
employee_id ASC;The first key splits the rows into two groups. Rows with a salary get 0 and sort first. Rows without a salary get 1 and sort last. The second key then orders the rows inside each group. The result is the same on every engine: Ana, Ben, Eli, Dev, Cara.
To put NULLs first instead, swap the values:
SELECT employee_id, first_name, salary
FROM employees
ORDER BY CASE WHEN salary IS NULL THEN 0 ELSE 1 END ASC,
salary DESC,
employee_id ASC;Why not COALESCE?
Another common idea is to replace NULL with a sentinel value:
SELECT employee_id, first_name, salary
FROM employees
ORDER BY COALESCE(salary, 0) DESC;This works only if the sentinel is outside the range of real data. If a real employee earns 0 (an unpaid intern, say), that person ties with the NULL rows and the two groups mix. A sentinel must also match the column's type. The CASE flag avoids both problems, so prefer it.
NULLs are peers, so add a tie-breaker
All NULLs compare as equal for sorting. The standard does not define their order inside the NULL group, and the database may return them in any order, even a different order between runs. The same applies to any set of rows with equal sort values.
If your output must be repeatable, finish the ORDER BY with a unique column, usually the primary key:
SELECT employee_id, first_name, manager_id
FROM employees
ORDER BY manager_id ASC NULLS LAST, employee_id ASC;Here Ben, Cara, Dev, and Eli all have manager 2 and Ana has NULL. Ben, Cara, Dev, and Eli come first, ordered by employee_id. Ana comes last. Without employee_id, the order of the four tied rows could change between runs.
Top-N queries are affected
NULL placement matters most when you combine sorting with a row limit. Consider "the three highest salaries":
SELECT first_name, salary
FROM employees
ORDER BY salary DESC
LIMIT 3;On MySQL and SQLite, NULLs come last in a descending sort, so you get Ana, Ben, and Eli. On PostgreSQL, NULLs come first in a descending sort, so you get Cara (NULL), Ana, and Ben. Cara's missing salary takes a place in the top three.
The fix is to say what you mean. Either exclude the missing values, or place them last explicitly:
SELECT first_name, salary
FROM employees
WHERE salary IS NOT NULL
ORDER BY salary DESC
LIMIT 3;SELECT first_name, salary
FROM employees
ORDER BY salary DESC NULLS LAST
LIMIT 3;The first form is portable. It also states clearly that rows without a salary are not candidates. Use the second form if you want NULL rows to fill the remaining slots when fewer than N rows have a value.
Related details worth knowing
- DISTINCT groups NULLs together.
SELECT DISTINCT manager_id FROM employeesreturns one NULL row, even if several employees have no manager. This is the same peer rule that sorting uses. - Expressions follow the same rules. If
salary * 12is computed on a NULL salary, the result is NULL, and it sorts with the NULLs. Sorting by an alias such asannual_salarybehaves the same way as sorting by the underlying expression. - Text, dates, and numbers behave alike. NULL placement does not depend on the column type.
- Each sort key is independent. In
ORDER BY a DESC, b ASC, the default NULL position forafollowsDESC, and the default forbfollowsASC. On PostgreSQL that means NULLs first foraand last forb.
Common mistakes
- Assuming one default for all databases. A query tested on SQLite may order differently when moved to PostgreSQL.
- Writing
ORDER BY salary = NULL. Comparing with=yields unknown for every row, so it sorts nothing. UseIS NULLinside aCASE. - Using NULLS LAST on MySQL or SQL Server. The syntax is a parse error there. Use the
CASEflag. - Leaving out a tie-breaker. The order of NULL rows, and of other equal rows, can differ between runs.
- Forgetting NULLs in top-N queries. A descending sort can fill the top slots with missing values.
Exercise
On PostgreSQL, the query SELECT first_name, salary FROM employees ORDER BY salary DESC LIMIT 2; returns Cara (NULL salary) and Ana. Rewrite it so it returns the two highest actual salaries and works on PostgreSQL, MySQL, and SQLite. Then explain why the original result differs on MySQL.
Show answer
Use SELECT first_name, salary FROM employees WHERE salary IS NOT NULL ORDER BY salary DESC LIMIT 2; which returns Ana (120000) and Ben (60000) on every engine. The original differs on MySQL because MySQL treats NULL as the smallest value, so a descending sort puts NULLs last and the top two rows are Ana and Ben. PostgreSQL treats NULL as the largest value, so a descending sort puts NULLs first.
Exercise
Write a query that lists employees ordered by manager_id ascending with NULL managers first, using only syntax that works on SQL Server and MySQL. Add a tie-breaker so the output is repeatable.
Show answer
SELECT employeeid, firstname, managerid FROM employees ORDER BY CASE WHEN managerid IS NULL THEN 0 ELSE 1 END ASC, managerid ASC, employeeid ASC; The CASE flag puts Ana (NULL manager) first. The employees with manager 2 follow, ordered by employeeid: Ben, Cara, Dev, and Eli. Ben's own managerid is 1, so he appears before the manager 2 group: the order is Ana, Ben, Cara, Dev, Eli.