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, dept_id, salary,
FIRST_VALUE(name) OVER (PARTITION BY dept_id ORDER BY salary DESC, name) AS top_earner
FROM employees WHERE dept_id IS NOT NULL
ORDER BY dept_id, salary DESC, name;| name | dept_id | salary | top_earner |
|---|---|---|---|
| Asha | 1 | 120000 | Asha |
| Mei | 1 | 95000 | Asha |
| Ravi | 1 | 95000 | Asha |
| Tom | 2 | 70000 | Tom |
| Sara | 2 | 62000 | Tom |
| Diego | 3 | 55000 | Diego |
| Omar | 3 | 48000 | Diego |
Every Engineering row shows Asha, every Sales row Tom and every Support row Diego. Unlike LAST_VALUE, FIRST_VALUE does not need a frame clause, because the default frame starts at the partition's first row.
A join to a per-department MAX would also work, but it returns two rows per employee if two people tie for the top salary. The window version with a tie-breaker always returns exactly one name.
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, dept_id, salary,
FIRST_VALUE(name) OVER (PARTITION BY dept_id ORDER BY salary DESC, name) AS top_earner
FROM employees WHERE dept_id IS NOT NULL
ORDER BY dept_id, salary DESC, name;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- FIRST_VALUE returns the first row's value in window order
- The default frame is fine for FIRST_VALUE
- Add a tie-breaker for deterministic results
- Joining to MAX can duplicate rows on ties
Common mistakes
- Using LAST_VALUE with the default frame for the same task
- Leaving ties unresolved
Follow-ups
- How would you show the lowest-paid person too?
- How would you show the gap to the top salary?
Tips
- Contrast with LAST_VALUE