Operator precedence in WHERE in SQL - Time & Space 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?
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 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.
Each row is checked one time through the conditions, so the work grows as the number of rows grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of checks grows directly with the number of rows.
Time Complexity: O(n)
This means the time to filter grows linearly with the number of rows in the table.
[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.
Understanding how conditions combine helps you write clear queries and reason about their performance, a useful skill in real projects.
"What if we added parentheses to change the condition grouping? How would that affect the time complexity?"