FIRST_VALUE (Transact-SQL)
Returns the first value in an ordered set of values that is specified by an argument list.
Syntax
FIRST_VALUE ( [ scalar_expression ] )
OVER ( [ <partition_by_clause> ] <order_by_clause> [ ,...n ] )
Parameters
- scalar_expression
-
The expression to which the
FIRST_VALUEis applied. It can be a column name, a constant, or any other scalar expression.
Returns
The data type of scalar_expression.
Remarks
-
FIRST_VALUEis a deterministic function. - If two or more rows share the same value for the expression that determines the first row, then all these rows will be returned as the first value.
-
FIRST_VALUEcan only be used with theOVERclause. -
In a
OVERclause,ORDER BYis required to determine the order of rows. IfORDER BYis not specified, the result is nondeterministic.
Examples
Example 1: Get the first product sold in each category
This example demonstrates how to find the name of the first product sold within each product category.
WITH SalesWithRank AS (
SELECT
ProductName,
Category,
SalesDate,
ROW_NUMBER() OVER(PARTITION BY Category ORDER BY SalesDate ASC) as rn
FROM Products
)
SELECT
ProductName,
Category,
SalesDate,
FIRST_VALUE(ProductName) OVER(PARTITION BY Category ORDER BY SalesDate ASC) as FirstProductSoldInCategory
FROM SalesWithRank
WHERE rn = 1;
Result:
| ProductName | Category | SalesDate | FirstProductSoldInCategory |
|---|---|---|---|
| Gadget Pro | Electronics | 2023-01-15 | Gadget Pro |
| Cozy Sweater | Clothing | 2023-02-10 | Cozy Sweater |
Example 2: Get the highest salary in each department
This example shows how to retrieve the highest salary from each department using FIRST_VALUE in conjunction with ORDER BY and DESC.
SELECT
Department,
Salary,
EmployeeName,
FIRST_VALUE(Salary) OVER(PARTITION BY Department ORDER BY Salary DESC) as HighestSalaryInDepartment
FROM Employees;
Result:
| Department | Salary | EmployeeName | HighestSalaryInDepartment |
|---|---|---|---|
| Engineering | 120000 | Alice Smith | 120000 |
| Engineering | 110000 | Bob Johnson | 120000 |
| Marketing | 95000 | Charlie Brown | 95000 |