Sort by column ASC, but NULL values first?
The quickest way to sort with NULLs first using an ORDER BY and CASE is:
This little piece of genius makes NULLs show up first by ranking them as the lowest value.
Using Postgres Modifiers – NULLS FIRST and NULLS LAST
NULLS at the starting line
In PostgreSQL, handling NULLs is as easy as:
This sets NULLs as high priority in line to be displayed.
NULLS taking a backseat
To place NULLs at the end, say after sorting values, use:
NULLs are now chillaxing at the back!
Index Masters – Optimizing your Queries
Index for the Fast Lane
Indexes can be the fast lane your queries need. Creating them on a last_updated
column can be a gamechanger:
The index tells Postgres: "Please sort this column first, thanks 😊."
Reverse Gear: DESC Order Queries
Postgres can read btree indexes in reverse, perfect for DESC
queries. Think of it as a fancy SQL backflip.
NULLs in the Query Plan Maze
Your query plan may have secret passages (unexpected handling of NULLs) that may impact performance. Be the Harry Potter in the SQL magic world.
Raise your 'CASE'. Control those NULLs.
Prioritize NULLs using CASE
Want to demote non-NULLs and uplift your NULLs? Use a CASE statement:
Who knew you could move mountains (or change sorting order)
Views from the SQL Tower
Creating a view that includes your sorting logic simplifies future queries, but watch out for the performance longview.
PostgreSQL Deep Dive
Dive into PostgreSQL's approach to NULL handling. It's like the Mariana Trench of SQL sorting.
Was this article helpful?