Full answer
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');sql
SELECT name, salary FROM employees WHERE salary < 120000 ORDER BY salary DESC, id LIMIT 1;| name | salary |
|---|---|
| Ravi | 95000 |
With id as the tie-breaker, Ravi (id 2) comes before Mei (id 3), every time. Without it, the engine may return either, and the choice can change with a new index or a different plan.
If the question is "who earns the most", including all tied people with WHERE salary = (SELECT MAX(salary) ...) or RANK() = 1 is usually the better answer than picking one.
sql
CREATE TABLE departments (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
dept_id INTEGER REFERENCES departments(id),
manager_id INTEGER REFERENCES employees(id),
salary INTEGER,
hire_date TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
(1,'Asha', 1,NULL,120000,'2019-03-01'),
(2,'Ravi', 1,1, 95000,'2020-07-15'),
(3,'Mei', 1,1, 95000,'2021-01-10'),
(4,'Tom', 2,1, 70000,'2022-05-20'),
(5,'Sara', 2,4, 62000,'2023-02-01'),
(6,'Diego',3,1, 55000,'2021-11-30'),
(7,'Lena', NULL,4, NULL, '2024-06-03'),
(8,'Omar', 3,6, 48000,'2024-09-09');
SELECT name, salary FROM employees WHERE salary < 120000 ORDER BY salary DESC, id LIMIT 1;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- LIMIT with ties returns an arbitrary tied row
- Add a unique tie-breaker to ORDER BY
- Plans can change which tied row comes first
- Use RANK or a MAX subquery to return all tied rows
Common mistakes
- Relying on the current plan to pick the same tied row
- Answering 'top earner' with LIMIT 1 when ties are possible
Follow-ups
- What does FETCH FIRST 1 ROW WITH TIES do in PostgreSQL?
- How would you return all top earners?
Tips
- Always mention the tie-breaker