I need to sort a PostgreSQL table ascending by a date/time field, e.g. last_updated
.
But that field is allowed to be empty or null and I want records with null in last_updated
come before non-null last_updated
.
Is this possible?
order by last_updated asc /* and null last_updated records first ?? */
PostgreSQL provides the
NULLS FIRST | LAST
keywords for theORDER BY
clause to cater for that need exactly:A typical use case is with descending sort order (
DESC
), which yields the complete inversion of the default ascending order (ASC
) with null values first. Often not desirable - so, to keep null values last:To support the query with an index, make it match:
Postgres can read btree indexes backwards, but it matters where NULL values are appended.
You can create a custom ORDER BY using a CASE statement.
The CASE statement checks for your condition and assigns to rows which meet that condition a lower value than that which is assigned to rows which do not meet the condition.
It's probably easiest to understand given an example: