COUNT, SUM, AVG, MIN, MAX in PostgreSQL - Time & Space Complexity
When using aggregate functions like COUNT, SUM, AVG, MIN, and MAX in a database, it's important to understand how the time to get results changes as the data grows.
We want to know how the work done by these functions grows when the number of rows increases.
Analyze the time complexity of the following SQL query using aggregate functions.
SELECT COUNT(*), SUM(price), AVG(price), MIN(price), MAX(price)
FROM sales;
This query calculates the total number of sales, the sum and average of prices, and the minimum and maximum price from the sales table.
Look for repeated actions in the query execution.
- Primary operation: Scanning each row in the sales table once.
- How many times: Exactly once for all rows, since all aggregates can be computed in a single pass.
As the number of rows increases, the database reads each row once to update the aggregate values.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 reads and updates |
| 100 | 100 reads and updates |
| 1000 | 1000 reads and updates |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles the work.
Time Complexity: O(n)
This means the time to compute these aggregates grows linearly with the number of rows in the table.
[X] Wrong: "Aggregate functions like COUNT or SUM run instantly no matter how big the table is."
[OK] Correct: The database must look at each row to include it in the calculation, so more rows mean more work and more time.
Understanding how aggregate functions scale helps you explain query performance clearly and shows you know how databases handle data as it grows.
"What if we added a WHERE clause that filters most rows before aggregation? How would the time complexity change?"
Practice
COUNT(column_name) do in a PostgreSQL query?Solution
Step 1: Understand COUNT function behavior
The COUNT function counts how many rows have a non-null value in the specified column.Step 2: Differentiate from other aggregate functions
SUM adds values, AVG finds average, MAX finds maximum, so they do not count rows.Final Answer:
Counts the number of non-null values in the specified column. -> Option BQuick Check:
COUNT = number of non-null rows [OK]
- Thinking COUNT sums values
- Assuming COUNT includes nulls
- Confusing COUNT with AVG or MAX
price column in a table named products?Solution
Step 1: Recall correct function syntax
Aggregate functions like AVG require parentheses around the column name: AVG(column_name).Step 2: Check each option's syntax
SELECT AVG(price) FROM products; uses correct syntax: AVG(price). Options A, B, and C have syntax errors or invalid function names.Final Answer:
SELECT AVG(price) FROM products; -> Option CQuick Check:
AVG(column) uses parentheses [OK]
- Omitting parentheses in AVG
- Using wrong function name like AVERAGE
- Using brackets instead of parentheses
sales with column amount containing values (100, 200, NULL, 300), what is the result of this query?SELECT COUNT(amount), SUM(amount), AVG(amount), MIN(amount), MAX(amount) FROM sales;
Solution
Step 1: Count non-null values in amount
Values are 100, 200, NULL, 300. COUNT(amount) counts non-null values = 3.Step 2: Calculate SUM, AVG, MIN, MAX ignoring NULL
SUM = 100+200+300 = 600; AVG = 600/3 = 200; MIN = 100; MAX = 300.Final Answer:
(3, 600, 200, 100, 300) -> Option DQuick Check:
COUNT=3, SUM=600, AVG=200 [OK]
- Counting NULL as a value in COUNT(column)
- Dividing AVG by total rows including NULL
- Confusing COUNT(column) with COUNT(*)
SELECT COUNT(*), SUM(price), AVG(price) FROM products WHERE price > 'ten';
Solution
Step 1: Analyze WHERE clause condition
The condition price > 'ten' compares a numeric column to a string, which causes a type error in PostgreSQL.Step 2: Check other parts of the query
COUNT(*) with WHERE is valid; SUM and AVG can be used together; GROUP BY not needed without grouping.Final Answer:
Comparing price (numeric) with string 'ten' causes error. -> Option AQuick Check:
Numeric compared to string causes error [OK]
- Assuming COUNT(*) cannot be used with WHERE
- Thinking GROUP BY is always required with aggregates
- Mixing data types in WHERE conditions
orders with columns customer_id and total_amount. How do you write a query to find the average order amount for each customer, but only include customers with at least 5 orders?Solution
Step 1: Group orders by customer_id
Use GROUP BY customer_id to aggregate orders per customer.Step 2: Filter groups with HAVING clause
HAVING COUNT(*) >= 5 filters customers with at least 5 orders.Step 3: Calculate average order amount per customer
Use AVG(total_amount) to find average order value per customer.Final Answer:
SELECT customer_id, AVG(total_amount) FROM orders GROUP BY customer_id HAVING COUNT(*) >= 5; -> Option AQuick Check:
GROUP BY + HAVING filters groups [OK]
- Using WHERE instead of HAVING for group filters
- Placing HAVING before GROUP BY
- Not grouping by customer_id
Ready to prove it?
Pass the test and this pattern moves unknown
