176. Second Highest Salary - Detailed Explanation

Problem Statement

You are given an Employee table with the following schema:

  • Id (integer): The unique employee ID.
  • Salary (integer): The salary of the employee.

Write a SQL query to get the second highest salary from the Employee table. If there is no second highest salary (for example, when there is only one distinct salary in the table), the query should return null.

Example Inputs & Outputs

  • Example 1:

    • Employee Table:
      +----+--------+
      | Id | Salary |
      +----+--------+
      | 1  | 300    |
      | 2  | 200    |
      | 3  | 100    |
      +----+--------+
      
    • Output: 200
    • Explanation:
      The highest salary is 300, and the second highest distinct salary is 200.
  • Example 2:

    • Employee Table:
      +----+--------+
      | Id | Salary |
      +----+--------+
      | 1  | 100    |
      +----+--------+
      
    • Output: null
    • Explanation:
      There is only one salary value in the table; hence, there is no second highest salary.
  • Example 3:

    • Employee Table:
      +----+--------+
      | Id | Salary |
      +----+--------+
      | 1  | 400    |
      | 2  | 400    |
      | 3  | 300    |
      +----+--------+
      
    • Output: 300
    • Explanation:
      Although there are multiple rows with the highest salary (400), the next distinct salary is 300, which is the second highest.

Constraints

  • The Employee table can have one or more rows.
  • Salaries are positive integers.
  • There might be duplicate salary values.

Hints

  1. Using Subqueries:
    Think about first finding the highest salary, then using it to filter out those records when searching for the next highest.

  2. Handling Duplicates:
    Since the table can contain duplicate salaries, ensure that you consider only distinct salary values when determining the second highest.

Approaches

Approach 1: Using a Subquery

Idea:

  • First, determine the highest salary using a subquery.
  • Then, select the maximum salary that is less than this highest salary.

SQL Query:

SELECT (SELECT MAX(Salary) FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee) ) AS SecondHighestSalary;

Explanation:

  • The inner subquery (SELECT MAX(Salary) FROM Employee) finds the highest salary.
  • The outer query then finds the maximum salary that is less than that value.
  • If there is no such salary (i.e., if the table contains only one distinct salary), the result will be null.

Approach 2: Using LIMIT/OFFSET (MySQL Specific)

Idea:

  • Use DISTINCT to filter duplicate salary values.
  • Order the distinct salaries in descending order.
  • Use LIMIT with an offset to get the second element.

SQL Query:

SELECT (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1 ) AS SecondHighestSalary;

Explanation:

  • SELECT DISTINCT Salary FROM Employee gets unique salary values.
  • ORDER BY Salary DESC sorts them in descending order.
  • LIMIT 1 OFFSET 1 skips the highest salary and returns the next one.
  • This query returns null if there is no second highest salary.

Simulated Implementations

Since the original problem is SQL-based, here are simulated implementations in Python and Java that mimic the logic of retrieving the second highest salary from an in-memory dataset.

Python Code

Python3
Python3

. . . .

Java Code

Java
Java

. . . .

Complexity Analysis

  • Time Complexity:

    • SQL Approach:
      The subquery approach runs in a constant number of passes over the table (the performance is ultimately determined by the SQL engine's execution plan).

    • Python/Java Simulation:
      Extracting unique salaries from n employees takes O(n), and sorting the unique salaries takes O(k log k), where k is the number of distinct salaries. In the worst-case scenario, k is O(n).

  • Space Complexity:

    • SQL Approach:
      The space usage depends on the SQL engine and is generally managed internally.
    • Python/Java Simulation:
      Storing unique salaries takes O(k) extra space.

Common Mistakes

  1. Not Handling Duplicate Salaries:
    Failing to use distinct values may lead to incorrectly counting duplicates as separate salaries.

  2. Edge Case with One Employee:
    Forgetting to return null when there is only one distinct salary in the table.

  3. Overcomplicating the Query:
    Using unnecessary joins or multiple nested subqueries can make the solution more complex than needed.

Edge Cases & Alternative Variations

  • Edge Cases:

    • Single Record:
      When there is only one employee or all employees have the same salary.
    • All Salaries Identical:
      Even if multiple rows exist, if all salaries are the same, the answer should be null.
  • Alternative Variations:

    • Second Lowest Salary:
      Similar logic applies but instead of ordering in descending order, you would order in ascending order.
    • Nth Highest Salary:
      The problem can be generalized to find the Nth highest salary.
  • Nth Highest Salary:
    Extends the concept to finding the Nth highest distinct salary.

  • Top K Frequent Elements:
    A problem where understanding frequency and ordering can help in solving similar patterns.

  • Ranking in SQL:
    Problems that involve ranking records, such as using RANK() or DENSE_RANK() functions.

TAGS
leetcode
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
332. Reconstruct Itinerary - Detailed Explanation
Learn to solve Leetcode 332. Reconstruct Itinerary with multiple approaches.
2043. Simple Bank System - Detailed Explanation
Learn to solve Leetcode 2043. Simple Bank System with multiple approaches.
759. Employee Free Time - Detailed Explanation
Learn to solve Leetcode 759. Employee Free Time with multiple approaches.
76. Minimum Window Substring - Detailed Explanation
Learn to solve Leetcode 76. Minimum Window Substring with multiple approaches.
359. Logger Rate Limiter - Detailed Explanation
Learn to solve Leetcode 359. Logger Rate Limiter with multiple approaches.
51. N-Queens - Detailed Explanation
Learn to solve Leetcode 51. N-Queens with multiple approaches.
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.6
(3,192 learners)
Discounted price for Your Region

$123

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.