HardSQL challenge #190SubqueryDISTINCTOFFSET

Find the Second Highest Salary

Return the employees who earn the second-highest salary, handling ties correctly.

The challenge runs on the SQLabHub practice database (SQLite) and uses the employees table. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

Why this question comes up

This is one of the most common SQL interview questions. At work it appears as "who is the runner-up?": the second-best salesperson, the second-largest order. The catch is ties: if two people share the top salary, the second-highest salary is the next distinct value.

The task

Find employees with the second highest salary. Handle ties correctly.

A correct answer returns 1 row with 5 columns: first_name, last_name, department, title, salary.

Tables used in this challenge

employees 120 rows

id INTEGER (PK) · first_name TEXT · last_name TEXT · email TEXT · department TEXT · department_id INTEGER · title TEXT · salary REAL · hire_date TEXT · manager_id INTEGER · city TEXT · status TEXT

First 3 rows of the employees table
idfirst_namelast_nameemaildepartmentdepartment_idtitlesalaryhire_datemanager_idcitystatus
1WilliamLewiswlewis18@corp.ioCustomer Success7CS Specialist617742022-07-2460San Diegoactive
2JohnMillerjmiller51@corp.ioLegal8Senior Counsel1916942021-08-0955San Diegoactive
3DanielRiveradrivera50@corp.ioEngineering1Staff Engineer1350672016-06-06106Houstonactive

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
first_namelast_namedepartmenttitlesalary
NancyThompsonCustomer SuccessCS Director203999

The complete result: 1 row. This is the output of the model solution on the practice database.

What you practise

  • Choosing exactly which columns a query returns
  • Filtering rows with a WHERE condition
  • Removing duplicate rows with DISTINCT
  • Using the result of one query inside another
  • Sorting the result with ORDER BY
  • Returning only the first rows with LIMIT

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

Use a subquery with OFFSET 1 on DISTINCT salaries

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Read from the employees table.
  2. Filter in WHERE: keep the rows where salary equals the value returned by a subquery.
  3. The subquery runs once and returns a single value. It works like this:
    1. Read from the employees table.
    2. Return only the column salary.
    3. DISTINCT removes duplicate rows, so each value appears once.
    4. Sort the result by salary descending.
    5. Skip the first row with OFFSET and return the next one.
  4. Return only the columns first_name, last_name, department, title and salary.
Show the model solution
SELECT first_name, last_name, department, title, salary
FROM employees
WHERE salary = (
  SELECT DISTINCT salary
  FROM employees
  ORDER BY salary DESC
  LIMIT 1 OFFSET 1
);

This query produced the expected output above. Yours does not have to match it word for word: any query that returns the same rows is correct.

What to watch for

The subquery takes the distinct salaries, skips the highest and returns the next. The outer query then returns everyone on that salary, so a tie for second place gives several rows. DENSE_RANK() = 2 is the window-function version of the same answer.

  • Subquery. A subquery compared with =, > or < must return exactly one row and one column. If it can return several rows, use IN or an aggregate.
  • DISTINCT. DISTINCT works on the whole selected row. Adding one more column to the SELECT list can bring the duplicates back.
  • LIMIT. LIMIT without ORDER BY returns an arbitrary set of rows. LIMIT is also dialect-specific: SQL Server uses TOP and Oracle uses FETCH FIRST.

Another way to solve it

DENSE_RANK() numbers distinct salaries without gaps, so rank 2 is always the second-highest value, whatever the ties above it. Change the 2 to any N for the Nth highest; the OFFSET version needs OFFSET N-1.

Show the alternative query
SELECT first_name, last_name, department, title, salary
FROM (
  SELECT *, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
)
WHERE rnk = 2;

Checked when this page was built: it returns the same rows as the model solution on the practice database.

Solve This SQL Challenge

Keep learning