Advanced Queries
SQL Aggregate Queries
Many questions you ask of a database are about groups rather than single rows: total revenue per region, the number of courses each student takes, or customers whose orders add up to more than a threshold. An aggregate query collapses many rows into summary rows. This lesson covers the aggregate functions, the GROUP BY and HAVING clauses that organise and filter groups, and subqueries that compare values against an aggregate.
Aggregate functions and NULLs
An aggregate function takes the values of one column from a set of rows and returns a single value. Standard SQL provides five core aggregates, and their treatment of NULL is where most errors start.
Function | Returns | Treatment of NULL |
|---|---|---|
COUNT(*) | number of rows | counts every row |
COUNT(col) | number of non-null values | skips NULL |
SUM(col) | total of the values | skips NULL |
AVG(col) | SUM(col) / COUNT(col) | skips NULL, so the divisor is the non-null count |
MIN(col), MAX(col) | smallest or largest value | skips NULL |
Without GROUP BY, all rows that pass WHERE form one group and the query returns exactly one row. COUNT(DISTINCT col) counts distinct non-null values.
Example: A payments table holds amounts 20, 30, NULL and 50. COUNT(*) is 4 and COUNT(amount) is 3. SUM(amount) is 100, so AVG(amount) is 100 / 3 = 33.33, not 100 / 4 = 25.
GROUP BY and HAVING
GROUP BY partitions the rows that survive WHERE into groups that share the same values in the grouping columns, and each group produces one output row. Rows whose grouping column is NULL form a single group of their own. Because each group becomes one row, every column in SELECT that is not inside an aggregate must appear in GROUP BY; otherwise the database has no single value to show. Some systems relax this rule, but standard SQL and most exams enforce it.
SELECT region, COUNT(*) AS n_orders, SUM(total) AS revenue
FROM orders
WHERE status = 'shipped'
GROUP BY region
HAVING SUM(total) > 10000
ORDER BY revenue DESC;The clauses are written in the order above, but the database evaluates them in a different logical order.
The HAVING clause filters whole groups after the aggregates have been computed, so it may contain aggregate functions. WHERE filters individual rows before any group exists, so it may not.
Property | WHERE | HAVING |
|---|---|---|
Acts on | individual rows | groups |
Runs | before grouping | after grouping |
May contain aggregates | no | yes |
Effect | changes which rows are summarised | keeps or drops whole result rows |
A condition on a single row's value belongs in WHERE: it changes which rows enter each group and reduces the work done by grouping. Because SELECT runs after HAVING, standard SQL does not let you use a SELECT alias such as revenue in WHERE or HAVING, though ORDER BY may use it.
Comparing against an aggregate with a subquery
You cannot write WHERE total > AVG(total), because aggregates are not allowed in WHERE. Instead, compute the aggregate in a scalar subquery and compare against its result:
SELECT order_id, total
FROM orders
WHERE total > (SELECT AVG(total) FROM orders);The same pattern works for groups. HAVING AVG(total) > (SELECT AVG(total) FROM orders) keeps the groups whose average beats the overall average. The subquery is evaluated on its own rows: the outer WHERE does not filter it unless you repeat the condition inside.
To aggregate an aggregate, such as the average of per-customer totals, put the grouped query in FROM as a derived table and aggregate its result: SELECT AVG(cust_total) FROM (SELECT customer, SUM(total) AS cust_total FROM orders GROUP BY customer) AS t;
What to remember
- COUNT(*) counts rows; every other aggregate skips NULLs, so AVG divides by the non-null count.
- GROUP BY makes one output row per group; non-aggregated SELECT columns must be grouping columns.
- WHERE filters rows before grouping; HAVING filters groups after aggregation.
- Compare against an aggregate with a scalar subquery, and remember the outer WHERE does not apply inside it.
Example: Summarising bike-share rentals by station
A bike-share system logs each rental in a table rentals. The fee column is NUMERIC and holds the fee in dollars; it is NULL when the fee has not yet been recorded.
rental_id | station | minutes | fee |
|---|---|---|---|
1 | Dock A | 12 | 3.00 |
2 | Dock B | 45 | 7.50 |
3 | Dock A | 30 | 5.00 |
4 | Dock C | 8 | NULL |
5 | Dock B | 20 | 4.00 |
6 | Dock A | 55 | 9.00 |
7 | Dock C | 25 | 4.50 |
8 | Dock B | 10 | NULL |
a) Find the result of the query below, rounding averages to two decimal places.
SELECT station, COUNT(*) AS n_rentals, COUNT(fee) AS n_fees,
SUM(fee) AS total_fee, AVG(fee) AS avg_fee
FROM rentals
GROUP BY station;GROUP BY places rows with the same station together: Dock A holds rentals 1, 3 and 6; Dock B holds rentals 2, 5 and 8; Dock C holds rentals 4 and 7. Each group becomes one output row.
For Dock B, COUNT(*) counts all three rows, but rental 8 has a NULL fee, so COUNT(fee) is ________. The non-null fees sum to ________, and AVG divides by the non-null count: 11.50 / 2 = 5.75.
Dock A has three rows with fees 3.00, 5.00 and 9.00, so the sum is 17.00 and the average is 17.00 / 3 = 5.67. Dock C has two rows but only one fee, so the sum and the average are both 4.50.
- Dock A: n_rentals 3, n_fees 3, total_fee 17.00, avg_fee 5.67
- Dock B: n_rentals 3, n_fees 2, total_fee 11.50, avg_fee 5.75
- Dock C: n_rentals 2, n_fees 1, total_fee 4.50, avg_fee 4.50
b) Find the result of this query, which looks only at rentals of 15 minutes or more.
SELECT station, COUNT(*) AS n_long, SUM(fee) AS long_fee
FROM rentals
WHERE minutes >= 15
GROUP BY station
HAVING COUNT(*) >= 2;WHERE runs first, on individual rows. Rentals 1 (12 min), 4 (8 min) and 8 (10 min) are removed, leaving ________ rows: rentals 2, 3, 5, 6 and 7.
Grouping those rows gives Dock A with rentals 3 and 6, Dock B with rentals 2 and 5, and Dock C with only rental 7. HAVING then tests each group: Dock C has ________ row, so its group is dropped.
- Dock A: n_long 2, long_fee 5.00 + 9.00 = 14.00
- Dock B: n_long 2, long_fee 7.50 + 4.00 = 11.50
If you had grouped first and filtered on minutes afterwards, Dock A would still count rental 1 and show 3 rows; that is why the row condition belongs in WHERE.
c) Write a query that lists the stations whose average fee is greater than the average fee across all rentals, and state its result.
The comparison is made per station and involves an aggregate, so it goes in HAVING, with the overall average supplied by a scalar subquery:
SELECT station, AVG(fee) AS avg_fee FROM rentals GROUP BY station HAVING AVG(fee) > (SELECT AVG(fee) FROM rentals);
The subquery sums every non-null fee in the table, giving ________, and divides by the ________ non-null fees, so it returns ________.
Now compare each station average from part a: Dock A at 5.67 exceeds 5.50 and is kept; Dock B at 5.75 is kept; Dock C at 4.50 is dropped. The query returns Dock A (5.67) and Dock B (5.75).
A common slip is to divide 33.00 by all 8 rentals, giving 4.125; with that threshold Dock C would wrongly appear, because AVG never counts the NULL fees.
A database course asks you to trace how a relational engine logically processes the following query against an orders table. Arrange the processing stages in the order standard SQL defines them, from the first stage applied to the last.
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'shipped'
GROUP BY customer_id
HAVING SUM(amount) > 500
ORDER BY total DESC;1.
HAVING discards whole groups whose summed amount is 500 or less.
2.
SELECT computes customer_id and the total for each surviving group.
3.
WHERE removes individual rows whose status is not shipped.
4.
ORDER BY sorts the result rows by total from largest to smallest.
5.
GROUP BY collects the remaining rows into one group per customer.
6.
FROM identifies the orders table and supplies every candidate row.
A table purchases records each order a customer places, with amount stored as an integer number of dollars:
order_id | customer | amount |
|---|---|---|
101 | Lee | 25 |
102 | Patel | 40 |
103 | Lee | 15 |
104 | Okafor | 60 |
105 | Patel | 35 |
106 | Lee | 50 |
107 | Okafor | 20 |
Complete the result of the following query. Enter whole numbers.
SELECT customer, COUNT(*) AS cnt, SUM(amount) AS total, MAX(amount) AS biggest
FROM purchases
GROUP BY customer
ORDER BY customer;| customer | cnt | total | biggest |
| Lee | |||
| Okafor | |||
| Patel |