SQL
5 min read
BEGINNER
NULL ordering
Quick AnswerNULL represents missing or unknown information, not zero. Specify NULLS FIRST or NULLS LAST when the position of missing values matters.
Core idea
NULL represents missing or unknown information, not zero. Specify NULLS FIRST or NULLS LAST when the position of missing values matters.
Minimal example
sql
SELECT id, score FROM sort_scores ORDER BY score ASC NULLS FIRST, id;Expected SQLite rows:
text
2 | NULL4 | NULL3 | 01 | 10How it works
Use the supplemental sort_scores fixture. PostgreSQL 17 defaults to NULLS LAST for ASC and NULLS FIRST for DESC; SQLite defaults are the reverse. Both support explicit NULLS FIRST/LAST. Other engines may require a CASE expression, taught later.
Practical example
sql
SELECT id, score FROM sort_scores ORDER BY score DESC NULLS LAST, id;Expected SQLite rows:
text
1 | 103 | 02 | NULL4 | NULLCommon mistake and practice
Do not assume NULL sorts like zero. Change the first query to NULLS LAST and predict IDs 3, 1, 2, 4.