0
0
SQLquery~5 mins

CASE in SELECT for computed columns in SQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: CASE in SELECT for computed columns
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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

As the number of employees grows, the database must check each row's salary once.

Input Size (n)Approx. Operations
1010 salary checks
100100 salary checks
10001000 salary checks

Pattern observation: The work grows directly with the number of rows; doubling rows doubles the checks.

Final Time Complexity

Time Complexity: O(n)

This means the query time grows linearly with the number of rows in the table.

Common Mistake

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

Interview Connect

Understanding how conditional logic affects query time helps you explain your choices clearly and shows you know how databases handle row-by-row operations.

Self-Check

What if we added a JOIN to another table inside the query? How would the time complexity change?