Second Highest Salary

SQL coding challenge · Difficulty: easy · Topic: Subqueries · +50 XP

Problem

Find the second highest distinct salary.

If there is no second highest salary, return NULL.

Tables

Table: salaries

| Column | Type |
| --- | --- |
| id | INT |
| employee | VARCHAR |
| salary | INT |

Example Input

| id | employee | salary |
| --- | --- | --- |
| 1 | Alice | 95000 |
| 2 | Bob | 80000 |
| 3 | Carol | 80000 |
| 4 | Dave | 65000 |
| 5 | Eve | 50000 |

Expected Output

| second_highest_salary |
| --- |
| 80000 |

Explanation

The distinct salaries are 95000, 80000, 65000 and 50000.

Bob and Carol both earn 80000, but a duplicate does not create a separate rank — the second highest distinct salary is 80000.

Notes

What this SQL challenge teaches you

“Second Highest Salary” is a easy-level SQL challenge focused on Subqueries. Working through it gives you hands-on practice with subquery, LIMIT, OFFSET — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.

Concepts covered

How to approach it

If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:

  1. Your result should return: NULL.
  2. Compare your output to the Expected Output — the columns, values and row order must match exactly.
  3. SELECT MAX(salary) AS second_highest_salary FROM salaries WHERE salary < (SELECT MAX(salary) FROM salaries) ## Example input ```sql CREATE TABLE IF NOT EXISTS salaries ( id INTEGER PRIMARY KEY, employee VARCHAR(100), salary INTEGER ); INSERT INTO salaries VALUES (1,'Alice',95000), (2,'Bob', 80000), (3,'Carol',80000), (4,'Dave', 65000), (5,'Eve', 50000) ``` ## Expected output ``` 80000 ```

Where this comes up

Variations of this problem have been reported in interviews at Google, Amazon, TCS. Interviewers use it to check whether you can express the logic cleanly and reason about correctness on edge cases such as ties, nulls and empty groups.

How to practise it on PySpark.in

Open the challenge, write your SQL query in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.

Related SQL challenges

Frequently asked questions

Do I need to install Spark or a database to solve this?

No. The SQL environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.

Is this challenge free?

Yes - the problem, the sample dataset, the hints and unlimited test runs are free.

What level is it?

It is rated easy and covers Subqueries.

Solve this challenge free on PySpark.in