CASE in ORDER BY in SQL - Time & Space Complexity
We want to understand how using CASE inside ORDER BY affects how long a query takes to run.
Specifically, how does sorting with conditions grow as the data gets bigger?
Analyze the time complexity of the following code snippet.
SELECT id, name, status
FROM users
ORDER BY CASE
WHEN status = 'active' THEN 1
WHEN status = 'pending' THEN 2
ELSE 3
END, name;
This query sorts users first by a custom order of their status, then by their name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The database compares each row's status and name to sort all rows.
- How many times: It compares pairs of rows multiple times during sorting, roughly proportional to the number of rows times log of the number of rows.
As the number of rows grows, the sorting work grows faster than just looking at each row once.
| 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 a bit faster than the number of rows, because sorting needs to compare many pairs.
Time Complexity: O(n log n)
This means the time to sort grows a little more than linearly as the data grows, because sorting compares many pairs of rows.
[X] Wrong: "Using CASE in ORDER BY makes the query run in linear time because it just checks each row once."
[OK] Correct: Sorting always requires comparing rows multiple times, so the total work grows faster than just looking at each row once.
Understanding how sorting with conditions affects performance helps you explain query costs clearly and shows you know how databases handle ordering.
"What if we removed the CASE and just sorted by status directly? How would the time complexity change?"