SELECT with expressions and calculations in SQL - Time & Space Complexity
We want to understand how the time it takes to run a SELECT query with calculations changes as the data grows.
How does adding more rows affect the work the database does?
Analyze the time complexity of the following code snippet.
SELECT product_id, price, quantity, price * quantity AS total_cost
FROM sales;
This query selects each sale's product ID, price, quantity, and calculates the total cost by multiplying price and quantity for each row.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The database reads each row in the sales table once.
- How many times: Once per row, it performs the multiplication calculation.
As the number of rows grows, the database does more calculations, one for each row.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 multiplications |
| 100 | 100 multiplications |
| 1000 | 1000 multiplications |
Pattern observation: The work grows directly with the number of rows; double the rows, double the calculations.
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: "Calculations inside SELECT make the query much slower than just selecting columns."
[OK] Correct: The calculation is simple and done once per row, so it adds only a small, direct cost proportional to the number of rows.
Understanding how simple calculations affect query time helps you explain performance clearly and shows you know how databases handle data row by row.
"What if we added a JOIN to another table with m rows? How would the time complexity change?"