RUN

Second highest salary in SQL

A classic interview question, solved two ways. Press Run to try it, then change the code and run it again.

main.sql

CREATE TABLE employees (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  department TEXT,
  salary INTEGER
);

INSERT INTO employees (name, department, salary) VALUES
  ('Asha', 'Engineering', 95000),
  ('Rohan', 'Engineering', 82000),
  ('Mei', 'Design', 70000),
  ('Karan', 'Sales', 64000),
  ('Priya', 'Design', 76000);

-- With a subquery
SELECT MAX(salary) AS second_highest
FROM employees
WHERE salary < (SELECT MAX(salary) FROM employees);

-- With a window function
SELECT name, salary
FROM (
  SELECT name, salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
  FROM employees
)
WHERE rnk = 2;
Output

Press Run to see the output.

More SQL examples

Open the full SQL online compiler →