We use ORDER BY to sort data. Sometimes, data has empty values called NULLs. NULLS FIRST and NULLS LAST help decide if these empty values come at the start or end of the list.
ORDER BY with NULLS FIRST and NULLS LAST in PostgreSQL
SELECT column1, column2 FROM table_name ORDER BY column_name [ASC|DESC] NULLS {FIRST|LAST};
ASC means ascending order (smallest to largest), DESC means descending (largest to smallest).
NULLS FIRST puts NULL values at the beginning, NULLS LAST puts them at the end.
SELECT name, score FROM players ORDER BY score DESC NULLS LAST;
SELECT product, price FROM products ORDER BY price ASC NULLS FIRST;
SELECT employee, manager_id FROM employees ORDER BY manager_id ASC NULLS FIRST;
This creates a temporary table with some items and their ratings. Some ratings are NULL (unknown). The query sorts items by rating from highest to lowest, placing items with no rating at the end.
CREATE TEMP TABLE items (id SERIAL, name TEXT, rating INT); INSERT INTO items (name, rating) VALUES ('Item A', 5), ('Item B', NULL), ('Item C', 3), ('Item D', NULL), ('Item E', 4); SELECT name, rating FROM items ORDER BY rating DESC NULLS LAST;
By default, in PostgreSQL, ORDER BY ASC puts NULLs first, and ORDER BY DESC puts NULLs last.
Using NULLS FIRST or NULLS LAST lets you control this behavior explicitly.
This helps make your sorted lists clearer and easier to understand.
ORDER BY sorts data by columns.
NULLS FIRST and NULLS LAST decide where empty (NULL) values appear in the sorted list.
Use them to make your data lists more meaningful and easier to read.