MySQL CLI and Workbench - Time & Space Complexity
When using MySQL CLI or Workbench to run queries, it's helpful to understand how the time to get results grows as your data grows.
We want to see how query execution time changes when the amount of data increases.
Analyze the time complexity of the following simple query run in MySQL CLI or Workbench.
SELECT * FROM employees WHERE department_id = 5;
This query fetches all employees who belong to department number 5.
Look at what the database does repeatedly to answer this query.
- Primary operation: Scanning rows in the employees table to find matches.
- How many times: Once for each row in the employees table.
As the number of employees grows, the database checks more rows to find those in department 5.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 row checks |
| 100 | 100 row checks |
| 1000 | 1000 row checks |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles the checks.
Time Complexity: O(n)
This means the time to run the query grows in a straight line with the number of rows in the table.
[X] Wrong: "The query time stays the same no matter how many rows there are."
[OK] Correct: Without special help like indexes, the database must check each row, so more rows mean more work.
Understanding how query time grows helps you write better queries and explain your thinking clearly in interviews.
"What if we added an index on department_id? How would the time complexity change?"