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');The query as written:
sql
SELECT id, name, salary FROM employees
WHERE salary < 95000
ORDER BY salary DESC, id LIMIT 2;| id | name | salary |
|---|---|---|
| 4 | Tom | 70000 |
| 5 | Sara | 62000 |
Page 1 (ORDER BY salary DESC, id LIMIT 2) returned Asha and Ravi, so the last row seen was (95000, 2). Mei also earns 95000 with id 3, and the strict salary < 95000 condition jumps straight to Tom and Sara. Mei never appears on any page.
A corrected version:
sql
SELECT id, name, salary FROM employees
WHERE salary < 95000 OR (salary = 95000 AND id > 2)
ORDER BY salary DESC, id LIMIT 2;| id | name | salary |
|---|---|---|
| 3 | Mei | 95000 |
| 4 | Tom | 70000 |
Including the tiebreaker in the condition resumes exactly after the last row, so Mei comes first, then Tom. An index on (salary DESC, id) supports the query. Row-value syntax cannot express mixed directions here, because salary is descending and id is ascending, so the expanded OR form is needed.
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 id, name, salary FROM employees
WHERE salary < 95000
ORDER BY salary DESC, id LIMIT 2;
SELECT id, name, salary FROM employees
WHERE salary < 95000 OR (salary = 95000 AND id > 2)
ORDER BY salary DESC, id LIMIT 2;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Keyset cursors need a unique tiebreaker
- The WHERE must match the ORDER BY columns and directions
- Strict comparison on a non-unique column skips ties
Common mistakes
- Using only the sort column as the cursor
- Row values with mixed sort directions
Follow-ups
- How would you page backwards?
- Which index serves this query?
Tips
- Trace the last row of page 1