Sub topic 12
Sorting NULLs: NULLS FIRST and NULLS LAST
Assume you know basic SELECT, ORDER BY, and NULL tests. This chapter focuses on controlling where missing values appear in sorted results.
Why NULL Ordering Needs Attention
NULL does not represent a number, an empty string, or zero. It represents a missing, unknown, or inapplicable value. A database cannot always place it naturally among ordinary values.
The default position of NULL depends on the database system and sort direction. For example, one system may place NULL values first in ascending order, while another places them last. Relying on the default can make reports behave differently after a database migration.
Use NULLS FIRST or NULLS LAST when the position matters.
WITH employees(name, commission) AS (
VALUES
('Ada', NULL),
('Ben', 100.00),
('Cy', NULL),
('Di', 300.00)
)
SELECT name, commission
FROM employees
ORDER BY commission DESC NULLS LAST;This sorts known commissions from highest to lowest. Employees without a commission appear at the end.
To put missing values first, change the final clause:
ORDER BY commission DESC NULLS FIRST;The same options work with ascending order:
WITH employees(name, commission) AS (
VALUES
('Ada', NULL),
('Ben', 100.00),
('Cy', NULL),
('Di', 300.00)
)
SELECT name, commission
FROM employees
ORDER BY commission ASC NULLS LAST;Here, the result starts with 100.00, then 300.00 is not shown first because ascending order normally places smaller known values before larger ones. The NULL rows appear after all known values because of NULLS LAST.
Sort Rules with Multiple Columns
You can set null ordering separately for each sort expression. A common report groups rows by status and then sorts dates, keeping missing dates at the end.
SELECT customer_id, status, shipped_at
FROM orders
ORDER BY status ASC,
shipped_at ASC NULLS LAST;The database first sorts by status. Within each status, it sorts shipped_at from oldest to newest and puts undelivered orders, represented by NULL, last.
If several rows still compare equally, add another column as a tie-breaker:
ORDER BY shipped_at ASC NULLS LAST, customer_id ASC;Database Differences and Portable Alternatives
NULLS FIRST and NULLS LAST are supported by PostgreSQL, Oracle, and modern SQLite. Support and default behavior vary across database systems, so check the documentation for your system.
For a portable technique, sort by a CASE expression first:
ORDER BY
CASE WHEN commission IS NULL THEN 1 ELSE 0 END,
commission ASC;The CASE expression produces 0 for known values and 1 for NULL values. Since 0 sorts first, known commissions appear before missing commissions. Reverse the numbers to place NULL values first.
Exercise
Write an ORDER BY clause that sorts newest last_login values first and puts users who have never logged in at the end.
Show answer
ORDER BY last_login DESC NULLS LAST