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
1
Create the books table and insert data
Create a table called books with columns title as text and pub_year as integer. Then insert these exact rows: ('The Hobbit', 1937), ('1984', 1949), ('Unknown Book', NULL), ('Brave New World', 1932), ('Future Book', NULL).
PostgreSQL
Hint
Use CREATE TABLE to make the table, then INSERT INTO to add the rows exactly as given.
2
Write a query to order books with NULL publication years first
Write a SQL query to select all columns from books ordered by pub_year with NULL values appearing first. Use ORDER BY pub_year NULLS FIRST.
PostgreSQL
Hint
Use ORDER BY pub_year NULLS FIRST to put NULL values at the top.
3
Write a query to order books with NULL publication years last
Write a SQL query to select all columns from books ordered by pub_year with NULL values appearing last. Use ORDER BY pub_year NULLS LAST.
PostgreSQL
Hint
Use ORDER BY pub_year NULLS LAST to put NULL values at the bottom.
4
Add a final query to show books ordered by title ascending
Write a SQL query to select all columns from books ordered by title in ascending alphabetical order.
PostgreSQL
Hint
Use ORDER BY title ASC to sort books alphabetically by title.
Practice
(1/5)
1. What does ORDER BY column_name NULLS FIRST do in a PostgreSQL query?
easy
A. It ignores NULL values while sorting by column_name.
B. It sorts the rows by column_name and places NULL values at the end.
C. It causes a syntax error because NULLS FIRST is not valid.
D. It sorts the rows by column_name and places NULL values at the beginning.
Solution
Step 1: Understand ORDER BY behavior with NULLS FIRST
The ORDER BY clause sorts rows by the specified column. Adding NULLS FIRST means any NULL values in that column appear before non-NULL values.
Step 2: Confirm the effect on sorting
So, the rows with NULL in column_name come first, then the rest sorted normally.
Final Answer:
It sorts the rows by column_name and places NULL values at the beginning. -> Option D
Quick Check:
NULLS FIRST means NULLs appear first [OK]
Hint: NULLS FIRST puts empty values at the top of the list [OK]
Common Mistakes:
Confusing NULLS FIRST with NULLS LAST
Thinking NULLs are ignored in sorting
Assuming NULLS FIRST causes errors
2. Which of the following is the correct syntax to sort a table by column score in ascending order with NULL values last?
easy
A. SELECT * FROM table ORDER BY score ASC NULLS LAST;
B. SELECT * FROM table ORDER BY score NULLS LAST ASC;
C. SELECT * FROM table ORDER BY NULLS LAST score ASC;
D. SELECT * FROM table ORDER BY score ASC LAST NULLS;
Solution
Step 1: Recall correct ORDER BY syntax with NULLS LAST
The correct syntax places the column name first, then the sort order (ASC or DESC), followed by NULLS FIRST or NULLS LAST.
Step 2: Check each option
SELECT * FROM table ORDER BY score ASC NULLS LAST; follows this order: score ASC NULLS LAST. Others mix the order or use invalid syntax.
Final Answer:
SELECT * FROM table ORDER BY score ASC NULLS LAST; -> Option A
Quick Check:
Column, order, then NULLS position [OK]
Hint: Order: column, ASC/DESC, then NULLS FIRST/LAST [OK]
Common Mistakes:
Placing NULLS FIRST/LAST before column name
Swapping ASC/DESC and NULLS keywords
Using invalid keyword order causing syntax errors
3. Given the table students with column grade containing values (NULL, 85, 90, NULL, 75), what is the order of grade values after running: SELECT grade FROM students ORDER BY grade DESC NULLS FIRST;?
medium
A. [NULL, NULL, 90, 85, 75]
B. [90, 85, 75, NULL, NULL]
C. [75, 85, 90, NULL, NULL]
D. [NULL, 90, 85, 75, NULL]
Solution
Step 1: Understand DESC with NULLS FIRST
Sorting by grade DESC means highest grades first. Adding NULLS FIRST places NULL values before all grades.
Step 2: Arrange values accordingly
NULLs come first: [NULL, NULL], then grades in descending order: 90, 85, 75.
Final Answer:
[NULL, NULL, 90, 85, 75] -> Option A
Quick Check:
DESC sorts high to low, NULLS FIRST puts NULLs upfront [OK]
Hint: NULLS FIRST always puts NULLs before sorted values [OK]
Common Mistakes:
Placing NULLs at the end despite NULLS FIRST
Sorting grades ascending instead of descending
Mixing order of NULLs and values
4. You wrote this query but it gives a syntax error: SELECT * FROM employees ORDER BY salary NULLS FIRST DESC; What is the error and how to fix it?
medium
A. The column name salary is missing ASC or DESC.
B. NULLS FIRST cannot be used with DESC; remove NULLS FIRST.
C. The order of NULLS FIRST and DESC is wrong; use ORDER BY salary DESC NULLS FIRST.
D. You must use parentheses around NULLS FIRST and DESC.
Solution
Step 1: Identify correct keyword order in ORDER BY
The correct syntax is: column name, then ASC or DESC, then NULLS FIRST or NULLS LAST.
Step 2: Fix the query
Change ORDER BY salary NULLS FIRST DESC to ORDER BY salary DESC NULLS FIRST to fix the syntax error.
Final Answer:
The order of NULLS FIRST and DESC is wrong; use ORDER BY salary DESC NULLS FIRST. -> Option C
Quick Check:
Column, order, then NULLS position [OK]
Hint: Put ASC/DESC before NULLS FIRST/LAST [OK]
Common Mistakes:
Placing NULLS FIRST before ASC/DESC
Assuming NULLS FIRST is invalid with DESC
Missing ASC/DESC keyword
5. You have a table products with a price column containing some NULLs. You want to list products sorted by price ascending, but show NULL prices at the end. Then, for products with the same price, sort by name ascending. Which query achieves this?
hard
A. SELECT * FROM products ORDER BY price NULLS LAST ASC, name ASC;
B. SELECT * FROM products ORDER BY price ASC NULLS LAST, name ASC;
C. SELECT * FROM products ORDER BY price ASC, name ASC NULLS LAST;
D. SELECT * FROM products ORDER BY price ASC NULLS FIRST, name ASC;
Solution
Step 1: Sort by price ascending with NULLs last
Use ORDER BY price ASC NULLS LAST to sort prices low to high and put NULLs at the end.
Step 2: Add secondary sort by name ascending
After sorting by price, add name ASC to sort products with the same price alphabetically.
Final Answer:
SELECT * FROM products ORDER BY price ASC NULLS LAST, name ASC; -> Option B
Quick Check:
Price ASC NULLS LAST, then name ASC [OK]
Hint: Chain ORDER BY: main column with NULLS, then tie-breaker column [OK]
Common Mistakes:
Placing NULLS LAST before ASC
Applying NULLS LAST to wrong column
Using NULLS FIRST instead of NULLS LAST
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.