Skip to the page

SQL querying · Write code

Aggregate in WHERE

The interviewer asks

This query should list cities with more than 100 orders in 2026, but it throws an error. What's wrong, and how do you fix it?

SELECT city, COUNT(*) AS order_count
FROM orders
WHERE COUNT(*) > 100 AND created_at >= '2026-01-01'
GROUP BY city;

Then

Follow-ups the interviewer asks next

  1. In what order does the database logically run FROM, WHERE, GROUP BY, HAVING, SELECT and ORDER BY?
  2. Can HAVING use the alias order_count?
  3. Should the date filter go in WHERE or HAVING, and does it matter for speed?
  4. What happens if you select a column that is not in GROUP BY, in MySQL and in PostgreSQL?

The answer

What a strong answer covers

  • Aggregates can't appear in WHERE. WHERE filters rows before grouping; HAVING filters groups after.
  • Fix: WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01' GROUP BY city HAVING COUNT(*) > 100. Also notices the missing upper bound for "in 2026".
  • Logical order: FROM and JOIN, WHERE, GROUP BY, HAVING, SELECT (and window functions), DISTINCT, ORDER BY, LIMIT.
  • Row filters belong in WHERE: fewer rows to group, and an index on created_at can be used.
  • PostgreSQL does not allow output aliases in HAVING (it does in ORDER BY); MySQL allows them as an extension.
  • Non-grouped columns: PostgreSQL errors unless the column depends on a grouped primary key; MySQL errors too with ONLY_FULL_GROUP_BY, on by default since 5.7.

The red pen

Common traps

Avoid:moving every condition into HAVING; using a SELECT alias in WHERE.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview