Syntax of the FIRST_VALUE function in SQL

In SQL, the FIRST_VALUE function is used to retrieve the first value of an expression within a group. It is commonly used with the WINDOW clause to define the group of rows to consider.

The syntax of the FIRST_VALUE function can be expressed as follows:

FIRST_VALUE ( expression ) OVER (
    [PARTITION BY partition_expression]
    [ORDER BY order_expression [ASC | DESC]]
    [ROWS {UNBOUNDED PRECEDING | integer PRECEDING | CURRENT ROW | integer FOLLOWING | UNBOUNDED FOLLOWING}]
)

Let’s break down the elements of the syntax:

Here is an example usage of the FIRST_VALUE function:

SELECT
    employee_name,
    department,
    salary,
    FIRST_VALUE(salary) OVER (PARTITION BY department ORDER BY salary DESC) AS highest_salary
FROM
    employees

In this example, the FIRST_VALUE function is used to retrieve the highest salary within each department. The PARTITION BY clause divides the rows by department, and the ORDER BY clause sorts the salaries in descending order. The result will include the employee name, department, salary, and the highest salary within each department.

For further details and examples, refer to the documentation of your specific SQL database system or consult relevant SQL books and resources.

References: