Sorting Data with ORDER BY and NULLS FIRST / NULLS LAST in PostgreSQL
📖 Scenario: You are managing a small bookstore database. Some books have a known publication year, but others do not have this information yet, so their publication year is NULL. You want to list the books sorted by their publication year, but you want to control where the NULL values appear in the list.
🎯 Goal: Create a table called books with book titles and publication years. Then write two queries: one that sorts books by publication year with NULL values first, and another that sorts books by publication year with NULL values last.
📋 What You'll Learn
Create a table called
books with columns title (text) and pub_year (integer).Insert exactly these rows into
books: ('The Hobbit', 1937), ('1984', 1949), ('Unknown Book', NULL), ('Brave New World', 1932), ('Future Book', NULL).Write a query to select all columns from
books ordered by pub_year with NULL values first.Write a query to select all columns from
books ordered by pub_year with NULL values last.💡 Why This Matters
🌍 Real World
Sorting data with NULL values is common in real databases, such as when some information is missing or unknown. Controlling where NULLs appear helps make reports clearer.
💼 Career
Database developers and analysts often need to write queries that handle NULL values properly to ensure correct data presentation and analysis.
Progress0 / 4 steps