ORDER BY with NULL values behavior in SQL - Time & Space Complexity
When sorting data with ORDER BY in SQL, the time it takes depends on how many rows there are.
We want to understand how sorting with NULL values affects the work the database does.
Analyze the time complexity of this SQL query:
SELECT id, name, score
FROM students
ORDER BY score NULLS LAST;
This query sorts students by their score, placing NULL scores at the end.
Look at what repeats during sorting:
- Primary operation: Comparing rows to order them by score.
- How many times: Comparisons happen many times, depending on the sorting method and number of rows.
Sorting work grows as the number of rows increases:
| 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 rows times log of rows.
Time Complexity: O(n log n)
This means sorting takes more time as rows increase, but not as fast as checking every pair; it grows in a balanced way.
[X] Wrong: "Sorting with NULL values is faster or slower than sorting without NULLs because NULLs are special."
[OK] Correct: NULLs only affect where rows appear, but sorting still compares all rows similarly, so time grows the same way.
Understanding how sorting scales helps you explain database performance clearly and confidently in real situations.
"What if we added an index on the score column? How would that change the time complexity of sorting with ORDER BY?"