Faragiri

Learn Grouping and aggregation SQL

Two counts on the same rows giving different answers, the count that is wrong after every left join, and the rule engines disagree about.

4Sections
3Min read
4Depth

Recommended Before This

0 / 2
  • SQL
  • SELECT

Two counts on the same four rows give different answers.
COUNT(*) answers 4 and COUNT(maker_id) answers 3,
measured on MySQL 8.4 on 2026-09-02, because one kiln has no maker.
COUNT(*) counts rows and COUNT(column) counts rows
where that column is not null, and the difference between them is a null
count.

Every other aggregate follows the same rule and it is the one to carry:
aggregates ignore NULL. SUM(litres) over those
kilns answers 460 and AVG(litres) answers 115, which is 460 divided
by 4 rather than by the number of rows, because in this data every kiln has a
litres value. Where a column does have nulls, the average divides by the
non-null count, so an average is over the rows that had a number rather than
over the rows.

The wrong count after a left join

This is the error that reaches a report. Joining makers to kilns with a left
join and counting per maker:

Four rows, two counts

What each form of COUNT is actually counting

The two agree on a plain table and disagree the moment a null or a left join is involved, which is where every wrong report comes from.

COUNT(*)Counts rows
COUNT(column)Counts rows where the column is not null
Four kilns, one with no maker43
After a left join, for a maker with none1, and it is wrong0, which is the answer meant
On a plain table with no nullsThe sameThe same
What it is askingHow many rows are hereHow many of these have a value
After a join that multiplied rowsToo highAlso too high

The last row has no winner: neither form protects you from a join producing two rows where you expected one. That is a different bug and it is found by removing the aggregate rather than by changing it.

Interactive Practice Lab

Edit and run this snippet directly in your browser (zero setup)

SQL
CREATE TABLE workshop_orders (id INTEGER PRIMARY KEY, supplier TEXT, qty INTEGER, city TEXT);INSERT INTO workshop_orders VALUES (1, 'Sepehr', 15, 'Ardabil'), (2, 'Aria', 47, 'Tabriz'), (3, 'Sepehr', 22, 'Ardabil'), (4, 'Nima', 31, 'Tehran');SELECT supplier, COUNT(*) AS deliveries, SUM(qty) AS total_qtyFROM workshop_ordersGROUP BY supplierORDER BY total_qty DESC;

Live Big-O Complexity & Binary Search Race Lab

Compare complexity curves at scale and watch Linear vs Binary Search race live.

  • Nasim | 2 | 2
  • Behrouz | 1 | 0
  • Roya | 1 | 1
  • Kaveh | 1 | 0

The middle column is COUNT(*) and the last is
COUNT(k.id). Behrouz has no kilns and COUNT(*) says 1,
because the left join produced one row for him with nulls in the kiln columns
and that row is still a row. Counting a column from the joined side gives 0,
which is the answer meant. After a left join, never count star.

GROUP BY, HAVING and the rule engines disagree about

GROUP BY town collapses the rows into one per town, and every
selected column must either be in the GROUP BY or inside an aggregate. Postgres
enforces that strictly; MySQL historically did not and would return an arbitrary
value from the group, which is the source of results that differ between
engines for the same query.

Clause order

Why WHERE cannot filter by a group count and HAVING can

SQL builds groups and computes aggregates before HAVING runs, while engines differ on ungrouped columns.

  1. 01Filter raw rows with WHERERuns before groups exist, so putting COUNT(*) > 1 here is an error.
  2. 02Collapse rows with GROUP BY townPostgres requires every selected column to be grouped or aggregated; older MySQL returned an arbitrary value.
  3. 03Compute group aggregatesProduces per-town counts and summaries across each collapsed group.
  4. 04Filter groups with HAVINGRuns after counts exist, making HAVING COUNT(*) > 1 valid for keeping multi-maker towns.

Differences between strict Postgres grouping and older permissive MySQL defaults explain why the same query can behave differently across engines.

HAVING filters the groups after they exist, so
HAVING COUNT(*) > 1 is the way to ask for towns with more than
one maker, and the same condition in WHERE is an error because the count does
not exist yet. That is the clause order from
choosing rows and columns
made visible.

What to run in 2026

Window functions are the tool worth learning next, free and available in
every current engine.
COUNT(*) OVER (PARTITION BY town) gives the group's count on every
row without collapsing the rows, which is the thing GROUP BY cannot do and which
people usually solve with a subquery or a second query. It replaced joining a
table to an aggregate of itself.

Modern SQL

Replacing extra queries with window functions and FILTER

Current SQL engines compute row-level group counts and multiple conditional totals in a single pass.

Multi-query workaroundsSubqueries, self-joins, and repeated GROUP BY passes.
  1. 01COUNT(*) OVER (PARTITION BY town)Attaches the group count to every row without collapsing rows, replacing self-joins.
  2. 02COUNT(*) FILTER (WHERE litres > 100)Or CASE inside an aggregate; counts subsets in one scan instead of running three GROUP BY queries.
Single-pass 2026 SQLFree and standard across modern database engines.

Window functions keep row detail intact while conditional aggregates fold several filtered counts into one pass.

FILTER or a CASE inside an aggregate is the second,
free and standard. COUNT(*) FILTER (WHERE litres > 100) counts a
subset within the same pass, so several conditional counts come from one query
rather than from one query each. It replaced running the same GROUP BY three
times with different WHERE clauses.

Where this stalls people

The stall is an aggregate that is quietly wrong rather than an error. Nothing
in the four rows above is flagged: the query runs, returns numbers, and one of
the columns is meaningless. A total that is too high usually means a join
multiplied rows, and a count that is too high usually means
COUNT(*) after a left join.

Debugging totals

Why wrong aggregates pass silently and how one run reveals them

A broken aggregate query succeeds with plausible numbers, hiding row inflation underneath.

  • Query runs without errorsReturns clean summary numbers with no warning flagged.
Aggregate output looks valid
  • Left join padded unmatched makers with null rowsInflates COUNT(*) when you meant to count joined child records.
  • Join multiplied rows before SUM ranProduces totals that are quietly too high across duplicated rows.
  • Remove the aggregate to inspect raw rowsCounting unaggregated rows by eye exposes both bugs in one run.

Almost every aggregation bug is invisible after collapsing rows and immediately obvious once you inspect the unaggregated join output.

The check takes one run: remove the aggregate, look at the rows, and count
them by eye against what you expected. Almost every aggregation bug is visible
there and invisible in the aggregated result. The join underneath is
combining tables, and the four
kinds
, and the nested version of the same questions is
a query inside a query, and
when to avoid one
, inside
the language for asking a database
questions
.

Alongside this

Above this