Nulls Last, Nulls First
Postgres query sorting has a great feature,nulls first
/nulls last
, that helps us specify where in a query result null values appear.
Nulls in Postgres are sorted as larger than any other value, so this is a descending sort containing null values (💀 == null):
example=# select * from users order by full_name desc;
full_name
--------------
💀
💀
💀
Tracy Jordan
Liz Lemon
Jack Donaghy
Reverse the null position with nulls last
:
example=# select * from users order by full_name desc nulls last;
full_name
--------------
Tracy Jordan
Liz Lemon
Jack Donaghy
💀
💀
💀
(6 rows)
Here's the opposite query, ascending:
example=# select * from users order by full_name asc;
full_name
--------------
Jack Donaghy
Liz Lemon
Tracy Jordan
💀
💀
💀
(6 rows)
Now, reverse the null position with nulls first
:
example=# select * from users order by full_name asc nulls first;
full_name
--------------
💀
💀
💀
Jack Donaghy
Liz Lemon
Tracy Jordan
(6 rows)
Lots of ways to explore our data.
Tweet