Departments With at Least 3 Employees
SQLGROUP BYMidSeniorUpdated
Return the names of departments that have at least 3 employees, alphabetically sorted.
Schema
CREATE TABLE employees (
id BIGINT PRIMARY KEY,
department TEXT NOT NULL
);Drill This: Your Query First
The Correct Query
Option (b)
SELECT department
FROM employees
GROUP BY department
HAVING COUNT(*) >= 3
ORDER BY department;Filtering aggregates requires HAVING, which runs after GROUP BY. (a) and (c) try to use WHERE on COUNT(*), which is a syntax error because WHERE is evaluated before grouping. (d) applies HAVING to the whole result set (no GROUP BY), so it returns either all departments or none depending on the total row count.
The Options That Fail
The explanation above says why each of these breaks.
Option (a)
SELECT department
FROM employees
WHERE COUNT(*) >= 3
GROUP BY department
ORDER BY department;Option (c)
SELECT department
FROM employees
GROUP BY department
WHERE COUNT(*) >= 3
ORDER BY department;Option (d)
SELECT DISTINCT department
FROM employees
HAVING COUNT(*) >= 3
ORDER BY department;