Skip to content

FIRST_VALUE

FIRST_VALUE(expression) OVER ([PARTITION BY partition_expression] [ORDER BY sort_expression [ASC|DESC]] [ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW])

Section titled “FIRST_VALUE(expression) OVER ([PARTITION BY partition_expression] [ORDER BY sort_expression [ASC|DESC]] [ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW])”
  • expression: This is the value that will be analyzed. FIRST_VALUE will return the first value in the ordered set based on this expression.
  • partition by partition_expression: This clause divides the result set into partitions to which the FIRST_VALUE function is applied. If it’s not specified, the function treats the entire result set as a single partition.
  • order by sort_expression [asc|desc]: This clause specifies the order of the data in each partition. The ASC or DESC determines the sequence. If it’s not specified, the function treats all rows of the query result set as a single group.
  • rows between unbounded preceding and current row: This clause defines the window frame in which the FIRST_VALUE function operates. In this case, it is from the first row of the partition to the current row. The setting of the window frame size can impact the result of the FIRST_VALUE function.
SELECT FIRST_VALUE(product_name) OVER (ORDER BY price DESC) AS 'Most Expensive Product'
FROM Products;
+-------------------+
| Most Expensive Product |
+-------------------+
| MacBook Pro |
+-------------------+

In this example, the FIRST_VALUE() function is used to return the first value in an ordered set based on the price of the product. Here it returns the ‘MacBook Pro’ which has the highest price in the ‘Products’ table.