Black Friday Sale20% off every plan — this weekend onlyEnds in04days11hrs51min51secSee plans

WHERE vs HAVING in SQL: the difference with examples

SQL Updated 1 min read By LogicByte team

Short answer

WHERE filters individual rows before they are grouped. HAVING filters groups after GROUP BY, so it can use aggregate functions such as COUNT, SUM and AVG. You can use both in one query.

On this page
  1. The difference at a glance
  2. Example: using both
  3. The common mistake
  4. Interview tip

The difference at a glance

WHEREHAVING
FiltersRowsGroups
RunsBefore GROUP BYAfter GROUP BY
Can use COUNT, SUM, AVGNoYes
Works without GROUP BYYesRarely useful
SpeedFaster — fewer rows to groupRuns on grouped results

Example: using both

Show cities with more than 50 orders in 2026:

SELECT city, COUNT(*) AS orders
FROM orders
WHERE order_date >= '2026-01-01'      -- rows: only 2026
GROUP BY city
HAVING COUNT(*) > 50;                  -- groups: only busy cities

The common mistake

-- Error: aggregate in WHERE
SELECT city FROM orders WHERE COUNT(*) > 50 GROUP BY city;

WHERE runs before rows are grouped, so COUNT has nothing to count yet. Move the condition to HAVING.

Interview tip

If a condition does not need an aggregate, put it in WHERE even when the query has GROUP BY. Filtering early means less data to group, which is faster.

Try it yourself

5 questions from the LogicByte practice bank. Pick an answer to check it.

  1. 1Which query returns all rows where status is 'Active'?

    SELECT *
    FROM Users
    WHERE status = 'Active';
    Show answer

    Answer: D — SELECT * FROM Users WHERE status = 'Active';

    WHERE filters rows based on a condition.