ORDER BY with NULLS FIRST and NULLS LAST in PostgreSQL - Time & Space Complexity
When sorting data in a database, it is important to understand how the sorting time grows as the data grows.
We want to know how adding NULLS FIRST or NULLS LAST affects the sorting time.
Analyze the time complexity of this query that sorts data with NULL values:
SELECT id, score
FROM results
ORDER BY score NULLS LAST;
This query sorts rows by the score column, placing NULL values at the end.
Sorting involves comparing and ordering rows repeatedly.
- Primary operation: Comparing two rows' score values to decide order.
- How many times: Many comparisons happen, depending on the number of rows.
Sorting time grows as the number of rows increases, but not simply by doubling.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 30 comparisons |
| 100 | About 700 comparisons |
| 1000 | About 10,000 comparisons |
Pattern observation: The number of comparisons grows faster than the number of rows, roughly like n times log n.
Time Complexity: O(n log n)
This means sorting takes more time as data grows, but it is still efficient for large data sets.
[X] Wrong: "Adding NULLS FIRST or NULLS LAST makes sorting much slower because it adds extra steps."
[OK] Correct: The NULLS FIRST or NULLS LAST option only changes how NULLs are treated during comparisons, not the overall sorting method or its time complexity.
Understanding how sorting scales with data size helps you explain query performance clearly and confidently.
What if we added an index on the score column? How would that affect the time complexity of this ORDER BY query?
Practice
ORDER BY column_name NULLS FIRST do in a PostgreSQL query?Solution
Step 1: Understand ORDER BY behavior with NULLS FIRST
TheORDER BYclause sorts rows by the specified column. AddingNULLS FIRSTmeans any NULL values in that column appear before non-NULL values.Step 2: Confirm the effect on sorting
So, the rows with NULL incolumn_namecome first, then the rest sorted normally.Final Answer:
It sorts the rows by column_name and places NULL values at the beginning. -> Option DQuick Check:
NULLS FIRST means NULLs appear first [OK]
- Confusing NULLS FIRST with NULLS LAST
- Thinking NULLs are ignored in sorting
- Assuming NULLS FIRST causes errors
score in ascending order with NULL values last?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 byNULLS FIRSTorNULLS 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 AQuick Check:
Column, order, then NULLS position [OK]
- Placing NULLS FIRST/LAST before column name
- Swapping ASC/DESC and NULLS keywords
- Using invalid keyword order causing syntax errors
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;?Solution
Step 1: Understand DESC with NULLS FIRST
Sorting bygrade DESCmeans highest grades first. AddingNULLS FIRSTplaces 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 AQuick Check:
DESC sorts high to low, NULLS FIRST puts NULLs upfront [OK]
- Placing NULLs at the end despite NULLS FIRST
- Sorting grades ascending instead of descending
- Mixing order of NULLs and values
SELECT * FROM employees ORDER BY salary NULLS FIRST DESC;What is the error and how to fix it?
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
ChangeORDER BY salary NULLS FIRST DESCtoORDER BY salary DESC NULLS FIRSTto fix the syntax error.Final Answer:
The order of NULLS FIRST and DESC is wrong; use ORDER BY salary DESC NULLS FIRST. -> Option CQuick Check:
Column, order, then NULLS position [OK]
- Placing NULLS FIRST before ASC/DESC
- Assuming NULLS FIRST is invalid with DESC
- Missing ASC/DESC keyword
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?Solution
Step 1: Sort by price ascending with NULLs last
UseORDER BY price ASC NULLS LASTto sort prices low to high and put NULLs at the end.Step 2: Add secondary sort by name ascending
After sorting by price, addname ASCto sort products with the same price alphabetically.Final Answer:
SELECT * FROM products ORDER BY price ASC NULLS LAST, name ASC; -> Option BQuick Check:
Price ASC NULLS LAST, then name ASC [OK]
- Placing NULLS LAST before ASC
- Applying NULLS LAST to wrong column
- Using NULLS FIRST instead of NULLS LAST
Ready to prove it?
Pass the test and this pattern moves unknown
