Write a query that finds the third highest value in a column.
Two answers, depending on whether you mean the third highest distinct value or the third row.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(120) NOT NULL,
salary_cents INTEGER NOT NULL
);
INSERT INTO employees (id, name, salary_cents) VALUES
(1, 'Grace Hopper', 150000),
(2, 'Alan Turing', 150000),
(3, 'Ada Lovelace', 120000),
(4, 'Joan Clarke', 90000),
(5, 'Claude Shannon', 80000);
-- The third highest ROW.
SELECT name, salary_cents
FROM employees
ORDER BY salary_cents DESC
LIMIT 1 OFFSET 2;
-- The third highest DISTINCT value: Claude Shannon, at 80000.
SELECT name, salary_cents
FROM employees
WHERE salary_cents = (
SELECT DISTINCT salary_cents
FROM employees
ORDER BY salary_cents DESC
LIMIT 1 OFFSET 2
)
ORDER BY id;The first query returns Ada Lovelace at 120000 — the third row when sorted, counting Grace and Alan separately even though they tie. The second returns Claude Shannon at 80000, because the distinct salaries are 150000, 120000, 90000 and 80000, and the third of those is 90000... except that the OFFSET lands on the third distinct value, which is 90000, held by Joan Clarke.
Let the query settle it: the second query returns Joan Clarke at 90000. The distinct salaries in descending order are 150000, 120000, 90000 and 80000, so the third distinct value is 90000.
The general rule that follows from this is worth having ready for an interview. To find the Nth highest distinct value, wrap the DISTINCT subquery in a comparison. To find the Nth row, use LIMIT and OFFSET directly on the sorted table. To find every row holding the Nth highest distinct value, use DENSE_RANK and filter on it — that is the version that handles ties correctly and is usually what a business question wants.