Interview Q&A / SQL & DBMS

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

Write a query to list departments that have more than 5 employees.

SHORT ANSWER

Group by department and filter groups with HAVING COUNT(*) > 5. WHERE cannot be used because the count exists only after grouping.

Explain it simply

Count heads in each department, then keep only the departments whose count passes the bar. Counting must happen first, so the filter on the count goes in HAVING.

Line by line

Table employees(id, name, dept_id).

sql
SELECT dept_id, COUNT(*) AS headcount
FROM employees
GROUP BY dept_id
HAVING COUNT(*) > 5;
  • GROUP BY dept_id forms one group per department.
  • COUNT(*) counts the rows in each group.
  • HAVING COUNT(*) > 5 removes groups of 5 or fewer.

To show the department name, join to departments and group by the name as well:

sql
SELECT d.name, COUNT(*) AS headcount
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.id, d.name
HAVING COUNT(*) > 5;

An employee with a NULL dept_id would form a NULL group in the first query.

Complexity

Time: O(n) with hash aggregation, or O(n log n) if the database sorts to group. Space: O(g) for g groups.

What to say in the interview

"I group by department and use HAVING for the condition on the aggregate. WHERE filters rows before grouping, HAVING filters groups after."

#sql#group-by#having#coding

Related questions

Practise more SQL & DBMS questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open SQL & DBMS quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.