SQL querying · Write code
Aggregate 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 voiceThe 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
- In what order does the database logically run FROM, WHERE, GROUP BY, HAVING, SELECT and ORDER BY?
- Can HAVING use the alias
order_count? - Should the date filter go in WHERE or HAVING, and does it matter for speed?
- 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_atcan 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 voicePractise 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.