Comparison operators in MySQL - Time & Space Complexity
When using comparison operators in SQL, it's important to know how the time to run queries changes as data grows.
We want to see how the number of rows affects the work done when comparing values.
Analyze the time complexity of the following code snippet.
SELECT *
FROM employees
WHERE salary > 50000;
This query selects all employees whose salary is greater than 50,000 using a comparison operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking the salary value of each employee row against 50,000.
- How many times: Once for every row in the employees table.
As the number of employees grows, the database checks more rows one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 comparisons |
| 100 | 100 comparisons |
| 1000 | 1000 comparisons |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles comparisons.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of rows in the table.
[X] Wrong: "Comparison operators instantly find matching rows regardless of table size."
[OK] Correct: Without indexes, the database must check each row one by one, so more rows mean more work.
Understanding how comparisons scale helps you explain query performance clearly and shows you know how databases handle data.
"What if we added an index on the salary column? How would the time complexity change?"