Explain Codes LogoExplain Codes Logo

Sort by column ASC, but NULL values first?

sql
nulls-first
query-optimization
case-statement
Anton ShumikhinbyAnton Shumikhin·Aug 5, 2024
TLDR

The quickest way to sort with NULLs first using an ORDER BY and CASE is:

SELECT * FROM your_table ORDER BY CASE WHEN column_name IS NULL THEN 0 ELSE 1 END, column_name ASC;

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:

ORDER BY column_name ASC NULLS FIRST;

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:

ORDER BY column_name DESC NULLS LAST;

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:

CREATE INDEX idx_last_updated ON your_table (last_updated);

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:

SELECT * FROM your_table ORDER BY CASE WHEN column_name IS NULL THEN 1 /* lead, NULLs! */ ELSE 2 END, column_name ASC;

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.