SQL error · GROUP BY and calculations

COUNT or SUM does not work in WHERE

Problem: WHERE evaluates rows before the aggregate exists.

Solution: Use HAVING for the condition on the aggregate and keep the per-row conditions in WHERE.

Why it happens: COUNT or SUM does not work in WHERE

Problem SQL
WITH sales(category, amount) AS (
  VALUES ('A', 10), ('A', 20), ('A', 30),
         ('B', 5),  ('B', 7)
)
SELECT category, COUNT(*) AS sales
FROM sales
WHERE COUNT(*) >= 3
GROUP BY category;

The condition depends on COUNT(*), which only exists after grouping. Shuffling keywords around will not fix it: first work out whether you are filtering rows or groups.

Check the result with small data

Team A goes over the threshold once its two sales are added together.

Self-contained query · SQLite
WITH sales(team, amount) AS (
  VALUES ('A',10),('A',7),('B',4)
)
SELECT team, SUM(amount) AS total
FROM sales GROUP BY team
HAVING SUM(amount) > 10;
Query result
teamtotal
A17

HAVING filters groups once they are calculated. A condition WHERE amount > 10 would remove both of A's sales before adding them up and give the wrong result.

Check your understanding: Why is A's total 17 even though no single row exceeds 10?

Show answer

Because HAVING compares the group's sum (10 + 7 = 17), not each row. No single sale exceeds 10, but A's total does.

“COUNT or SUM does not work in WHERE” error messages by engine

The exact wording depends on the database. Compare these common messages with the one in your console.

EngineTypical message
PostgreSQLERROR: aggregate functions are not allowed in WHERE
MySQLERROR 1111 (HY000): Invalid use of group function
SQL ServerMsg 147, Level 15: An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
OracleORA-00934: group function is not allowed here
SQLiteError: misuse of aggregate function COUNT()

How to fix it in SQL

Fixed SQL
WITH sales(category, amount) AS (
  VALUES ('A', 10), ('A', 20), ('A', 30),
         ('B', 5),  ('B', 7)
)
SELECT category,
       COUNT(*) AS sales,
       SUM(amount) AS total
FROM sales
GROUP BY category
HAVING COUNT(*) >= 3;
Result: only the group with at least three sales remains
categorysalestotal
A360

How to check it

Check which rows take part before grouping and which groups remain after HAVING.

How to avoid it next time

WHERE decides what goes in; HAVING decides which summaries to show.

Related cases worth checking

They are not mutually exclusive. Use WHERE to decide which rows go into the calculation and HAVING to decide which groups remain afterwards.

Two filtering stages
SELECT category, COUNT(*) AS valid_sales
FROM sales
WHERE amount >= 10
GROUP BY category
HAVING COUNT(*) >= 2;

First, sales with an amount under 10 are removed. Then the remaining rows are grouped, and only the groups with at least two records are kept.

Separate the population being measured from the group being retained

To count paid orders per customer and show customers with at least two payments, you need two rules applied at different stages. WHERE status = 'paid' decides which orders are counted. HAVING COUNT(*) >= 2 decides which groups survive once they have been measured. Swapping one for the other changes the question, even if the statement still runs.

Test a customer with three orders, only one of them paid. Counting every order first can put them over the threshold of two; filtering for payments first leaves them out. Also add a customer with no payments to see that grouping filtered orders does not invent a row with zero. If every customer must appear, you need to start from the customers and design the relationship with their transactions.

When the condition uses a measure calculated in another query, the outer WHERE can filter it like an ordinary column. That does not contradict the logical order: the aggregation has already happened inside. For a clear check, show the count without the HAVINGfirst, confirm that each group measures the right population and then apply the threshold. Do not rely on aliases in HAVING without checking your engine's rules.

Technical questions: PostgreSQL: Table Expressions and Joins (opens in a new tab).