0
0
SQLquery~5 mins

ORDER BY with NULL values behavior in SQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: ORDER BY with NULL values behavior
O(n log n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Sorting work grows as the number of rows increases:

Input Size (n)Approx. Operations
10About 30 comparisons
100About 700 comparisons
1000About 10,000 comparisons

Pattern observation: The number of comparisons grows faster than the number of rows, roughly like rows times log of rows.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how sorting scales helps you explain database performance clearly and confidently in real situations.

Self-Check

"What if we added an index on the score column? How would that change the time complexity of sorting with ORDER BY?"