Selecting specific columns in MySQL - Time & Space Complexity
When we ask for specific columns in a database, we want to know how the work grows as the table gets bigger.
We want to see how the time to get results changes when we select only some columns instead of all.
Analyze the time complexity of the following code snippet.
SELECT name, email
FROM users
WHERE active = 1;
This query gets only the name and email columns from all active users in the users table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each row in the users table to check if active = 1.
- How many times: Once for each row in the table.
As the number of rows grows, the database checks more rows to find active users.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row checks |
| 100 | About 100 row checks |
| 1000 | About 1000 row checks |
Pattern observation: The work grows directly with the number of rows in the table.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the table gets bigger.
[X] Wrong: "Selecting fewer columns makes the query run much faster in terms of time complexity."
[OK] Correct: The main time cost is checking each row, not the number of columns selected. Selecting fewer columns helps with data size but does not change how many rows are checked.
Understanding how selecting columns affects query time helps you explain database efficiency clearly and confidently.
"What if we add an index on the active column? How would the time complexity change?"