← Back to PostgreSQL, page 2

postgresql-0025 · Easy fresher

Control where NULLs appear when sorting with NULLS FIRST and NULLS LAST.

PostgreSQL treats NULL as larger than any value, so NULLs come last in ascending order and first in descending order. NULLS FIRST or NULLS LAST overrides this per sort key. An index can serve such a sort only if it was created with the same NULLS ordering.

Full answer

Sample schema and data:

sql
CREATE TABLE tasks (title text, due date);
INSERT INTO tasks VALUES ('report', '2026-12-10'), ('backlog', NULL), ('invoice', '2026-12-05'), ('idea', NULL);
sql
SELECT title, due FROM tasks ORDER BY due, title;

Output:

text
  title  |    due
---------+------------
 invoice | 2026-12-05
 report  | 2026-12-10
 backlog | NULL
 idea    | NULL
(4 rows)
sql
SELECT title, due FROM tasks ORDER BY due DESC, title;

PostgreSQL returns:

text
  title  |    due
---------+------------
 backlog | NULL
 idea    | NULL
 report  | 2026-12-10
 invoice | 2026-12-05
(4 rows)
sql
SELECT title, due FROM tasks ORDER BY due DESC NULLS LAST, title;

Result on PostgreSQL 17:

text
  title  |    due
---------+------------
 report  | 2026-12-10
 invoice | 2026-12-05
 backlog | NULL
 idea    | NULL
(4 rows)

Ascending order puts the two undated tasks last, and descending order puts them first, which is often not what a 'latest first' screen wants. DESC NULLS LAST lists the dated tasks newest first and the undated ones at the end. The title is a tie-breaker so rows with equal dates come out in a stable order. MySQL and SQL Server sort NULLs first in ascending order, so explicit NULLS clauses also make queries portable in intent. For an index-backed sort, create the index as ON tasks (due DESC NULLS LAST).

sql
CREATE TABLE tasks (title text, due date);
INSERT INTO tasks VALUES ('report', '2026-12-10'), ('backlog', NULL), ('invoice', '2026-12-05'), ('idea', NULL);

SELECT title, due FROM tasks ORDER BY due, title;

SELECT title, due FROM tasks ORDER BY due DESC, title;

SELECT title, due FROM tasks ORDER BY due DESC NULLS LAST, title;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • NULLs sort as largest by default
  • DESC puts NULLs first
  • NULLS FIRST/LAST overrides per key
  • Indexes must match the NULL order
  • Add tie-breakers for stable order

Common mistakes

  • Showing undated items at the top of a newest-first list
  • Assuming all databases order NULLs the same

Follow-ups

  • How would you sort NULLs last on a database without NULLS LAST?
  • Does NULLS LAST affect index usage?

Tips

  • Show the DESC surprise