Postgres has the NULLS FIRST | LAST
modifiers for ORDER BY
expression:
... ORDER BY last_updated NULLS FIRST
The typical use case is with descending sort order (DESC
), which produces the complete inversion of the default ascending order (ASC
) with null values first - which is often not desirable. To sort NULL
values last:
... ORDER BY last_updated DESC NULLS LAST
To support the query with an index, make it match:
CREATE INDEX foo_idx ON tbl (last_updated DESC NULLS LAST);
Postgres can read btree indexes backwards, but for some query plans it matters where NULL
values are appended. See:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…