Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Top N Per Group with Window

MediumSQL · PostgreSQL00:00
Practice interviewer
In session
5 left
00:00

Your question is Top N Per Group with Window. Start with the requirements and the two tables on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Write a SQL query using a window function to find the top three highest-paid employees in each department.

Use the employees and departments tables. Exclude employees without a department or salary, and break salary ties by the lower employee_id.

Output

  1. One row per selected employee, with department_id, department_name, employee_id, employee_name, salary, and salary_rank.
  2. Include up to three employees per department, ordered by department_id, then salary_rank.

Schema

departments
ColumnTypeDescription
department_idPKINTUnique department identifier
department_nameVARCHAR(100)Department name
employees
ColumnTypeDescription
employee_idPKINTUnique employee identifier
employee_nameVARCHAR(100)Employee full name
department_idINTEmployee department identifier
salaryNUMERIC(12,2)Annual employee salary
Tablesemployeesdepartments
Your solutionPostgreSQL
You need to log in / sign up to run or submit.
Run a query to see results