SQL Interview & Case Lab
Back to Interview SQL Patterns

The Nth Highest Salary Problem

The most-asked SQL interview question of all time. Five wrong answers, two right ones. FIND_VIDEO: search 'nth highest salary SQL leetcode' — recommended channel: Joma Tech / Alex Freberg. Aim for 9 min or under.

12 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Problem Overview — Introduces the problem of finding the Nth highest salary and outlines solving it via five methods.
  2. Nested MAX Approach — Demonstrates finding the 2nd and 3rd highest salaries using nested MAX subqueries.
  3. LIMIT Clause and DISTINCT — Explains LIMIT offset syntax and why DISTINCT is necessary to handle duplicate salary rows.
  4. Correlated Self-Join — Shows how to count strictly greater distinct salaries using correlated subqueries matching N-1.
  5. DENSE_RANK Window Function — Illustrates ranking salaries with DENSE_RANK() inside a derived table to retrieve rank N.
  6. NOT IN and Inequality Filter — Covers finding the second highest salary using MAX combined with NOT IN or not equal operators.
PDF notes

Frequently asked questions

Why does LIMIT 2, 1 return the wrong result without DISTINCT?

Without DISTINCT, duplicate salaries take up row offsets, causing LIMIT to fetch another instance of the 2nd highest salary instead of the true 3rd highest.

What is the difference between RANK() and DENSE_RANK() for this problem?

RANK() skips subsequent rank numbers after ties (e.g., 1, 2, 2, 4), whereas DENSE_RANK() maintains consecutive numbers (e.g., 1, 2, 2, 3).

Which approach is most preferred in production and interviews?

DENSE_RANK() is preferred because it handles duplicates cleanly, scales to any N, and complies with modern SQL standards.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.