sqlcmd.net validated sql reference
advanced windowing MySQL MariaDB SQL Server PostgreSQL SQLite

Access The First Row In A Window With FIRST_VALUE

Return a value from the first row of a window partition, useful for comparing each row against the group leader.

Docker-validated Not currently validation-green

Show each employee's salary alongside the top earner in their department

FIRST_VALUE(name) OVER (PARTITION BY dept ORDER BY salary DESC) evaluates separately for each department. Within Eng, the window is ordered from highest salary to lowest, so FIRST_VALUE returns Dave (salary 100000) for every row in that partition. Within Sales, Carol (90000) is first so all three Sales rows show Carol as top earner. To find the lowest earner instead, use LAST_VALUE(name) OVER (PARTITION BY dept ORDER BY salary DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) — the explicit frame clause is required to make LAST_VALUE reach the true end of the partition.

Rows loaded before the example query runs.
Setup
CREATE TABLE employees (
  id INT,
  dept VARCHAR(20),
  name VARCHAR(50),
  salary INT
);

INSERT INTO
  employees (id, dept, name, salary)
VALUES
  (1, 'Sales', 'Alice', 80000),
  (2, 'Sales', 'Bob', 60000),
  (3, 'Sales', 'Carol', 90000),
  (4, 'Eng', 'Dave', 100000),
  (5, 'Eng', 'Eve', 95000);
Shared across supported engines.
SQL
SELECT
  dept,
  name,
  salary,
  FIRST_VALUE (name) OVER (
    PARTITION BY
      dept
    ORDER BY
      salary DESC
  ) AS top_earner
FROM
  employees
ORDER BY
  dept,
  salary DESC;
Returned rows for the shared example.
deptnamesalarytop_earner
EngDave100000Dave
EngEve95000Dave
SalesCarol90000Carol
SalesAlice80000Carol
SalesBob60000Carol

The syntax is identical across all supported engines.

Where this command helps.

  • comparing each employee's salary to the top earner in their department
  • flagging rows that are not the group leader

What the command is doing.

FIRST_VALUE(column) OVER (PARTITION BY ... ORDER BY ...) returns the value from the first row within each window partition according to the specified ordering. It is commonly used to compare every row against the top-ranked member of its group — for example, each employee's salary versus the highest salary in their department. LAST_VALUE works symmetrically but requires an explicit ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING frame clause; without it the default frame stops at the current row, making LAST_VALUE return the current row's own value rather than the true last row. Both functions require MySQL 8.0+ and MariaDB 10.2+.