Why computed values add flexibility in MySQL - Performance Analysis
We want to understand how using computed values in SQL affects the time it takes to run queries.
Specifically, how does adding calculations inside queries change the work the database does?
Analyze the time complexity of the following SQL query with a computed value.
SELECT product_id, price, quantity, (price * quantity) AS total_cost
FROM sales;
This query calculates the total cost for each sale by multiplying price and quantity for every row.
Look at what repeats as the query runs.
- Primary operation: Multiplying price by quantity for each row.
- How many times: Once for every row in the sales table.
As the number of rows grows, the database does more multiplications.
| 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.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the number of rows increases.
[X] Wrong: "Adding a computed value doesn't affect query time much because it's just one calculation."
[OK] Correct: Even one calculation per row adds up when there are many rows, so the total work grows with the data size.
Understanding how computed values affect query time shows you can think about how databases handle work as data grows, a useful skill for real projects and interviews.
What if we added a computed value that uses a subquery for each row? How would the time complexity change?