0
0
SQLquery~5 mins

SELECT with expressions and calculations in SQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: SELECT with expressions and calculations
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of rows grows, the database does more calculations, one for each row.

Input Size (n)Approx. Operations
1010 multiplications
100100 multiplications
10001000 multiplications

Pattern observation: The work grows directly with the number of rows; double the rows, double the calculations.

Final Time Complexity

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.

Common Mistake

[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.

Interview Connect

Understanding how simple calculations affect query time helps you explain performance clearly and shows you know how databases handle data row by row.

Self-Check

"What if we added a JOIN to another table with m rows? How would the time complexity change?"