Skip to the page

DBMS · Build it

Department-wise count and the second highest salary

The interviewer asks

We have an employee table with id, name, salary and dept_id, and a department table with dept_id and dept_name. Write a query that shows each department's name and how many employees it has, biggest first.

Then

Follow-ups the interviewer asks next

  1. Show only departments with more than 5 employees. Why can't that condition go in WHERE?
  2. A new department has no employees and doesn't appear. Why, and how do you fix it?
  3. Now find the second highest salary in the whole company.
  4. What if two people share the highest salary?
  5. What does your query return if everyone earns the same?
  6. Find the second highest salary in each department.

The answer

What a strong answer covers

  • SELECT d.dept_name, COUNT(e.id) AS employees FROM department d LEFT JOIN employee e ON e.dept_id = d.dept_id GROUP BY d.dept_id, d.dept_name ORDER BY employees DESC;
  • COUNT(e.id), not COUNT(): with a left join, an empty department has one row of NULLs, which COUNT() would count as 1.
  • HAVING COUNT(e.id) > 5: WHERE filters rows before grouping; HAVING filters groups after it.
  • An inner join drops departments with no employees; a left join from department keeps them.
  • Second highest: SELECT MAX(salary) FROM employee WHERE salary < (SELECT MAX(salary) FROM employee); It handles ties at the top and returns NULL when there's no second salary.
  • Or SELECT DISTINCT salary FROM employee ORDER BY salary DESC LIMIT 1 OFFSET 1; (MySQL, PostgreSQL). DISTINCT is needed for ties; it returns no row, not NULL, when there's no second salary.
  • Per department: DENSE_RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) in a subquery or CTE, then keep rank 2.

The red pen

Common traps

Avoid:COUNT(*) with a left join; LIMIT 1 OFFSET 1 without DISTINCT; an aggregate inside WHERE; grouping by name only when two departments could share a name.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise 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.

Start your free interview