Combining multiple aggregates in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we combine several aggregate functions in one query, it is important to know how the work grows as the data grows.
We want to understand how the time to get results changes when the number of rows increases.
Analyze the time complexity of the following code snippet.
SELECT
COUNT(*) AS total_orders,
SUM(amount) AS total_amount,
AVG(amount) AS average_amount
FROM orders
WHERE order_date >= '2024-01-01';
This query calculates the total number of orders, the sum of amounts, and the average amount for orders from 2024 onward.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning each row in the filtered orders table once.
- How many times: Once per row that meets the date condition.
As the number of orders grows, the database must look at each matching row once to update all aggregates.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row checks and updates |
| 100 | About 100 row checks and updates |
| 1000 | About 1000 row checks and updates |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles work.
Time Complexity: O(n)
This means the time to run the query grows in a straight line with the number of rows processed.
[X] Wrong: "Adding more aggregate functions makes the query take longer by multiplying the work."
[OK] Correct: All aggregates are calculated in one pass over the data, so adding more aggregates only adds a small fixed amount of work per row, not a full extra pass.
Understanding how combining aggregates affects performance helps you write efficient queries and explain your reasoning clearly in interviews.
"What if we added a GROUP BY clause to this query? How would the time complexity change?"
Practice
Solution
Step 1: Understand aggregate functions
Aggregate functions like SUM() and AVG() calculate summary values from data.Step 2: Combining aggregates in one query
Using commas, you can list multiple aggregates in SELECT to get many summaries at once.Final Answer:
Get several summary values like totals and averages in one result -> Option AQuick Check:
Multiple aggregates = multiple summaries [OK]
- Thinking multiple queries run simultaneously
- Confusing aggregates with table creation
- Assuming aggregates sort data automatically
Solution
Step 1: Check aggregate separation
Aggregates must be separated by commas in SELECT clause.Step 2: Identify correct syntax
SELECT SUM(price), AVG(price) FROM sales; uses commas correctly; others use AND, OR, or no separator which is invalid.Final Answer:
SELECT SUM(price), AVG(price) FROM sales; -> Option BQuick Check:
Aggregates separated by commas [OK]
- Using AND or OR instead of commas
- Omitting commas between aggregates
- Writing aggregates without any separator
orders with column amount, what will this query return?SELECT COUNT(*), MAX(amount), MIN(amount) FROM orders;
Solution
Step 1: Understand each aggregate
COUNT(*) counts rows, MAX(amount) finds highest value, MIN(amount) finds lowest value.Step 2: Combine results
All three aggregates return one row with three summary values: count, max, and min.Final Answer:
Number of rows, highest amount, lowest amount -> Option AQuick Check:
COUNT, MAX, MIN = count, max, min [OK]
- Confusing COUNT(*) with SUM(amount)
- Expecting multiple rows instead of one
- Thinking multiple aggregates cause syntax error
SELECT SUM(price), AVG(price) FROM sales GROUP BY category;
Solution
Step 1: Check GROUP BY usage
When using GROUP BY category, category must appear in SELECT to show groups.Step 2: Identify missing column
Query selects only aggregates but misses category column, causing error or unexpected output.Final Answer:
Missing GROUP BY column in SELECT clause -> Option CQuick Check:
GROUP BY columns must appear in SELECT [OK]
- Omitting GROUP BY column in SELECT
- Thinking SUM and AVG can't be combined
- Misplacing GROUP BY clause
sales table with columns category and amount. Which query correctly combines these aggregates?Solution
Step 1: Include category in SELECT and GROUP BY
To get aggregates per category, category must be in SELECT and GROUP BY.Step 2: Combine aggregates with commas
SUM(amount), AVG(amount), COUNT(*) are combined with commas to get totals, averages, and counts.Final Answer:
SELECT category, SUM(amount), AVG(amount), COUNT(*) FROM sales GROUP BY category; -> Option DQuick Check:
GROUP BY category with aggregates = SELECT category, SUM(amount), AVG(amount), COUNT(*) FROM sales GROUP BY category; [OK]
- Missing GROUP BY clause
- Using AND instead of commas between aggregates
- Not including category in SELECT when grouping
