December 5, 2026

SQL GROUP BY and HAVING: WHERE vs HAVING, COUNT(*) vs COUNT(column), and the Bare-Column Trap

Receipts sorted into separate trays on a desk

Every “total sales per customer” report in SQL runs through the same three clauses: WHERE, GROUP BY and HAVING. They look interchangeable in simple queries and give different answers the moment the data has refunds, missing values or a customer with no name. Running the same nine-row orders table through SQLite 3.53.1 and DuckDB 2.0.1 shows what each clause does, where the two engines agree, and the one query SQLite answers happily while DuckDB refuses it outright.

Video: Alex The Analyst on YouTube

The test table

Nine orders

The experiments used one small table, built identically in both databases:

id customer status amount
1 ana paid 120
2 ana paid 80
3 ana refunded 50
4 ben paid 300
5 ben pending NULL
6 cy paid 20
7 cy paid 25
8 cy paid 30
9 NULL paid 40

It is small enough to check by hand, and it contains the three things that cause most grouping bugs: rows that should not count (the refund), a missing amount (ben’s pending order) and a missing customer name (order 9).

The basic grouping

SELECT customer, count(*), sum(amount) FROM orders GROUP BY customer returned four groups in both engines: NULL with 1 order totaling 40, ana with 3 orders totaling 250, ben with 2 orders totaling 300 and cy with 3 orders totaling 75. Two details are already visible. The order with no customer formed its own group rather than disappearing. And ben’s total was 300, not NULL, because sum() skipped the missing amount instead of treating it as zero or poisoning the total.

A green colander full of white eggs

WHERE filters rows, HAVING filters groups

The rule

PostgreSQL’s tutorial states the difference in one sentence: “WHERE selects input rows before groups and aggregates are computed (thus, it controls which rows go into the aggregate computation), whereas HAVING selects group rows after groups and aggregates are computed.” PostgreSQL documentation, Aggregate Functions

Seeing it

Adding WHERE status = 'paid' changed ana’s total from 250 to 200, because the refunded order was removed before summing. Every other total stayed the same, since nobody else had a non-paid order with an amount.

HAVING sum(amount) > 100 instead kept the groups whose total exceeded 100, which were ana (250) and ben (300), and dropped cy and the unnamed customer. The totals themselves did not change; whole groups disappeared.

Both at once

The real power is in combining them. This query asks for customers with at least two paid orders, and the total of those paid orders:

SELECT customer, sum(amount) AS total
FROM orders
WHERE status = 'paid'
GROUP BY customer
HAVING count(*) >= 2;

It returned ana with 200 and cy with 75. Ben was gone: after WHERE removed his pending order, he had only one row left, so his group failed the HAVING test. The order of operations decided the answer. Moving the status test into HAVING would not even make sense, because status is not a single value per group.

Aggregates belong in HAVING, not WHERE

What the engines said

Writing WHERE sum(amount) > 100 is the most common GROUP BY mistake, and both engines rejected it. SQLite answered misuse of aggregate: sum(). DuckDB answered Binder Error: WHERE clause cannot contain aggregates!

The PostgreSQL tutorial explains the logic: “the WHERE clause must not contain aggregate functions; it makes no sense to try to use an aggregate to determine which rows will be inputs to the aggregates.” The sum does not exist yet when WHERE runs.

HAVING on plain columns

The reverse direction is allowed but rarely wise. HAVING customer LIKE 'c%' worked in SQLite and returned cy’s group. The same filter in WHERE would remove the other rows before grouping and do the same job more cheaply. SQLite’s documentation also describes what happens when a HAVING expression is not an aggregate: it “is evaluated with respect to an arbitrarily selected row from the group.” SQLite, SELECT For a column that is the same across the group, like the grouping column itself, that is harmless. For anything else, it is a hidden coin toss.

HAVING without GROUP BY

SELECT count(*) FROM orders HAVING count(*) > 5 returned 9 in both engines. With no GROUP BY, the whole table is one group, and HAVING decides whether that single summary row appears at all. Changing the threshold to 10 would return no rows instead of a row containing zero.

White printer paper

COUNT(*) is not COUNT(column)

Ben’s two orders

For ben, count(*) returned 2, count(amount) returned 1 and avg(amount) returned 300.0. count(*) counts rows. count(amount) counts rows where amount is not NULL. And avg() divided the sum by the non-NULL count, 300 / 1, not by both rows.

That average is the kind of number that looks reasonable in a report and is quietly wrong for many purposes. If the pending order should count as zero, the query has to say so with coalesce(amount, 0) inside the aggregate; if it should not count at all, the current answer is right. SQL will not guess which was meant.

Counting distinct values

The same NULL rule applies to count(DISTINCT ...). Over the whole table, both engines returned 9 for count(*), 8 for count(customer) and 3 for count(DISTINCT customer). The unnamed order counted as a row but not as a customer, and it did not count as a fourth distinct customer either, even though GROUP BY had given it a group of its own. A dashboard that shows “3 customers” next to a grouped table with four rows is not broken; the two numbers answer different questions, and the difference is exactly the NULL.

Conditional totals with FILTER

Sometimes the goal is several totals per group, each with its own condition. The FILTER clause does that. PostgreSQL’s tutorial describes it as “much like WHERE, except that it removes rows only from the input of the particular aggregate function that it is attached to.”

SELECT customer,
  sum(amount) FILTER (WHERE status = 'paid') AS paid,
  sum(amount) FILTER (WHERE status = 'refunded') AS refunded
FROM orders
GROUP BY customer;

Both SQLite and DuckDB accepted it and gave ana 200 paid and 50 refunded, with refunded as NULL for every customer who had no refunds. One pass over the table produced both columns.

The bare-column trap

SQLite allows it

The sharpest difference between the two engines appeared with a query that names a column that is neither grouped nor aggregated:

SELECT customer, status, max(amount) FROM orders GROUP BY customer;

DuckDB refused: column "status" must appear in the GROUP BY clause or must be part of an aggregate function. SQLite returned a row per customer, and for ana it reported paid with 120.

What SQLite does with it

SQLite documents this behavior and gives it special handling when the aggregate is min() or max(). If there is exactly one such aggregate, “all bare columns in the result set take values from an input row which also contains the minimum or maximum.” So ana’s status came from her 120 order, which was paid. Switching to min(amount) returned refunded with 50, from her smallest order, exactly as documented.

And when it is not min or max

With sum(amount), SQLite still returned a status for ana (paid in this run), but its documentation says that in this case a bare column “will take on the value of an arbitrary row from the aggregate’s input. The particular row chosen might change from one invocation to the the next.” A report built on that query can change its output after an index is added or the data is reordered, with no error anywhere.

The safe habit is the rule DuckDB enforces: every selected column is either in GROUP BY or inside an aggregate. Code written that way runs on SQLite, DuckDB, PostgreSQL and the rest without surprises.

A laptop and a mug on a table

NULLs, aliases and a working order

The NULL group

The order with no customer showed up as its own group with a NULL key. Grouping treats all NULLs as one group even though NULL = NULL is not true in a WHERE clause. Reports that list customers often filter it out with WHERE customer IS NOT NULL, or label it with coalesce(customer, '(none)').

Aliases in HAVING

HAVING total > 100, using the SELECT alias instead of repeating sum(amount), worked in both SQLite and DuckDB. Standard SQL does not promise that, and some databases reject it, so repeating the expression is the portable choice.

A mental model

Writing the clauses in the order the database logically processes them helps:

  1. FROM: pick the table.
  2. WHERE: drop rows that should not count.
  3. GROUP BY: form groups.
  4. Aggregates: compute count, sum, avg for each group.
  5. HAVING: drop groups that fail a test.
  6. SELECT and ORDER BY: shape the output.

Any condition about individual rows goes before the grouping. Any condition about totals goes after it. When a query returns totals that look too high, the first thing to check is whether a row-level condition ended up in HAVING or was left out entirely; when it returns too few groups, check whether a total-level condition was applied too early.

Sources

  • PostgreSQL documentation, 2.7. Aggregate Functions: https://www.postgresql.org/docs/current/tutorial-agg.html
  • SQLite documentation, SELECT (HAVING clause and bare columns): https://www.sqlite.org/lang_select.html

920 Posts

Peter Kalafatis writes and edits X9M8. He holds a bachelor's degree from LIU Post and a master's in Media Studies from The New School, with academic work in the philosophy of science, human behavior, AI, and memetics.

View All Posts

Leave a Reply

Your email address will not be published. Required fields are marked *