Sub topic 12
Sorting NULLs: NULLS FIRST and NULLS LAST
This chapter assumes you can write SELECT, WHERE, and ORDER BY queries. It also assumes you know that NULL marks a missing value and that comparisons with NULL yield UNKNOWN. It uses the employees table from the earlier chapters. In that table Ada and Cy have a NULL commission, Ben has 100.00, and Di has 300.00.
Why NULL needs a sort rule
ORDER BY puts rows in order by comparing values. NULL is not a value, so commission < 100 is UNKNOWN for a NULL commission, and the database cannot rank NULL by comparison. The database still has to place those rows somewhere. The SQL standard says NULLs sort either before all non-NULL values or after all of them. The standard does not say which, so each database system picks its own default.
The standard does fix two things:
- All NULLs end up together in one block. They never mix in among the non-NULL values.
- Rows within that block are peers. The database may return them in any order unless you add a tiebreaker.
In ORDER BY, NULLs are treated as equal to each other, so they form one group. In WHERE, NULL = NULL is UNKNOWN. The sort uses a different rule from the filter.
The default placement differs by system
Two behaviors are common. Some systems treat NULL as larger than every value. Others treat it as smaller than every value. Direction then moves the NULLs from one end to the other.
| System | NULL treated as | `ASC` puts NULLs | `DESC` puts NULLs | `NULLS FIRST/LAST` syntax |
|---|---|---|---|---|
| PostgreSQL | Largest | Last | First | Yes |
| Oracle | Largest | Last | First | Yes |
| SQLite | Smallest | First | Last | Yes, since 3.30 |
| MySQL / MariaDB | Smallest | First | Last | No |
| SQL Server | Smallest | First | Last | No |
You rarely need to memorize this table. If the position of NULLs matters to your query, state it explicitly.
NULLS FIRST and NULLS LAST
Add NULLS FIRST or NULLS LAST after the direction. The clause applies to one sort key only, so each key in the list can have its own.
-- PostgreSQL, Oracle, SQLite 3.30+
SELECT name, commission
FROM employees
ORDER BY commission DESC NULLS LAST, name;The result is Di (300.00), Ben (100.00), Ada (NULL), Cy (NULL). The name tiebreaker makes the order of the two NULL rows predictable.
The opposite choice is just as valid. A "who still needs a commission figure?" report may want the gaps at the top:
SELECT name, commission
FROM employees
ORDER BY commission ASC NULLS FIRST, name;This returns Ada, Cy, Ben, Di.
Direction and NULL placement are independent. In PostgreSQL, ASC implies NULLS LAST and DESC implies NULLS FIRST. Because the two defaults are tied together, they are easy to forget. When you write DESC to get the highest values first, you also get the NULLs first, which is rarely what you want.
A common gotcha: top-N queries
The default behavior causes the most trouble in "top N" queries. On PostgreSQL, this query is meant to find the two highest commissions:
SELECT name, commission
FROM employees
ORDER BY commission DESC
LIMIT 2;Because DESC puts NULLs first there, the result is Ada and Cy, both with NULL. The two people with real commissions are cut off by LIMIT. The fix is one clause:
SELECT name, commission
FROM employees
ORDER BY commission DESC NULLS LAST
LIMIT 2;This returns Di and Ben. The same applies to FETCH FIRST 2 ROWS ONLY, TOP 2, and window functions such as ROW_NUMBER() OVER (ORDER BY commission DESC). The OVER clause takes the same NULLS FIRST/LAST option on systems that support it.
Emulating NULLS FIRST and NULLS LAST
MySQL, MariaDB, and SQL Server have no NULLS FIRST/LAST clause. The portable workaround is to sort on a separate flag first, then on the real column. A CASE expression works everywhere:
-- NULLS LAST on any system
SELECT name, commission
FROM employees
ORDER BY CASE WHEN commission IS NULL THEN 1 ELSE 0 END,
commission DESC,
name;The first sort key is 0 for rows with a commission and 1 for rows without one. All the non-NULL rows come first. Within them, commission DESC orders the values. The second key never has to compare a NULL against anything. To get NULLS FIRST, swap the 1 and the 0.
MySQL and MariaDB treat a comparison result as a number, so they allow a shorter form:
-- MySQL / MariaDB: IS NULL is 0 for non-NULL rows and 1 for NULL rows.
SELECT name, commission
FROM employees
ORDER BY commission IS NULL, commission DESC, name;Use commission IS NULL DESC instead to put NULLs first. This shorthand does not work on SQL Server, which does not accept a boolean expression there, so use the CASE form.
Sorting by a substituted value
Another approach is to sort by COALESCE:
SELECT name, commission
FROM employees
ORDER BY COALESCE(commission, 0) DESC, name;This treats a missing commission as zero. It is a different query, not just a placement choice, because a real commission of 0 and a NULL now tie. It is only correct when "missing" and the substitute value mean the same thing for your report. Avoid inventing sentinel values such as -1 or 999999 to force an order. A sentinel can collide with real data, and it hides the intent of the query from the next reader.
Sorting, indexes, and performance
A B-tree index stores its entries in sorted order, and NULLs are stored in that order too. A query can skip its sort step if the index order matches the ORDER BY, including NULL placement. Consider these cases:
- PostgreSQL can scan an index backward, so an index on
(commission)serves bothASC NULLS LASTandDESC NULLS FIRST. A query asking forASC NULLS FIRSTdoes not match it. It needs an index created as(commission NULLS FIRST). - Oracle works in a similar way, and its B-tree indexes do not contain rows where every indexed column is NULL. That can make a
NULLS FIRSTsort over a whole table unable to use the index. - A
CASEexpression inORDER BYis not a plain column, so the database usually cannot use a plain index for it. On large tables, the portable workaround can force a full sort. You can create an expression index in some systems, but check your system's documentation first.
Look at the query plan (EXPLAIN) before assuming an index helps. A plan with a separate sort step means the index order did not match.
NULLs in other places that sort
NULL placement also matters outside a plain ORDER BY:
- Compound queries. With
UNIONorINTERSECT, a singleORDER BYat the end sorts the combined result. The same NULL rules apply to it. - Multiple keys.
ORDER BY manager_id NULLS FIRST, namesorts by manager, puts the manager-less rows first, then breaks ties by name. Each key has its own NULL placement. - Ordering by position.
ORDER BY 2 DESC NULLS LASTrefers to the second selected column and accepts the same clause. - Aggregate ordering. Where a database lets you order inside an aggregate, such as
STRING_AGG(name, ',' ORDER BY commission DESC NULLS LAST)in PostgreSQL, the same rules apply there.
DISTINCT and GROUP BY treat all NULLs as one group, as covered in the previous chapter. Their output order is not guaranteed unless you add ORDER BY.
Checking your understanding
Exercise
On PostgreSQL, SELECT name FROM employees ORDER BY commission DESC LIMIT 1; is meant to return the employee with the highest commission. Why does it return Ada or Cy instead of Di, and how do you fix it?
Show answer
In PostgreSQL, NULL is treated as larger than every value, so DESC puts NULLs first. LIMIT 1 keeps the first row, which has a NULL commission (Ada or Cy, since their order is not defined). Fix it with ORDER BY commission DESC NULLS LAST LIMIT 1, which returns Di (300.00).
Exercise
Write a query for SQL Server that lists employees by commission from lowest to highest, with employees who have no commission at the end, and ties broken by name.
Show answer
SQL Server has no NULLS LAST, so sort first on a flag: SELECT name, commission FROM employees ORDER BY CASE WHEN commission IS NULL THEN 1 ELSE 0 END, commission ASC, name;. This returns Ben (100.00), Di (300.00), Ada (NULL), Cy (NULL).
Exercise
A colleague replaces ORDER BY commission DESC NULLS LAST with ORDER BY COALESCE(commission, -1) DESC. Give one reason this can go wrong.
Show answer
The substitute -1 is a value that could also appear in real data, so a genuine commission of -1 would tie with the NULL rows. The query also hides the intent, and the expression may stop the database from using an index on commission. Writing NULLS LAST says what is meant.