Sub topic 1
Refresher: Aggregates and GROUP BY
An aggregate function reads many rows and returns one value. GROUP BY splits a table into groups first, so you get one value per group. Every conditional aggregation technique in this tutorial builds on these two ideas. This chapter reviews them, with attention to the details that matter later: how NULLs are treated, what an empty input produces, and the order in which a query's clauses run.
Prerequisites
This chapter assumes you already know:
- Basic
SELECT,WHEREandORDER BYsyntax. - What aggregate functions such as
count,sumandavgdo, at least roughly. - That NULL in SQL means "unknown or missing", and that comparing anything to NULL with
=does not return true.
You also need access to a PostgreSQL database where you can create a table. Any recent version works. FILTER, which later chapters cover, has been available since PostgreSQL 9.4.
The sample table and data
All examples in this tutorial use one table. Create it first:
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
);Then load eight rows. They are small enough that you can check every result by hand.
INSERT INTO orders (id, customer_id, status, amount, created_at) VALUES
(1, 10, 'paid', 40.00, '2026-01-05 10:00+00'),
(2, 10, 'refunded', 25.00, '2026-01-20 12:30+00'),
(3, 11, 'paid', 60.00, '2026-01-28 09:15+00'),
(4, 11, 'pending', 15.50, '2026-02-02 16:45+00'),
(5, 12, 'paid', 100.00, '2026-02-10 08:00+00'),
(6, 12, 'paid', 20.00, '2026-02-14 19:20+00'),
(7, 12, 'refunded', 20.00, '2026-02-15 11:00+00'),
(8, 13, 'pending', 75.00, '2026-02-21 14:10+00');Aggregates without GROUP BY
When a query uses an aggregate and has no GROUP BY, the whole table (after WHERE) is treated as a single group. The result is always exactly one row.
SELECT
count(*) AS total_orders,
sum(amount) AS total_amount,
min(amount) AS smallest,
max(amount) AS largest
FROM orders;With the sample data this returns 8, 355.50, 15.50 and 100.00.
The aggregates you will use most often are listed below.
| Function | Returns | Rows it skips |
|---|---|---|
| `count(*)` | Number of rows | None |
| `count(expr)` | Number of rows where `expr` is not NULL | NULL values |
| `sum(expr)` | Total of `expr` | NULL values |
| `avg(expr)` | Mean of `expr` | NULL values |
| `min(expr)`, `max(expr)` | Smallest or largest value | NULL values |
| `array_agg(expr)` | Array of values | None (NULLs are kept in the array) |
| `string_agg(expr, sep)` | Values joined into text | NULL values |
Notice that count(*) and count(expr) are different functions. count(*) counts rows. count(expr) counts rows where the expression is not NULL. The difference matters in the next chapters, because conditional aggregation depends on aggregates ignoring NULLs.
How aggregates treat NULL
Our table has no nullable columns, so use a VALUES list to see the behavior directly:
SELECT
count(*) AS rows_seen,
count(x) AS non_null_x,
sum(x) AS sum_x,
avg(x) AS avg_x
FROM (VALUES (1), (NULL), (3)) AS t(x);The result is 3, 2, 4 and 2.0000000000000000. The NULL row is counted by count(*) but ignored by the other three. Notice that avg divides by 2, not 3. The NULL row does not count as a zero. It is excluded from both the numerator and the denominator.
Aggregates over zero rows
If no rows reach the aggregate, the functions behave differently:
SELECT
count(*) AS n,
sum(amount) AS total
FROM orders
WHERE status = 'cancelled';No order has the status cancelled, so this returns one row with n = 0 and total = NULL. The query returns one row because there is no GROUP BY, so there is one group even when it is empty. count returns 0 for an empty input. sum, avg, min, max and array_agg return NULL.
The next chapters cover this contrast in detail, because filtered aggregates often run over empty sets.
GROUP BY: one result row per group
GROUP BY lists the expressions that define the groups. Rows with the same values for those expressions land in the same group, and each aggregate runs once per group.
SELECT
status,
count(*) AS orders,
sum(amount) AS total_amount
FROM orders
GROUP BY status
ORDER BY status;| status | orders | total_amount |
|---|---|---|
| paid | 4 | 220.00 |
| pending | 2 | 90.50 |
| refunded | 2 | 45.00 |
The group totals add up to the overall figures: 4 + 2 + 2 = 8 orders and 220.00 + 90.50 + 45.00 = 355.50.
The grouping rule
Every column in the SELECT list must either appear in GROUP BY or be used inside an aggregate function. This query breaks the rule:
SELECT customer_id, status, count(*)
FROM orders
GROUP BY customer_id;PostgreSQL rejects it with an error similar to column "orders.status" must appear in the GROUP BY clause or be used in an aggregate function. The database cannot pick one status for a customer who has several, and it will not guess. Either add status to GROUP BY, which makes groups of customer and status pairs, or aggregate it, for example with string_agg(DISTINCT status, ', ').
There is one exception. If you group by a table's primary key, PostgreSQL lets you select any other column of that table, because the key determines them.
Grouping by an expression
You can group by any expression, not just a bare column. A common case is bucketing timestamps into months:
SELECT
date_trunc('month', created_at) AS month,
count(*) AS orders,
sum(amount) AS total_amount
FROM orders
GROUP BY 1
ORDER BY 1;GROUP BY 1 refers to the first column of the SELECT list. It saves repeating a long expression. Many teams prefer to write the expression out for readability, and both forms work. With the sample data, January has 3 orders totaling 125.00 and February has 5 totaling 230.50.
Grouping by several columns
Listing more than one expression gives one group for each distinct combination:
SELECT
customer_id,
status,
count(*) AS orders
FROM orders
GROUP BY customer_id, status
ORDER BY customer_id, status;Customer 12 produces two rows here: one for paid (2 orders) and one for refunded (1 order). Combinations that do not occur in the data, such as customer 13 with paid, produce no row at all. GROUP BY only creates groups from rows that exist. This point returns in later chapters, where we put the statuses into columns instead of rows.
DISTINCT inside an aggregate
Placing DISTINCT inside the call removes duplicate input values before the aggregate runs:
SELECT
count(*) AS orders,
count(DISTINCT customer_id) AS customers
FROM orders;This returns 8 orders and 4 customers. DISTINCT inside an aggregate is separate from SELECT DISTINCT, which removes duplicate output rows. You can combine the two forms, but they do different jobs.
WHERE, GROUP BY and HAVING
A query has two places to filter rows, and they act at different moments:
WHEREremoves rows before grouping. It cannot reference an aggregate, because no aggregate exists yet.HAVINGremoves whole groups after the aggregates are computed. It can reference aggregates.
This query finds customers whose orders sum to more than 70:
SELECT
customer_id,
sum(amount) AS total_amount
FROM orders
GROUP BY customer_id
HAVING sum(amount) > 70
ORDER BY customer_id;It returns customers 11 (75.50), 12 (140.00) and 13 (75.00). Customer 10 totals 65.00, so that group is dropped.
You can use both clauses together. This variant first discards non-paid orders, then groups, then drops small groups:
SELECT
customer_id,
sum(amount) AS paid_total
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING sum(amount) > 50
ORDER BY customer_id;Paid totals are 40.00 for customer 10, 60.00 for customer 11 and 120.00 for customer 12. Customer 13 has no paid orders, so it never forms a group. The query returns customers 11 and 12.
The order a query runs in
SQL is written in one order but evaluated in another. Knowing the evaluation order explains most of the rules above, and it explains why FILTER has the shape it has.
This is the logical order. The planner may execute steps differently as long as the result is the same. Three consequences follow:
WHEREcannot use an aggregate, because aggregates are computed later.HAVINGcan use an aggregate, because it runs after them.- Column aliases from the
SELECTlist are not visible toWHERE,GROUP BYorHAVING. PostgreSQL does allow aliases and positions inGROUP BYandORDER BYas a convenience.WHEREandHAVINGnever accept aliases.
The limitation that motivates conditional aggregation
Suppose a report needs, in one row, the total number of orders and the number of refunded orders. WHERE status = 'refunded' cannot do this alone, because it would also shrink the total. Your options with only the tools in this chapter are weak:
- Run two queries and combine the results in application code.
- Use
GROUP BY statusand pivot the rows into columns outside the database. - Use a subquery or self-join for each condition, scanning the table repeatedly.
All of these are clumsy. What is missing is a way to give each aggregate its own condition within one grouped query. The next two chapters cover the two ways to do it: a CASE expression inside the aggregate, and PostgreSQL's FILTER (WHERE ...) clause.
Common mistakes to avoid now
- Using
count(column)when you meantcount(*). If the column can be NULL, the counts differ. - Putting an aggregate in
WHERE. PostgreSQL raisesaggregate functions are not allowed in WHERE. Move the condition toHAVING, or to a subquery. - Using
HAVINGfor row-level conditions.HAVING status = 'paid'works only ifstatusis a grouping column. It is slower and less clear than putting the condition inWHERE, because rows are grouped before they are discarded. - Expecting a row for an empty group. With
GROUP BY, a group with no rows does not exist and gives no output row. WithoutGROUP BY, an empty input still gives one row.
Exercise
Using the sample data, write a query that returns each customer_id with the number of its orders and its total amount, but only for customers who have at least 2 orders and only counting orders whose status is not 'pending'. What rows does it return?
Show answer
SELECT customerid, count(*) AS orders, sum(amount) AS totalamount FROM orders WHERE status <> 'pending' GROUP BY customerid HAVING count(*) >= 2 ORDER BY customerid; The WHERE clause removes pending orders (ids 4 and 8) before grouping. Customer 10 has 2 orders totaling 65.00, customer 11 has only 1 order left (60.00) and is dropped by HAVING, customer 12 has 3 orders totaling 140.00, and customer 13 has no orders left. The result is two rows: (10, 2, 65.00) and (12, 3, 140.00).
Exercise
What do count(*), count(x) and sum(x) return for the input values 5, NULL, NULL, and what does sum(x) return when there are no input rows at all?
Show answer
For the values 5, NULL, NULL, count(*) returns 3 because it counts rows, count(x) returns 1 because it skips NULLs, and sum(x) returns 5 because it also skips NULLs. When there are no input rows, count returns 0 but sum returns NULL.