Skip to content
CodeKruPro

Top two earners in each department

SQLMedium-HardAsked in: TCS

Return the dept_id, name and salary of the two highest-paid employees in each department (just one if the department has only one employee). When two salaries are equal, the employee with the smaller id ranks higher. Leave out employees with no department.

Rows can come back in any order. Column names do not matter; the values do.

Sample database: Company: departments, employees and orders

Three tables. departments (id, name, city). employees (id, name, email, dept_id, manager_id, salary, bonus, hire_date): dept_id and manager_id may be NULL, bonus may be NULL, hire_date is text in the form YYYY-MM-DD. orders (id, employee_id, customer, amount, status, order_date): employee_id is the sales rep (an employee id), amount may be NULL, status is DELIVERED, SHIPPED, PENDING or CANCELLED in capitals, and order_date is text in the form YYYY-MM-DD. Foreign keys are not enforced, so an order may point to an employee who does not exist.

departments
idnamecity
1EngineeringBengaluru
2QAPune
3SalesMumbai
4HRPune
5SupportChennai
employees
idnameemaildept_idmanager_idsalarybonushire_date
1Asha Raoasha@shop.in1NULL150000200002018-03-01
2Vikram Shahvikram@shop.in1195000NULL2020-07-15
3Neha Guptaneha@shop.in218200050002021-01-10
4Rohan Mehtarohan@shop.in2364000NULL2022-06-01
5Priya Nairpriya@shop.in236400030002023-02-20
6Arjun Dasarjun@shop.in3170000150002019-11-05
7Kavya Iyerkavya@shop.in3652000NULL2024-01-08
8Imran Khanimran@shop.in415800020002020-09-30
9Sneha Patilneha@shop.inNULL147000NULL2025-04-14
10Dev Malhotradev@shop.in129500080002022-12-01
orders
idemployee_idcustomeramountstatusorder_date
1016Acme Ltd12000DELIVERED2026-01-05
1026Bharat Traders4500CANCELLED2026-01-09
1037Acme Ltd8000DELIVERED2026-02-11
1047Cosmo Retail15000SHIPPED2026-02-20
1056Delta Foods3000PENDING2026-03-02
1067Bharat Traders9500DELIVERED2026-03-15
10712Echo Stores7000DELIVERED2026-03-18
1086Acme LtdNULLPENDING2026-04-01
1097Cosmo Retail15000SHIPPED2026-02-20
1108Fresh Mart2500DELIVERED2026-04-10
SQL (SQLite)

Run shows your rows. Submit compares them with the expected rows.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in