QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › Aggregation

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

FROM transactions10 rowsWHERE failed + September7 rows: a row filterGROUP BY user_id3 groups: 4, 1 and 2 rowsHAVING COUNT(*) > 31 group: a group filter
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'
  AND COUNT(*) > 3
GROUP BY 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 filter
  AND t.created_at >= '2026-09-01'
  AND t.created_at <  '2026-10-01'
GROUP BY a.user_id
HAVING COUNT(*) > 3;                      -- group filter

What HAVING drops

after GROUP BY
user_idfailed_cnt
14
21 filtered out
32 filtered out
result
user_idfailed_cnt
14
Figure 2. HAVING COUNT(*) > 3 keeps only the group of user 1: the other two have three failures or fewer.

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.

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 user
SELECT 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'
GROUP BY a.user_id
HAVING COUNT(*) 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 place
SELECT a.user_id, t.status, COUNT(*) AS cnt
FROM transactions t
JOIN accounts a ON a.id = t.account_id
GROUP BY a.user_id, t.status
HAVING t.status = 'failed' AND COUNT(*) > 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).

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.

More articles in this chapter