Tables, rows, and columns concept in SQL - Time & Space Complexity
When working with tables in a database, it is important to understand how the time to access data grows as the table gets bigger.
We want to know how the number of rows and columns affects the time it takes to find or process data.
Analyze the time complexity of the following SQL query.
SELECT *
FROM Employees
WHERE Department = 'Sales';
This query searches the Employees table for all rows where the Department column equals 'Sales'.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Checking each row in the Employees table to see if the Department matches 'Sales'.
- How many times: Once for every row in the table.
As the number of rows grows, the database must check more rows one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows directly with the number of rows.
Time Complexity: O(n)
This means the time to find matching rows grows in a straight line as the table gets bigger.
[X] Wrong: "Adding more columns will make the query slower in the same way as adding more rows."
[OK] Correct: The query time mainly depends on how many rows are checked, not how many columns each row has.
Understanding how table size affects query time helps you explain database performance clearly and confidently.
"What if we added an index on the Department column? How would the time complexity change?"