SQL FIRST_VALUE function
Returns an expression from the first row of the window frame, so every row can be compared with a baseline, such as each price next to the opening price.
- Categoria
- Janela
- Returns
type of the expression- In this category
- 7 of 79
Sintaxe
FIRST_VALUE(expression) OVER (PARTITION BY g ORDER BY x)
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | Supported under this name. |
| PostgreSQL | Sim | Supported under this name. |
| MySQL | Sim | MySQL 8.0+ |
| SQLite | Sim | SQLite 3.25+ |
| Oracle | Sim | Supported under this name. |
Exemplos
Any engine
SELECT day, price,
FIRST_VALUE(price) OVER (ORDER BY day) AS open_price
FROM prices;
Any engine
SELECT region, city, sales,
sales - FIRST_VALUE(sales) OVER (PARTITION BY region ORDER BY sales DESC) AS vs_leader
FROM regional_sales;
Bom saber
- The default frame is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, which is fine for FIRST_VALUE with a plain ORDER BY, but be explicit when the frame is custom.
- FIRST_VALUE is window-only: to return only the first row per group, use ROW_NUMBER() = 1 instead.
- If the first row's value is NULL, FIRST_VALUE returns NULL. NULLS LAST in the ORDER BY (PostgreSQL, Oracle, SQLite 3.30+) or a CASE sort key on SQL Server and MySQL moves those rows out of first place; Oracle and SQL Server 2022+ also accept FIRST_VALUE(x) IGNORE NULLS.
Questions about FIRST_VALUE
How is FIRST_VALUE different from MIN?
MIN returns the smallest value; FIRST_VALUE returns the value from the first row of the frame. FIRST_VALUE(price) OVER (ORDER BY day) is the earliest price, which is only the minimum if prices never fell. FIRST_VALUE can return one column from the row chosen by another.
How do I get the first row per group, not just its value?
ROW_NUMBER() OVER (PARTITION BY g ORDER BY x) = 1 in a CTE. FIRST_VALUE attaches values to all rows; it does not reduce them.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- First and last value in a partition Snippet
- Lag compare within a group Snippet
- SQL window function interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.