Aggregate functions reduce a set of rows to a single value: COUNT, SUM, AVG, MIN and MAX. COUNT gives the number of rows, SUM the total, AVG the mean, MIN and MAX the smallest and largest, including for dates and strings. All except COUNT(*) ignore NULL. Without GROUP BY the result is one row even for an empty set: COUNT returns 0, the others NULL.
SQL · Aggregates
A manager asks: how many transactions, what turnover and when was the last one. Is one query enough?
The screen says "Turnover for the period: 120" and a tester has to check that this number is right. Exporting thousands of rows and counting by hand is slow and unreliable: the database can count by itself. This lesson is about aggregate functions: what exactly they do with rows, where in the query they run and where their behaviour surprises.
How it works and why. An aggregate function reads a set of rows and returns one value for the whole set. Without GROUP BY the set is all rows that passed WHERE, so the result is exactly one row (unless the query has HAVING). Even when there are no rows, the database does not return "nothing": COUNT gives 0 and the other functions give NULL.
Many rows collapse into one
Figure 1. An aggregate leaves no separate rows: the output is one value per function.
Function
What it computes
NULL on input
Empty set
COUNT(*)
the number of rows
the row is counted
0
COUNT(col)
rows where col is not NULL
ignores
0
SUM(col)
the sum
ignores
NULL
AVG(col)
the average
ignores
NULL
MIN, MAX
the smallest and the largest
ignores
NULL
Result types matter too. MIN and MAX work not only with numbers but with anything that can be ordered: dates and strings (strings are compared by the collation rules, so "a" and "B" may order differently than you expect). In PostgreSQL SUM of integer returns bigint and AVG of integers returns numeric, so the average of 30 and 31 is 30.5, not 30.
Example: from an export to one query. The "turnover for the period" report is checked like this:
SELECTCOUNT(*) AS total,
SUM(amount) AS volume,
AVG(amount) AS avg_amount,
MAX(amount) AS max_amount
FROM transactions
WHERE status = 'completed';
-- one row: 3, 120, 40.0000…, 50
The WHERE filter runs first, so the failed transaction (20) never reaches the aggregate. That is why the "turnover" here is 120, not 140.
What the aggregate sees after WHERE
transactions
id
status
amount
1
completed
50
2
completed
30
3
failed
20 filtered out
4
completed
40
result
total
volume
max_amount
3
120
50
Figure 2. WHERE removes row 3 before the computation: the aggregate works with three rows only.
Limits and alternatives. An aggregate without GROUP BY cannot be mixed with a plain column in SELECT: the database does not know which of many status values to show. Nesting aggregates (SUM(COUNT(*))) without a subquery is forbidden in PostgreSQL too. And if an empty set must give a number rather than NULL, the result is wrapped in COALESCE (a separate lesson in this chapter). Besides the five classic functions, dialects have useful extensions:
-- PostgreSQL: all statuses of a user in one rowSELECT account_id,
STRING_AGG(DISTINCT status, ', 'ORDERBY status) AS statuses
FROM transactions
GROUPBY account_id;
-- MySQL: GROUP_CONCAT(DISTINCT status)
If you need to keep all rows and add a total to each one (for example a share of the grand total), window functions fit: they compute over the same set but do not collapse it into one row.
Common mistakes.
-- error: an aggregate and a plain column without GROUP BYSELECT status, COUNT(*) FROM transactions;
-- an empty set: still exactly one rowSELECTCOUNT(*), SUM(amount), MAX(amount)
FROM transactions
WHERE id = -1;
-- 0 | NULL | NULL
Adding a plain column to an aggregate without GROUP BY: an error, and in some MySQL settings and in SQLite the query runs and shows a random value.
Expecting 0 from SUM on an empty set: it is NULL, and the client shows an empty field.
Forgetting that WHERE drops rows before the aggregate: "turnover" without a status filter includes failed transactions too.
Computing AVG of integers by hand in code with integer division: the fraction is lost.
Finding the largest row with MAX and taking other fields at once: MAX returns only the value, not the whole row.
Check yourself
The query SELECT COUNT(*), SUM(amount) FROM transactions WHERE id = -1 runs without errors. How many rows does it return and what is in them?
Answer
Exactly one row: COUNT gives 0 and SUM gives NULL. An aggregate without GROUP BY always returns one row, even when no row passed WHERE. A test that expects an "empty result" will be wrong here.
Why does SELECT status, COUNT(*) FROM transactions fail?
Answer
An aggregate collapses the set into one value, while status has many different values and the database does not know which to show. Either add GROUP BY status or choose an aggregate for status too (for example MIN(status)).
The table has amounts 100, NULL, 200. Why is AVG(amount) 150 and not 100?
Answer
AVG ignores NULL both in the sum and in the count: (100 + 200) / 2. If NULL were treated as zero it would be (100 + 0 + 200) / 3 = 100. Which variant is right is decided by the business rule.
Related lessons: “How do COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ?”, “How does GROUP BY work?”, “How do aggregates behave with NULL? What is COALESCE?”.
In an interview.Junior: Aggregate functions collapse many rows into one value: COUNT counts, SUM sums, AVG averages, MIN and MAX give the extremes, and not only for numbers but for dates too. For example MAX of the creation date shows when the last transaction happened. Middle/Senior: An aggregate works after WHERE, and without GROUP BY it always returns one row, even on an empty set: COUNT gives 0, the rest NULL. All but COUNT(*) ignore NULL, so I check the result type and what the client does with NULL. To verify a report I count in SQL rather than by hand.
How do COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ?
COUNT(*) counts all rows, COUNT(col) only the rows where col is not NULL, and COUNT(DISTINCT col) the number of different non-NULL values. So COUNT(*) - COUNT(col) equals the number of NULLs in the column. After a LEFT JOIN, a column of the right table is counted instead of COUNT(*), so that a missing pair gives 0 and not 1.
SQL · Aggregates
After a migration users has 100 rows but COUNT(phone) returns 70. A defect or normal?
After a migration a tester compares counts: users has 100 users but COUNT(phone) returns 70. Were 30 phone numbers lost, or were they empty before the migration too? The three forms of COUNT give different numbers on the same data, and telling them apart is a basic data-checking skill.
How it works and why.COUNT(*) counts rows and looks at no column, so NULL does not affect it. COUNT(col) evaluates the expression for each row and counts those where the result is not NULL. COUNT(DISTINCT col) first drops repeats among the non-NULL values and then counts. COUNT(1) and COUNT(*) are the same: a constant is never NULL. A rule follows: COUNT(*) - COUNT(col) equals the number of NULLs in the column, and COUNT(col) - COUNT(DISTINCT col) the number of "extra" repeats.
Three COUNTs on the same data
users
id
name
phone
1
Anna
0501
2
Ivan
NULLnot counted
3
Olha
0502
4
Petro
NULLnot counted
5
Sasha
0501
result
expression
value
COUNT(*)
5
COUNT(phone)
3
COUNT(DISTINCT phone)
2
COUNT(*) - COUNT(phone)
2
Figure 1. Two empty phones drop out of COUNT(phone), and two equal values 0501 merge into one.
Example: what 100 and 70 mean. A query that answers the migration question at once:
SELECTCOUNT(*) AS users_total,
COUNT(phone) AS with_phone,
COUNT(DISTINCT phone) AS distinct_phones,
COUNT(*) - COUNT(phone) AS without_phone
FROM users;
-- on the Figure 1 data: 5 | 3 | 2 | 2
The without_phone difference shows how many fields are empty. Then it has to be compared with the source: if the old system also had an empty phone for 30 users, that is normal, and if not, data was lost during the migration. The number decides nothing by itself, it only points where to look.
COUNT after a LEFT JOIN
wrong
COUNT(*)
A user with no orders gets 1: the LEFT JOIN result has a row for them with NULL in the order columns, and COUNT(*) counts rows.
right
COUNT(o.id)
The same user gets 0: o.id in their row is NULL and COUNT(column) skips it.
Figure 2. After a LEFT JOIN count a column of the right table, otherwise "no orders" turns into "one order".
-- orders per user, including users with noneSELECT u.name, COUNT(o.id) AS orders_cnt
FROM users u
LEFTJOIN orders o ON o.user_id = u.id
GROUPBY u.id, u.name;
Limits and alternatives.COUNT(DISTINCT col) does not count NULL as a separate value, so empty values drop out of the unique ones. It is more expensive than a plain COUNT because the database has to remove repeats, which is noticeable on large tables. Uniqueness often depends on how the data is normalised:
-- how many different addresses if case does not matterSELECTCOUNT(DISTINCT email) AS raw_cnt,
COUNT(DISTINCT lower(email)) AS normalized_cnt
FROM users;
-- the numbers differ: some addresses differ only in case
PostgreSQL does not support COUNT(DISTINCT a, b) with two columns (MySQL does), so pairs are counted through a subquery:
-- PostgreSQL does not accept COUNT(DISTINCT a, b); wrap a subquerySELECTCOUNT(*)
FROM (SELECTDISTINCT user_id, status FROM transactions) AS pairs;
Two more practical details. In PostgreSQL COUNT(*) over a whole large table reads it completely, because every transaction snapshot sees its own rows, so on millions of rows such a query is slow. If you only need to know whether at least one row exists, EXISTS is cheaper. And COUNT returns bigint: in the JavaScript pg driver it arrives as the string "5" by default, so a comparison with the number 5 in a test fails without a type conversion.
Common mistakes.
COUNT(*) after LEFT JOIN instead of COUNT(a column of the right table): "zero orders" becomes "one".
Expecting COUNT(col) to count all rows: a NULL in the column silently reduces the result.
Assuming COUNT(DISTINCT col) counts NULL as one unique value: it skips it.
Counting unique emails without lower() and missing duplicates that differ in case.
Comparing COUNT with an expected number in a test without checking types: the string "5" does not equal the number 5.
Check yourself
users has 100 rows, COUNT(phone) returns 70 and COUNT(DISTINCT phone) returns 65. What do these numbers say?
Answer
30 users have an empty phone (100 - 70). Among the 70 filled ones there are 5 repeats: the same number appears for more than one user. That may be normal (a shared number) or a defect, so it is compared with the domain rules.
A column holds the values 'a', 'a' and NULL. What do COUNT(*), COUNT(col) and COUNT(DISTINCT col) return?
Answer
3, 2 and 1. COUNT(*) counts all three rows, COUNT(col) skips the NULL, and COUNT(DISTINCT col) then merges the two 'a' into one.
A user has no orders. Which COUNT gives 0 after a LEFT JOIN: COUNT(*) or COUNT(o.id)?
Answer
COUNT(o.id). For such a user the LEFT JOIN returns one row with NULL in o.id: COUNT(*) counts that row and gives 1, while COUNT(o.id) skips the NULL and gives 0.
Related lessons: “What aggregate functions are there?”, “How do aggregates behave with NULL? What is COALESCE?”, “How does GROUP BY work?”.
In an interview.Junior: COUNT star counts all rows, COUNT of a column only those where the value is not NULL, and COUNT DISTINCT the number of unique non-NULL values. The difference between the first two shows how many fields are empty, and I use it to check data completeness after a migration. Middle/Senior: After a LEFT JOIN I count a column of the right table, otherwise a missing link gives 1 instead of 0. COUNT(DISTINCT) ignores NULL and is more expensive, and in PostgreSQL several columns need a subquery. I check types too: a bigint can arrive as a string in the driver.
How does GROUP BY work?
GROUP BY splits the rows that passed WHERE into groups by the key value and returns one row per group, with the aggregate computed separately for each. Every column in SELECT must be a grouping key, an aggregate or depend unambiguously on the key. NULLs in the key form one group, and the order of groups is not guaranteed without ORDER BY.
SQL · Aggregates
How many transactions are in each status? And why does the query fail once an email appears in SELECT?
After a release a tester suspects there are more failed transactions. Single rows will not tell: a distribution by status is needed. That is what GROUP BY is for. This lesson explains how the database builds groups, why SELECT is restricted and where grouping silently gives something other than expected.
How it works and why.GROUP BY splits the rows that passed WHERE into groups: rows with the same key value (or set of values) land in one group. Then the aggregate is computed for each group separately and the output is one row per group. For grouping, NULLs count as equal to each other, so all rows with an empty key form one group.
That gives the rule for SELECT: every column must be a grouping key, an aggregate, or depend on the key uniquely. Otherwise the group has many values and the database does not know which to show.
Rows are split into groups
transactions
id
status
amount
1
completed
50
2
failed
20
3
completed
30
4
pending
10
5
failed
40
GROUP BY status
status
cnt
volume
completed
2
80
failed
2
60
pending
1
10
Figure 1. Five rows became three groups: the aggregate is computed per status separately.
Example: a distribution by status and the email error. The distribution the tester was after:
SELECT status, COUNT(*) AS cnt, SUM(amount) AS volume
FROM transactions
GROUPBY status
ORDERBY status;
-- completed | 2 | 80-- failed | 2 | 60-- pending | 1 | 10
Now let us add a "convenience": we also want to see a user's email next to the country.
SELECT country, email, COUNT(*)
FROM users
GROUPBY country;
-- PostgreSQL rejects the query:-- ERROR: column "users.email" must appear in the GROUP BY-- clause or be used in an aggregate function
A non-grouped column in SELECT
risk
SELECT country, email … GROUP BY country
In PostgreSQL this is an error. In SQLite and in MySQL without ONLY_FULL_GROUP_BY the query runs and shows a random email from the group, and the report looks plausible.
right
SELECT country, COUNT(*) … GROUP BY country
Show only the key and aggregates. If a concrete email is needed, group by the user id or take an aggregate (MIN(email)).
Figure 2. An error from the database is better than a "works" that returns a randomly picked value.
Reading the error: a column without a group
1ERROR: column "users.email" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT country, email, …
^ 2
What: the email column is neither in GROUP BY nor an aggregate. The database cannot tell which of the many emails of the group to show, so it refuses.
Where: below, the database repeats the query line, and ^ points at the column it could not explain.
What to do
Remove email from SELECT, add it to GROUP BY (the groups get finer) or take an aggregate such as MIN(email) when any one value will do.
Figure 3. The PostgreSQL error text (shortened): the numbers lead to the explanations.
You can group by several columns (every unique combination becomes a group) and by an expression:
-- grouping by an expression: transactions per month (PostgreSQL)SELECT date_trunc('month', created_at) AS month,
COUNT(*) AS cnt
FROM transactions
GROUPBY date_trunc('month', created_at)
ORDERBY month;
Limits and alternatives. In PostgreSQL and MySQL GROUP BY accepts an alias from SELECT and a column number (GROUP BY 1), SQL Server forbids the alias, and Oracle accepts it only since 23ai. One more exception to the "column in GROUP BY" rule: if you group by a table's primary key, the other columns of that table depend on it uniquely. PostgreSQL and MySQL 5.7+ recognise this, SQL Server does not, so for portability it is better to list columns explicitly.
-- PostgreSQL: name is allowed because u.id is the primary keySELECT u.id, u.name, COUNT(o.id) AS orders_cnt
FROM users u
LEFTJOIN orders o ON o.user_id = u.id
GROUPBY u.id;
For intermediate totals (per group and a grand total) there are ROLLUP and GROUPING SETS (PostgreSQL, SQL Server, Oracle; MySQL has WITH ROLLUP). When after grouping you need to keep all source rows and add the group total to each, you need window functions, because GROUP BY collapses them.
Common mistakes.
Adding to SELECT a column that is neither in GROUP BY nor in an aggregate: an error, and in softer databases a random value.
Grouping too finely (for example together with id): every group is one row and the aggregates collapse nothing.
Relying on the order of groups without ORDER BY: the database returns them in arbitrary order and it can change.
Missing the group with NULL in the key: it exists and in a report it is a separate row.
Grouping after a "one-to-many" JOIN and summing a column from the "one" side: the sums multiply.
Check yourself
The status column has the values completed, failed, NULL and another NULL. How many groups does GROUP BY status return?
Answer
Three: completed, failed and one group for NULL. For grouping, empty values count as equal, so both NULLs together give one result row.
The query SELECT country, email, COUNT(*) FROM users GROUP BY country fails. How do you fix it, depending on what is needed?
Answer
If the count per country is needed, remove email. If a row per user is needed, group by id (or use no GROUP BY at all). If any email from the group will do, take an aggregate such as MIN(email).
Does GROUP BY status guarantee a result ordered by status?
Answer
No. The order of groups is undefined: the database may build them by hashing or by sorting. For a stable order add ORDER BY.
Related lessons: “How does WHERE differ from HAVING?”, “What aggregate functions are there?”, “What are window functions and how do they differ from GROUP BY?”.
In an interview.Junior: GROUP BY splits rows into groups with equal values and computes an aggregate for each group. Every column in SELECT must be either in GROUP BY or in an aggregate function. I use grouping by status to see the data distribution and spot anomalies, for example an unexpectedly large number of failed. Middle/Senior: The error about a column outside GROUP BY is a safeguard: in softer settings the query returns a random value from the group. NULLs form one group, the order of groups without ORDER BY is not guaranteed, and after a "one-to-many" JOIN the sums multiply. For totals there is ROLLUP and for keeping rows window functions.
How does WHERE differ from HAVING?
WHERE filters individual rows before grouping, while HAVING filters the finished groups by the values of aggregates. This follows from the logical order FROM, WHERE, GROUP BY, HAVING, SELECT: an aggregate cannot appear in WHERE because the groups do not exist yet. Row conditions go into WHERE so that fewer rows reach grouping, and HAVING keeps only conditions on aggregates.
SQL · Aggregates
Find users with more than three failed transactions in September. Which condition goes where?
The task sounds like one sentence, but it holds two different conditions: "a failed transaction in September" is about a single row, while "more than three" is about a total per user. If you put them in the wrong place, the query either fails with an error or returns something that looks plausible. This lesson explains how WHERE differs from HAVING and the rule for splitting conditions between them.
How it works and why. A query is executed in a logical order: first FROM, then WHERE, GROUP BY, HAVING and only then SELECT. Everything follows from that. WHERE works before grouping, so it sees single rows and cannot use an aggregate: the groups do not exist yet. HAVING works after grouping, so it sees groups and can compare their aggregates. (Physically the optimiser may act differently, but the result must match this order.)
Where each condition runs
Figure 1. In the example there are 10 transactions: WHERE keeps 7, GROUP BY collects them into 3 groups and HAVING keeps one of them.
The practical rule: whatever can be said about a single row goes in WHERE, and HAVING keeps only the conditions on aggregates. Then fewer rows reach grouping and the query reads unambiguously.
Example: from an error to a correct query. The first attempt puts both conditions in WHERE:
SELECT a.user_id, COUNT(*) AS failed_cnt
FROM transactions t
JOIN accounts a ON a.id = t.account_id
WHERE t.status = 'failed'ANDCOUNT(*) > 3GROUPBY a.user_id;
-- ERROR: aggregate functions are not allowed in WHERE-- there are no groups yet at the WHERE step
The error is expected: at the WHERE step the group does not exist yet, so COUNT(*) has nothing to count. The fix splits the conditions by their meaning:
SELECT a.user_id, COUNT(*) AS failed_cnt
FROM transactions t
JOIN accounts a ON a.id = t.account_id
WHERE t.status = 'failed'-- row filterAND t.created_at >= '2026-09-01'AND t.created_at < '2026-10-01'GROUPBY a.user_id
HAVINGCOUNT(*) > 3; -- group filter
The date interval is written half-open (>= and <), not with BETWEEN: that way the last day of September is not lost even when the column holds a time.
What HAVING drops
after GROUP BY
user_id
failed_cnt
1
4
2
1 filtered out
3
2 filtered out
result
user_id
failed_cnt
1
4
Figure 2. HAVING COUNT(*) > 3 keeps only the group of user 1: the other two have three failures or fewer.
Reading the error: an aggregate in WHERE
1ERROR: aggregate functions are not allowed in WHERE
LINE 5: AND COUNT(*) > 3
^ 2
What: an aggregate stands in WHERE. There are no groups at this step, so COUNT(*) has nothing to count.
Where:LINE 5 and ^ point at the aggregate call, not at the start of the query. The line number counts from the first line of the query text.
What to do
Keep the row condition in WHERE and move the aggregate condition to HAVING COUNT(*) > 3.
Figure 3. The PostgreSQL error text (shortened) for the first attempt in the example.
Limits and alternatives. Sometimes you need not one count but several. If a row must show both all transactions of a user and only the failed ones, the filter status = 'failed' in WHERE does not fit: it removes the rest before counting. Then the condition moves inside the aggregate (FILTER in PostgreSQL or CASE):
-- both all and failed transactions per userSELECT a.user_id,
COUNT(*) AS all_cnt,
COUNT(*) FILTER (WHERE t.status = 'failed') AS failed_cnt
FROM transactions t
JOIN accounts a ON a.id = t.account_id
WHERE t.created_at >= '2026-09-01'AND t.created_at < '2026-10-01'GROUPBY a.user_id
HAVINGCOUNT(*) FILTER (WHERE t.status = 'failed') > 3;
HAVING can also be written for a row condition if the column is in GROUP BY:
-- works, but a row condition lives in the wrong placeSELECT a.user_id, t.status, COUNT(*) AS cnt
FROM transactions t
JOIN accounts a ON a.id = t.account_id
GROUPBY a.user_id, t.status
HAVING t.status = 'failed'ANDCOUNT(*) > 3;
This is allowed but misleading: the PostgreSQL optimiser often moves such conditions to WHERE by itself, but you should not rely on it, and the reader does not see the intent. Three more nuances. An alias from SELECT in HAVING works in MySQL but not in PostgreSQL: the expression has to be repeated. HAVING without GROUP BY is allowed too: the whole selection is then one group and the query returns either one row or none. And a condition on an aggregate that is NULL (for example HAVING SUM(amount) > 100 for a group where all amounts are NULL) gives UNKNOWN, so that group disappears without any signal.
Common mistakes.
An aggregate in WHERE: SQL rejects the query because there are no groups at this step.
A row condition in HAVING: it works but hides the intent, and in some databases processes extra data.
A status filter in WHERE when a count of all rows is needed too: the total becomes wrong.
BETWEEN for dates with time: the last day of the range is lost. A half-open interval is better.
Forgetting NULL in an aggregate: a condition in HAVING silently drops the group.
Check yourself
The query SELECT user_id, COUNT(*) FROM payments WHERE COUNT(*) > 1 GROUP BY user_id fails. Why and how do you fix it?
Answer
WHERE runs before grouping, so there is no aggregate there yet. A condition on an aggregate moves to HAVING: GROUP BY user_id HAVING COUNT(*) > 1.
Where does each condition go: status = 'failed', COUNT(*) > 3, created_at >= '2026-09-01', SUM(amount) > 1000?
Answer
In WHERE: status = 'failed' and created_at >= '2026-09-01', because they are conditions on single rows. In HAVING: COUNT(*) > 3 and SUM(amount) > 1000, because they are conditions on group aggregates.
For each user you need the count of all transactions and the count of failed ones. Does WHERE status = 'failed' work?
Answer
No: WHERE removes all other rows before counting, and the total will be wrong. You need conditional aggregation: COUNT(*) FILTER (WHERE status = 'failed') in PostgreSQL or SUM(CASE WHEN … THEN 1 ELSE 0 END).
Related lessons: “How does GROUP BY work?”, “How do you use CASE WHEN and conditional aggregation?”, “In what order is a query actually executed?”.
In an interview.Junior: WHERE filters single rows before grouping, and HAVING the ready groups by aggregate results. So a condition like "the count is more than three" can only be written in HAVING. Whatever can be filtered before grouping I put in WHERE, so the query processes less data. Middle/Senior: It follows from the logical order FROM, WHERE, GROUP BY, HAVING, SELECT: an aggregate in WHERE is impossible, and a SELECT alias is unavailable in PostgreSQL even in HAVING. When both the total and the filtered count are needed, I move the condition inside the aggregate. Groups with a NULL aggregate are silently dropped in HAVING.
How do aggregates behave with NULL? What is COALESCE?
Aggregates skip NULL, and on an empty set SUM, AVG, MIN and MAX return NULL, not 0. COUNT always returns a number. COALESCE(a, b, …) returns the first argument that is not NULL, so COALESCE(SUM(x), 0) gives zero instead of NULL. Inside an aggregate COALESCE changes the arithmetic: NULL becomes zero, and, for example, the average is computed over a different number of rows.
SQL · Aggregates
A user with no transactions sees an empty field instead of 0. Where did the NULL come from?
For a new user the API response holds "balance": null and the UI shows an empty field or "NaN" instead of 0. There is no error in the query: the sum over an empty set really is NULL in SQL. This lesson is about how aggregates treat NULL, about COALESCE that fixes it, and about the places where the fix itself creates a new bug.
How it works and why. An aggregate takes the value of the expression from each row and skips those that are NULL. SUM, AVG, MIN and MAX compute only over what is left. If nothing is left (the set is empty or all values are NULL), they return NULL, because SQL does not regard "a sum of zero terms" as zero. The exception: COUNT always returns a number, and COUNT(*) is not touched by NULL at all.
COALESCE(a, b, …) returns the first argument that is not NULL, checking them left to right and not looking further. If all arguments are NULL the result is NULL. All arguments must have compatible types: COALESCE(amount, 'n/a') for a numeric column fails in PostgreSQL.
AVG skips NULL
transactions
id
amount
1
100
2
NULLignored
3
200
result
expression
value
COUNT(*)
3
COUNT(amount)
2
AVG(amount)
150
AVG(COALESCE(amount, 0))
100
Figure 1. The NULL row drops out of both the numerator and the denominator: (100 + 200) / 2 = 150. With COALESCE inside, NULL becomes zero: (100 + 0 + 200) / 3 = 100.
Example: an empty balance and a "vanished" fee. The first case from the start of the lesson: the account has no transactions.
-- account 999 has no transactionsSELECTSUM(amount) AS balance
FROM transactions
WHERE account_id = 999;
-- balance: NULLSELECTCOALESCE(SUM(amount), 0) AS balance
FROM transactions
WHERE account_id = 999;
-- balance: 0
COALESCE sits outside the aggregate, so it replaces only an empty result. The second case is subtler. Let the table have two rows: an amount of 100 with a fee of 5 and an amount of 200 without a fee (NULL).
-- rows: (amount 100, fee 5) and (amount 200, fee NULL)SELECTSUM(amount + fee) AS a, -- 105SUM(amount) + SUM(fee) AS b, -- 305SUM(amount + COALESCE(fee, 0)) AS c -- 305FROM transactions;
Arithmetic with NULL gives NULL at the row level: in the second row 200 + NULL is NULL and SUM skips that row entirely. So the first expression gives 105, and the two hundred vanished silently. The right total depends on the rule: if a missing fee means zero, the other two expressions give 305.
Where to put COALESCE
inside
AVG(COALESCE(amount, 0))
NULL counts as zero: the average over three rows is 100. Right if "no amount" means "zero".
outside
COALESCE(AVG(amount), 0)
NULLs are skipped: the average is 150. Zero appears only when there are no values at all.
Figure 2. Both variants are right but answer different questions. Which one is needed is decided by the business rule.
Limits and alternatives.COALESCE is in the SQL standard and works in all major databases, while dialect shortcuts differ: IFNULL (MySQL, SQLite), ISNULL (SQL Server), NVL (Oracle). To guard against division by zero there is NULLIF(x, 0): it returns NULL if the argument equals zero, and a division by NULL gives NULL instead of an error:
-- the failed percentage; NULLIF prevents division by 0SELECT ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'failed')
/ NULLIF(COUNT(*), 0), 1) AS failed_pct
FROM transactions
WHERE account_id = 999;
-- failed_pct: NULL (not a division by zero error)
A separate note about checks: COALESCE in a tester's query can hide a defect. If a column must hold a value and holds NULL, turning it into 0 makes the result "tidy" and unnoticeable. To check completeness, count the data as is, with COUNT(*) - COUNT(col), and substitute zeros only where the rule requires it.
Common mistakes.
Expecting 0 from SUM over an empty set: it is NULL, and the client shows an empty field or "NaN".
Forgetting that AVG ignores NULL: the average "over all" is really only over the filled ones.
Adding columns with NULL inside an aggregate (SUM(amount + fee)): the row with NULL drops out entirely.
Putting COALESCE inside when it is needed outside, and the other way round: it changes the arithmetic.
Comparing with NULL via = NULL: the result is always UNKNOWN, the right form is IS NULL.
Check yourself
Why does SELECT SUM(amount) FROM transactions WHERE account_id = 999 return NULL and not 0, and where will it do harm?
Answer
In SQL the sum of an empty set is NULL, because there is no value to add. The API will return null and the UI will show an empty field. The fix: COALESCE(SUM(amount), 0) outside the aggregate.
The amount column holds 100, NULL, 200. How do AVG(amount) and AVG(COALESCE(amount, 0)) differ?
Answer
The first ignores NULL and gives (100 + 200) / 2 = 150, the second counts NULL as zero and gives (100 + 0 + 200) / 3 = 100. The choice depends on whether "no value" means zero.
Rows: amount 100, fee 5 and amount 200, fee NULL. What does SUM(amount + fee) return and why is it dangerous?
Answer
105. In the second row 200 + NULL gives NULL and SUM skips the row entirely, so 200 vanished from the total without any error. SUM(amount + COALESCE(fee, 0)) = 305 is more correct.
Related lessons: “What is NULL and how does it differ from 0 and an empty string?”, “How do you find rows where the value is NULL?”, “How do COUNT(*), COUNT(col) and COUNT(DISTINCT col) differ?”.
In an interview.Junior: Aggregate functions ignore NULL, so the average is computed only over the filled values. The sum over an empty set returns not zero but NULL, and if the code does not expect it, an empty field or an error appears on screen. To substitute a default value I use COALESCE. Middle/Senior: I watch where COALESCE sits: inside an aggregate NULL becomes zero and changes the average, outside it only closes an empty result. Row-level arithmetic with NULL removes the row from SUM, so I wrap a fee in COALESCE. For division I use NULLIF, and in checks I count NULLs first and replace them afterwards.
How do you use CASE WHEN and conditional aggregation?
Conditional aggregation puts CASE WHEN inside an aggregate, so one pass counts both all rows and only the needed ones. Without ELSE, CASE returns NULL, which the aggregate skips, so no ELSE branch is written inside COUNT: 0 is not NULL and the counter would count everything. PostgreSQL has a shorter form, FILTER (WHERE …). A percentage is multiplied by 100.0 because integer division in PostgreSQL drops the fraction.
SQL · Aggregates
A report: total, failed and the failed percentage for each transaction type. Three queries or one?
A tester checks a dashboard: for each transaction type it must show the total count, the failed count and their percentage. Three separate queries mean three passes over the table and three results that still have to be merged. Conditional aggregation does it all in one pass. This lesson is about CASE, how it works inside an aggregate, and the three traps people fall into most often.
How it works and why.CASE is an expression, not a statement: for each row it checks the WHEN conditions top to bottom and returns the THEN of the first true one. If none matched and there is no ELSE, the result is NULL. Inside an aggregate, CASE decides which value the function sees for each row. Because aggregates skip NULL, an expression without ELSE simply "switches off" the extra rows. PostgreSQL also has a shorter form for this, FILTER (WHERE …), introduced in 9.4, available in SQLite from 3.30 and absent in MySQL and SQL Server.
One pass instead of three queries
transactions
type
status
amount
deposit
completed
100
deposit
failed
50
deposit
completed
150
withdrawal
failed
20
withdrawal
completed
80
result
type
total
failed
failed_pct
deposit
3
1
33.3
withdrawal
2
1
50.0
Figure 1. Every row goes into COUNT(*) and, if its status is failed, into the conditional counter; grouping splits them by type.
Example: a report in one query. What the dashboard needs:
SELECT type,
COUNT(*) AS total,
COUNT(*) FILTER (WHERE status = 'failed') AS failed,
ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'failed')
/ COUNT(*), 1) AS failed_pct
FROM transactions
GROUPBY type;
-- PostgreSQL; MySQL has no FILTER, see below
MySQL and SQL Server have no FILTER, so the same logic is written with CASE:
-- portable form: works everywhereSELECT type,
SUM(CASEWHEN status = 'failed'THEN1ELSE0END) AS failed,
SUM(CASEWHEN status = 'completed'THEN amount ELSE0END) AS completed_volume
FROM transactions
GROUPBY type;
Here ELSE 0 is deliberate: SUM then returns 0 when no row matched, while without ELSE it would return NULL. For the percentage there is one more danger. In PostgreSQL dividing two integers drops the fractional part:
So the percentage is multiplied by 100.0, not 100: the expression then becomes decimal. In MySQL the / operator returns a decimal result anyway, while PostgreSQL, SQL Server and SQLite use integer division, so code that worked in one database gives a different number in another.
A counter through CASE
wrong
COUNT(CASE … THEN 1 ELSE 0 END)
COUNT counts everything that is not NULL, and 0 is not NULL. The result equals COUNT(*): for deposit it gives 3 although only one is failed.
right
COUNT(CASE … THEN 1 END)
Without ELSE the extra rows give NULL and COUNT skips them. For deposit the result is 1. Or SUM(CASE … THEN 1 ELSE 0 END).
Figure 2. COUNT counts non-NULL, so ELSE 0 breaks a conditional counter.
Limits and alternatives. The same CASE sorts values into categories. The order of branches matters: the first true one wins, so the narrower condition goes higher. At the edges check the boundary values (99, 100, 999, 1000):
The simple CASE status WHEN 'failed' THEN … compares only for equality, and NULL equals nothing, so a WHEN NULL branch never fires: for empty values you write WHEN status IS NULL in the searched form. Branches must give compatible types: THEN 'a' ELSE 0 fails in PostgreSQL. If the denominator can be zero (a query without GROUP BY over an empty selection, or types from a lookup table joined with LEFT JOIN and COUNT(t.id) as the denominator), protect it with NULLIF(…, 0), as in the previous lesson about NULL. A query with GROUP BY type has no empty groups.
Common mistakes.
COUNT(CASE … ELSE 0 END) instead of an ELSE-less form: the counter counts all rows.
A percentage through integer division: 33 instead of 33.3 (in PostgreSQL, SQL Server, SQLite).
CASE branches in the "wrong" order: the narrower condition is unreachable after the wider one.
A forgotten boundary in ranges: < 100 and <= 100 send the amount 100 to different categories.
Dividing by a count without a zero guard: when the denominator is 0, PostgreSQL fails the query with an error, while MySQL silently returns NULL.
Check yourself
What does COUNT(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) return for a group of three transactions, one of which failed?
Answer
3. The ELSE branch gives 0, and 0 is not NULL, so COUNT counts all three rows. The right COUNT(CASE WHEN status = 'failed' THEN 1 END) gives 1, or SUM(CASE WHEN … THEN 1 ELSE 0 END).
In PostgreSQL the expression 100 * failed / total gives 33 for failed = 1 and total = 3. Why and how do you fix it?
Answer
All three values are integers, so the division is integer and drops the fraction. Multiply by 100.0 (or cast to numeric): 100.0 * 1 / 3 = 33.3333. In MySQL the / operator returns a decimal result without that.
For CASE WHEN amount < 100 THEN 'small' WHEN amount < 1000 THEN 'medium' ELSE 'large' END, which category do the amounts 100 and 1000 fall into?
Answer
100 falls into medium (amount < 100 is false and amount < 1000 is true), 1000 into large. That is why range checks take values at the boundaries: 99, 100, 999, 1000.
Related lessons: “How does GROUP BY work?”, “How does WHERE differ from HAVING?”, “Task: the percentage of failed transactions for each type.”.
In an interview.Junior: CASE WHEN is conditional logic in a query, like if-else. It is most useful combined with aggregates: in one query I can count the total, the failed ones and their percentage for each transaction type. Middle/Senior: Inside COUNT I do not write an ELSE branch, because 0 is not NULL and the counter would count everything, while for sums ELSE 0 is fine. I multiply the percentage by 100.0, not 100: in PostgreSQL integer division drops the fraction. I check the order of branches and range boundaries with separate values. Where there is no FILTER, I switch to SUM(CASE …).
WHERE vs HAVING and grouping
WHERE filters rows before grouping and HAVING filters groups by aggregates, and a JOIN runs even earlier, so the aggregate counts the already joined rows. A condition on a single order (paid) goes into WHERE, a condition on the total (more than 5) into HAVING. Grouping is by the unique id, not by name, because namesakes would merge, and after a one-to-many JOIN entities are counted with COUNT(DISTINCT id).
SQL · Aggregates
Find users with more than 5 orders, with their name. Where does the JOIN go and what do you group by?
A tester checks the "active buyers" segment: users with more than five paid orders, together with a name for the report. The aggregate over the orders table knows only user_id, while the name lives in users. That raises two questions: what to group by and where to filter "paid". The lesson “How does WHERE differ from HAVING?” covered the difference between WHERE and HAVING, and this one shows how it works in a query with a JOIN.
How it works and why. Logically a query goes through the steps FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT. So the JOIN runs before grouping, and the aggregate counts already joined rows. Two decisions follow. The grouping key must identify the entity unambiguously, that is it must be u.id, not u.name. And the name is added to GROUP BY only so it can be displayed (in PostgreSQL and MySQL the primary key is enough, but an explicit list is portable).
What to take as the grouping key
wrong
GROUP BY u.name
Two different users named Ivan with 3 orders each merge into one group with 6 orders and enter the selection, although neither has more than 5.
right
GROUP BY u.id, u.name
id is unique, so groups match users. name is added only for display.
Figure 1. A name is not unique, so it is never a grouping key.
Example: from the task to the query. The task splits into three conditions. "Paid" is about a single order, so it goes in WHERE. "More than 5" is about a total per user, so it goes in HAVING. And the name is attached through a JOIN:
SELECT u.id, u.name, COUNT(*) AS orders_count
FROM orders o
JOIN users u ON u.id = o.user_id
WHERE o.status = 'paid'-- row filterGROUPBY u.id, u.name -- key: id; name for displayHAVINGCOUNT(*) > 5-- group filterORDERBY orders_count DESC, u.id; -- u.id breaks ties
Groups after GROUP BY and the result
GROUP BY u.id, u.name
id
name
orders_count
1
Anna
7
2
Ivan
3 filtered out
3
Ivan
3 filtered out
4
Olha
6
result
id
name
orders_count
1
Anna
7
4
Olha
6
Figure 2. Both Ivans stay separate groups of 3 orders, and HAVING drops both.
In ORDER BYu.id follows the count: without it, users with the same number of orders can come back in a different order between runs, and a test comparing the list becomes unstable.
Limits and alternatives. The name can also be attached after aggregation: first count by user_id in a subquery or CTE and then join with users. That way grouping works with one narrow column and the JOIN runs over a small result:
-- aggregate by id first, then JOIN for the namesWITH busy AS (
SELECT user_id, COUNT(*) AS orders_count
FROM orders
WHERE status = 'paid'GROUPBY user_id
HAVINGCOUNT(*) > 5
)
SELECT u.id, u.name, b.orders_count
FROM busy b
JOIN users u ON u.id = b.user_id
ORDERBY b.orders_count DESC, u.id;
The "paid only" filter stays in WHERE in every variant. If the join is a LEFT JOIN, a condition on the right side must not go in WHERE (see the lesson about a condition in ON and in WHERE), otherwise it turns the join into an inner one. A separate risk: one more "one-to-many" JOIN multiplies rows.
-- after a JOIN with order_items each order has several rowsSELECT o.user_id,
COUNT(*) AS item_rows, -- counts itemsCOUNT(DISTINCT o.id) AS orders -- counts ordersFROM orders o
JOIN order_items i ON i.order_id = o.id
GROUPBY o.user_id;
If order items are added, COUNT(*) counts items rather than orders, so the threshold "more than 5" fires too early. For the number of orders you need COUNT(DISTINCT o.id). Finally, HAVING cannot find users without orders: no groups exist for them.
-- always 0 rows: there are no groups for users without ordersSELECT user_id FROM orders
GROUPBY user_id
HAVINGCOUNT(*) = 0;
-- right: users without a matchSELECT u.id
FROM users u
LEFTJOIN orders o ON o.user_id = u.id
WHERE o.id ISNULL;
Common mistakes.
Grouping by name instead of id: namesakes merge and the numbers are distorted.
Writing the "paid" condition in HAVING or forgetting it: all orders are counted.
Adding a "one-to-many" JOIN and keeping COUNT(*): join rows are counted, not entities.
ORDER BY only by the count: the order among equal values is random.
Looking for missing records through HAVING COUNT(*) = 0: there will never be rows.
Check yourself
Two different users are named Ivan, with 3 orders each. What happens if you group by u.name and add HAVING COUNT(*) > 5?
Answer
Grouping by name merges them into one group with 6 orders, and it passes HAVING although neither user has more than 5. You must group by u.id (and add name beside it for display).
Why does SELECT user_id FROM orders GROUP BY user_id HAVING COUNT(*) = 0 never return anything? How do you find users without orders?
Answer
Groups are built only from existing rows, and a user without orders has no rows in orders, so there is no group either. You need a LEFT JOIN with an o.id IS NULL check or NOT EXISTS.
After a JOIN with order_items the number of orders per user suddenly grew. Why and what should change?
Answer
Each order now takes as many rows as it has items, and COUNT(*) counts items. For orders you need COUNT(DISTINCT o.id), or count the orders in a subquery before the join.
Related lessons: “How does WHERE differ from HAVING?”, “How does GROUP BY work?”, “What is the difference between a condition in ON and in WHERE with a LEFT JOIN?”, “How do you find records that have no match in another table?”.
In an interview.Junior: WHERE filters rows before grouping and cannot work with aggregates, while HAVING filters the already formed groups. For users with more than 5 orders I do GROUP BY user_id and HAVING COUNT(*) greater than 5. If a name is needed, I add a JOIN with users and group by id and name. A filter such as "only paid" goes in WHERE so it runs before grouping. Middle/Senior: I take the unique id as the grouping key, not the name, because namesakes would merge. I watch that a "one-to-many" JOIN multiplies rows, so I count COUNT(DISTINCT) or aggregate before the join. For a deterministic order I add a unique column to ORDER BY, and I look for missing records with a LEFT JOIN, not HAVING.