CASE in SELECT for computed columns in SQL - Time & Space Complexity
We want to understand how the time to run a SQL query changes when using CASE statements in SELECT for computed columns.
Specifically, how does adding conditional logic affect the work the database does?
Analyze the time complexity of the following SQL query.
SELECT
employee_id,
salary,
CASE
WHEN salary > 70000 THEN 'High'
WHEN salary > 40000 THEN 'Medium'
ELSE 'Low'
END AS salary_level
FROM employees;
This query classifies each employee's salary into categories using CASE in the SELECT clause.
Look for repeated work done by the query.
- Primary operation: The database reads each row from the employees table.
- How many times: Once per row, it evaluates the CASE conditions to assign a category.
As the number of employees grows, the database must check each row's salary once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 salary checks |
| 100 | 100 salary checks |
| 1000 | 1000 salary checks |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles the checks.
Time Complexity: O(n)
This means the query time grows linearly with the number of rows in the table.
[X] Wrong: "Using CASE makes the query much slower because it adds complex logic."
[OK] Correct: The CASE statement just checks conditions once per row, so it adds a small, fixed amount of work per row, not extra loops or scans.
Understanding how conditional logic affects query time helps you explain your choices clearly and shows you know how databases handle row-by-row operations.
What if we added a JOIN to another table inside the query? How would the time complexity change?