Saturday 9 June 2018

sql - PostgreSQL sort by datetime asc, null first?



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 ?? */

Answer



Postgres provides the NULLS FIRST | LAST keywords for the ORDER BY clause to cater for that need exactly:



... ORDER BY last_updated NULLS FIRST


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:



... 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 it matters where NULL values are appended.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...