Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Nth Highest Salary in SQL

Nth Highest Salary in SQL

How to Find the Nth Highest Salary in SQL

Finding the Nth highest salary means retrieving the salary that ranks Nth when salaries are sorted from highest to lowest.


Common Methods to Get Nth Highest Salary


1. Using ORDER BY with LIMIT / OFFSET (MySQL, PostgreSQL)

Example: Get the 3rd highest salary

SELECT DISTINCT salaryFROM employeesORDER BY salary DESCLIMIT 1 OFFSET 2;
  • OFFSET 2 skips the first two highest salaries, then LIMIT 1 fetches the next one (3rd highest).

  • Use DISTINCT to avoid duplicates messing the count.


2. Using Subquery with TOP (SQL Server)

SELECT DISTINCT TOP 1 salaryFROM employeesWHERE salary < (    SELECT DISTINCT TOP 2 salary    FROM employees    ORDER BY salary DESC)ORDER BY salary DESC;

Explanation:

  • Inner query selects top 2 salaries,

  • Outer query selects the highest salary less than those (which is the 3rd highest).


3. Using ROW_NUMBER() or DENSE_RANK() Window Functions (Modern SQL)

Example for 3rd highest salary:

SELECT salaryFROM (    SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank    FROM employees) ranked_salariesWHERE rank = 3;
  • DENSE_RANK() ranks salaries without skipping ranks for duplicates.

  • You can use ROW_NUMBER() if you want distinct rows ignoring duplicates.


4. Using Correlated Subquery (Works in many databases)

SELECT DISTINCT salaryFROM employees e1WHERE 3 = (    SELECT COUNT(DISTINCT salary)    FROM employees e2    WHERE e2.salary >= e1.salary);

Explanation:

  • For each salary, count how many salaries are greater or equal; when count = 3, it's the 3rd highest.


Summary:

MethodBest ForNotes
LIMIT with OFFSETMySQL, PostgreSQLSimple, but doesn't work in SQL Server
TOP with subquerySQL ServerUseful in older SQL Server versions
Window functions (DENSE_RANK)Most modern DBsClean, handles duplicates well
Correlated subqueryGeneral compatibilityLess efficient for large datasets

If you want, I can help write a query for your specific SQL database!

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql