Sub topic 1
Refresher: aggregates and GROUP BY
Prerequisites
This chapter assumes that you can write basic SELECT, WHERE, and ORDER BY queries. You should also know common aggregate functions such as count, sum, and avg, and understand that SQL NULL means an unknown or missing value.
The examples use this PostgreSQL table:
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
amount numeric(10,2) NOT NULL,
created_at timestamptz NOT NULL
);What an aggregate does
An aggregate function combines values from several rows into one result. For example:
count(*)counts rows.sum(amount)adds numeric values.avg(amount)calculates an average.min(amount)andmax(amount)find the smallest and largest values.
Without GROUP BY, the whole input is one group:
SELECT
count(*) AS order_count,
sum(amount) AS total_amount,
avg(amount) AS average_amount
FROM orders;This query returns one row, even when orders contains many rows. The query has one aggregate result for the complete table.
An aggregate query can also include ordinary expressions that describe the result. For example, this query labels the complete result:
SELECT
'all orders' AS scope,
count(*) AS order_count,
sum(amount) AS total_amount
FROM orders;Splitting rows into groups
GROUP BY divides input rows into groups that have the same values for the grouped expressions. PostgreSQL then evaluates each aggregate separately for each group.
This query produces one row per customer:
SELECT
customer_id,
count(*) AS order_count,
sum(amount) AS total_amount
FROM orders
GROUP BY customer_id
ORDER BY customer_id;If customer 10 has three orders and customer 20 has two orders, the result has two rows. Each row contains the aggregates for one customer.
| customer_id | order_count | total_amount |
|---|---|---|
| 10 | 3 | 125.50 |
Every selected expression must either be grouped or be calculated by an aggregate. This is invalid because status is neither grouped nor aggregated:
SELECT customer_id, status, count(*)
FROM orders
GROUP BY customer_id;A customer can have several statuses, so PostgreSQL cannot choose one status for the output row. Add status to the grouping when you need one row per customer and status:
SELECT
customer_id,
status,
count(*) AS order_count
FROM orders
GROUP BY customer_id, status
ORDER BY customer_id, status;The order of filtering and grouping
A useful working model is:
FROMfinds the source rows.WHEREremoves rows before grouping.GROUP BYforms groups.- Aggregate functions calculate values for each group.
HAVINGremoves complete groups.ORDER BYsorts the final rows.
The following query counts only orders created during the last 30 days. The WHERE clause affects every aggregate because it removes rows before aggregation:
SELECT
customer_id,
count(*) AS recent_orders,
sum(amount) AS recent_amount
FROM orders
WHERE created_at >= now() - interval '30 days'
GROUP BY customer_id
HAVING count(*) >= 2
ORDER BY recent_amount DESC;The HAVING condition is different from WHERE. WHERE tests individual input rows. HAVING tests the aggregate result for a group. Here, PostgreSQL keeps only customers with at least two recent orders.
Why this matters for conditional aggregation
Conditional aggregation asks an aggregate to consider only some rows. The older pattern puts a CASE expression inside the aggregate:
SELECT
count(CASE WHEN status = 'paid' THEN 1 END) AS paid_orders
FROM orders;The CASE expression returns 1 for paid orders and NULL for other orders. count(expression) ignores NULL, so only paid orders are counted.
PostgreSQL provides a clearer syntax for this task:
SELECT
count(*) FILTER (WHERE status = 'paid') AS paid_orders
FROM orders;The FILTER clause belongs to the aggregate expression. It does not change the groups formed by GROUP BY. Later, you can place several filtered aggregates in the same grouped query, such as paid and refunded counts for every customer.
Exercise
Which clause should you use to keep only customers whose total order amount is greater than 1000?
Show answer
Use HAVING, for example: SELECT customerid, sum(amount) AS totalamount FROM orders GROUP BY customer_id HAVING sum(amount) > 1000;