SQLite FIRST_VALUE function

SQLite’s FIRST_VALUE() function is a window function that returns the first value of an expression within a window. This function is useful in situations where you want to get the first value of a column for each group within a larger dataset.

Syntax

The syntax for using the FIRST_VALUE() function in SQLite is as follows:

FIRST_VALUE(expression) OVER (
    [PARTITION BY partition_expression, ... ]
    [ORDER BY sort_expression [ASC|DESC], ... ]
    [frame_clause]
)

Here, expression refers to the column or expression that you want to return the first value of. The PARTITION BY clause is optional, and is used to divide the dataset into partitions based on one or more columns. The ORDER BY clause is also optional, and is used to specify the order in which the rows are processed within each partition. Finally, the frame_clause is also optional, and is used to specify the range of rows to include in the calculation.

Example

For example, suppose you have a table called sales with columns product, region, and sales_amount. You want to find the first sales amount for each product in each region. You can use the following query:

SELECT 
product, region, 
FIRST_VALUE(sales_amount) OVER 
( PARTITION BY product, region ORDER BY date ) AS first_sales_amount
FROM sales;

This will return a result set with columns product, region, and first_sales_amount. The first_sales_amount column will contain the first sales amount for each product in each region, based on the date column.

In summary, the SQLite FIRST_VALUE() function is a useful window function that can be used to obtain the first value of an expression within a window. It can be used to group data into partitions, specify the order of processing, and include a specific range of rows.