The Order SQL Runs In
You write SELECT first, but the database runs it almost last. Knowing the real order explains most confusing errors.
The order SQL actually runs in:
FROMandJOIN: gather the rowsWHERE: filter single rowsGROUP BY: form groupsHAVING: filter groupsSELECT: compute columns and aliasesORDER BY: sortLIMIT: cut
That's why this fails. WHERE runs before any groups exist, so there's no count to check yet:
SELECT department_id, COUNT(*)
FROM employees
WHERE COUNT(*) > 3
GROUP BY department_id;Move the condition to HAVING, which runs after grouping:
It's also why ORDER BY can use an alias from SELECT while WHERE usually can't. SQLite is lenient here, but PostgreSQL, MySQL and SQL Server aren't.
Check your understanding
Why can't you write WHERE COUNT(*) > 3?
Examples run on the employees sample database. Open any of them in the playground to experiment.