SQL QuestSQL Interview Questions › Window Functions

Second Highest Salary per Department

HardProQuerying BasicsWindow FunctionsSubqueries & CTEs

Find the employee with the second highest salary in each department. Use DENSE_RANK so tied salaries share the same rank. Show name, department, salary, and salary_rank. If a department has only 1 employee, exclude it. Sort by department. This exact question appears on LeetCode's top-50 SQL list and is asked at Amazon, Meta, and Google.

Solve it in the browser editor →

Runs on SQLite in your browser, graded against the expected result, no signup. A wrong answer gets a diagnosis, not just "incorrect".

Schema

employees

emp_idnamedepartmentpositionsalaryhire_datemanager_idperformance_rating
1Alice JohnsonEngineeringSenior Developer950002019-03-1554.5
2Bob SmithEngineeringDeveloper750002020-06-0113.8
3Carol WilliamsMarketingMarketing Manager850002018-09-20NULL4.2

Expected output: name of 95K employee, salary_rank: 2

Hint

This is a Pro challenge — the hint, the step-by-step tutor and the reference solution open in the app.

Concepts

SELECT Window Functions DENSE_RANK PARTITION BY CTE Window Functions + CTE

Practise the topic: SQL practice questions · Window function practice · CTE practice · Ranking function practice · Advanced SQL interview questions

In these company practice sets

Amazon · Google · Meta · NVIDIA · Snowflake · Goldman Sachs · Bloomberg

A SQL Quest challenge matched to patterns reported for these companies — not a question any of them has published.

Related questions

Cumulative Distinct Customers Over TimeHard · FreeSalary Rank Within DepartmentHard · FreeRunning Total RevenueHard · FreeYear-over-Year GrowthHard · Free7-Day Rolling Revenue AverageHard · FreeMulti-CTE Revenue PipelineHard · Free

Where would this cost you points in an interview?

Ten questions, no signup: a Skillmap across nine SQL skills and the one to fix first.

Take the readiness test