Paths Subjects Questions Quizzes Pricing Search
Beginner Open Pro

Rewriting a Query That Confuses WHERE and HAVING

A teammate writes this query to find departments that hired more than 5 people in 2020 or later, and it fails with a database error:

SELECT department, COUNT(*) AS headcount
FROM employees
WHERE hire_date >= '2020-01-01' AND COUNT(*) > 5
GROUP BY department;
  1. Identify precisely which part of this query is invalid, and explain why using the logical query processing order — don't just say "aggregates can't go in WHERE," explain why they can't.
  2. Fix the query so it correctly answers the original question: departments with more than 5 hires since 2020-01-01.
  3. Now extend the question: the team also wants to see the average salary of recent hires in those departments, but only counting employees hired in 2020 or later toward both the headcount and the average — employees hired earlier should not affect the average either. Write the full query and explain which clause is responsible for excluding the pre-2020 employees from the average salary calculation, and why that's the right clause for the job.

Share this question

← Back to SQL Mental Model & Query Execution Order practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.