Essential cookies keep authentication working. With your permission, we also use analytics cookies to understand and improve the product. Read our Privacy Policy

DataEngPrep.tech
QuestionsPracticeAI CoachDashboardPricingBlog
ProLogin
Home/Questions/SQL/Write an SQL query to find the second-highest salary from an employee table.

Write an SQL query to find the second-highest salary from an employee table.

SQLmedium0.8 min readFeatured

Reviewed by Aditya Kumar · Last reviewed 2026-03-24

**Using subquery with MAX**: ```sql SELECT MAX(salary) AS second_highest FROM employee WHERE salary < (SELECT MAX(salary) FROM employee); ``` **Using LIMIT/OFFSET** (MySQL, PostgreSQL): ```sql SELECT DISTINCT salary FROM employee ORDER BY salary DESC LIMIT 1 OFFSET 1; ```...

🤖 Analyze Your Answer
Frequency
Low
Asked at 6 companies
Category
487
questions in SQL
Difficulty Split
130E|271M|86H
in this category
Total Bank
1,863
across 7 categories
Asked at these companies
AccentureBCGCognizantIncedoYash Technologies
Interview Pro Tip

Pro-Move: Clarify 'second-highest' with ties (DENSE_RANK vs RANK). Red Flag: Using OFFSET 1 without DISTINCT when duplicates exist—wrong result.

Key Concepts Tested
partitionsqlwindow

Why This Question Matters

This medium-level SQL question appears frequently in data engineering interviews at companies like Accenture, BCG, Cognizant, and 3 others. While less common, it tests deeper understanding that distinguishes strong candidates. Mastering the underlying concepts (partition, sql, window) will help you answer variations of this question confidently.

How to Approach This

Break this problem into components. Identify the core trade-offs involved, then walk the interviewer through your reasoning step by step. Demonstrate awareness of edge cases and production considerations - this is what separates good answers from great ones. The expert answer includes a code example that demonstrates the implementation pattern.

Expert Answer
167 wordsIncludes code

Using subquery with MAX:

SELECT MAX(salary) AS second_highest
FROM employee
WHERE salary < (SELECT MAX(salary) FROM employee);

Using LIMIT/OFFSET (MySQL, PostgreSQL):

SELECT DISTINCT salary
FROM employee
ORDER BY salary DESC
LIMIT 1 OFFSET 1;

Using DENSE_RANK (ANSI SQL, most robust):

SELECT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rk
FROM employee
) t
WHERE rk = 2;

Architectural Logic & Trade-offs:

  • Subquery: Two table scans; O(n) each. Simple but doesn't handle ties (two top salaries → result is third-highest).

  • LIMIT/OFFSET: Single scan + sort; OFFSET can be expensive on very large tables (must skip rows).

  • DENSE_RANK: Window function—single pass, defines ranking semantics. Handles ties correctly; use when "second-highest" must account for duplicate top salaries.
  • Scalability: For tables >10M rows, ensure salary is indexed if using subquery; DENSE_RANK may require full sort—consider partition pruning if filtered by dept/region.

    Edge Cases: Empty table, single row, all identical salaries—DENSE_RANK returns NULL for rk=2 when none exists.

    ⚡
    Pro Tip

    Pro-Move: Clarify 'second-highest' with ties (DENSE_RANK vs RANK). Red Flag: Using OFFSET 1 without DISTINCT when duplicates exist—wrong result.

    Want all answers as a PDF for offline study?
    Seven focused volumes with 750+ in-depth answers — Answer Vault →
    Related Study Guides
    📘

    Incedo Data Engineer Interview Questions & Answers (2026)

    Practice the 44 most asked data engineering questions at Incedo. Covers Spark/Big Data, SQL, Behavioral and more.

    8 min read →
    📘

    BCG Data Engineer Interview Questions & Answers (2026)

    Practice the 36 most asked data engineering questions at BCG. Covers Spark/Big Data, SQL, Cloud/Tools and more.

    8 min read →
    📘

    Accenture Data Engineer Interview Questions & Answers (2026)

    Practice the 33 most asked data engineering questions at Accenture. Covers SQL, Spark/Big Data, Behavioral and more.

    8 min read →
    📘

    SQL Optimization Interview Questions Explained

    Master 487 sql questions with expert answers. Real questions from 97+ companies.

    60 min read →
    🪟

    SQL Window Functions & CTEs: The Complete Interview Guide for Data Engineers (2026)

    Window functions and CTEs are the #1 tested SQL topics at Amazon, Google, and Databricks. This guide covers every pattern you'll face with production-ready answers.

    18 min read →
    🔗

    SQL Joins for Data Engineer Interviews: Every Type Explained with Real Examples (2026)

    SQL joins are the most tested topic in data engineering interviews. Most candidates know INNER and LEFT JOIN but stumble on CROSS APPLY, anti-joins, and self-joins. This guide covers them all with real interview patterns.

    13 min read →

    Related SQL Questions

    mediumDemonstrate the difference between DENSE_RANK() and RANK()FreemediumDiscuss differences between ROW_NUMBER(), RANK(), and DENSE_RANK(), and provide examples from your projects.FreemediumExplain the differences between Data Warehouse, Data Lake, and Delta LakeFreemediumExplain the differences between Repartition and Coalesce. When would you use each?FreeeasyExplain the differences between a Data Lake and a Data Warehouse.Free
    Weak vs Strong Answer Breakdown

    Compare your response with a stronger, structured example and identify missing concepts.

    Read Answer Analysis

    Level up your prep

    Recommended
    Educative
    Educative Unlimited

    800+ hands-on courses — Grokking System Design, Coding Patterns, and AI mock interviews for your DE loop.

    Start learning →

    Some links below are affiliate links. If you buy through them we may earn a small commission at no extra cost to you — it helps keep DataEngPrep free.

    According to DataEngPrep.tech, this is one of the most frequently asked SQL interview questions, reported at 6 companies. DataEngPrep.tech maintains an editor-reviewed database of 1,863 data engineering interview questions across 7 categories.

    ← Back to all questionsMore SQL questions →
    Categories
    All QuestionsSQLSpark / Big DataPython / CodingSystem DesignCloud / ToolsBehavioral
    By Company
    AmazonGoogleDatabricksSnowflakeAWSAzureMicrosoftNetflixUberTCS
    Interview Guides
    All GuidesTop SQL QuestionsTop Spark QuestionsPySpark QuestionsTop Python QuestionsTop System DesignKafka QuestionsAirflow QuestionsSQL Window FunctionsETL QuestionsData Modeling
    Products
    AI Interview CoachAnswer AnalyzerSQL PlaygroundResume AnalyzerAnswer Vault PDFsPricing
    Company
    About & Editorial PolicyContact UsAI DisclosureDisclaimerTerms of ServicePrivacy Policy
    © 2026 DataEngPrep.tech. All rights reserved.
    AboutBlogContactDisclaimer