MySQL + SQL · Lesson 1

Nth Highest Salary

The Problem

A very common interview question: find the 2nd, 3rd or Nth highest salary from an employees table.

Using LIMIT and OFFSET

-- 2nd highest salary (N=2, so OFFSET 1)
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
salary ------ 50000

Using a Subquery

-- highest salary less than the maximum = 2nd highest
SELECT MAX(salary)
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

Summary

  • For the Nth highest: ORDER BY salary DESC LIMIT 1 OFFSET (N-1).
  • Use DISTINCT to skip duplicate salaries.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n