0
0
SQLquery~5 mins

Operator precedence in WHERE in SQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Operator precedence in WHERE
O(n)
Understanding Time Complexity

We want to understand how the order of operations in a WHERE clause affects how many checks the database does.

How does the way conditions are grouped change the work done when filtering data?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

SELECT *
FROM Employees
WHERE (department = 'Sales' AND salary > 50000) OR experience > 5;

This query filters employees who are either in Sales with salary above 50000 or have more than 5 years of experience.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Checking each row against the WHERE conditions.
  • How many times: Once per row in the Employees table.
How Execution Grows With Input

Each row is checked one time through the conditions, so the work grows as the number of rows grows.

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

Pattern observation: The number of checks grows directly with the number of rows.

Final Time Complexity

Time Complexity: O(n)

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

Common Mistake

[X] Wrong: "Changing the order of AND and OR in WHERE changes how many rows are checked."

[OK] Correct: The database still checks every row once; only the logic grouping changes which rows pass, not how many are checked.

Interview Connect

Understanding how conditions combine helps you write clear queries and reason about their performance, a useful skill in real projects.

Self-Check

"What if we added parentheses to change the condition grouping? How would that affect the time complexity?"