Kubernate

Database # Second Highest Salary from Table

There are several ways to get the second highest salary from an EMPLOYEE table depending on which SQL dialect you’re using. Let me show you the most common approaches:


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

SELECT salary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1;
  • ORDER BY salary DESC → sorts salaries from highest to lowest
  • LIMIT 1 OFFSET 1 → skips the first row (highest salary) and returns the next one

2. Using TOP with NOT IN (SQL Server)

SELECT TOP 1 salary
FROM employee
WHERE salary NOT IN (SELECT MAX(salary) FROM employee)
ORDER BY salary DESC;
  • Excludes the maximum salary, then picks the next highest

3. Using MAX with WHERE (Works in most SQL engines)

SELECT MAX(salary) AS second_highest_salary
FROM employee
WHERE salary < (SELECT MAX(salary) FROM employee);
  • Finds the maximum salary that is less than the overall maximum

4. Using DENSE_RANK() (ANSI SQL, Oracle, SQL Server, PostgreSQL)

SELECT salary
FROM (
    SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
    FROM employee
) ranked
WHERE rnk = 2;
  • DENSE_RANK() assigns ranks without skipping for ties
  • Returns all employees who share the second highest salary


No comments:

Post a Comment

Spring Boot - Bean LifeCycle

 Here is a clear, step-by-step lifecycle of a Spring Boot application , explained in a simple + interview-ready way. 🔄 Spring Boot Applica...

Kubernate