MySQL LAG Function: Usage & Syntax
The LAG function is a window function in MySQL that is used to retrieve data from a specified number of rows before the current row.
The syntax of the LAG function is as follows: LAG(expression, offset, default) OVER (PARTITION BY partition_expression ORDER BY sort_expression)
Description of Parameters:
- the column or expression that needs to be obtained.
- Number of rows to retrieve, which can be a positive, negative, or zero value. Positive numbers indicate fetching rows before the current row, negative numbers indicate fetching rows after the current row, and zero indicates fetching the current row.
- optional parameter that specifies the default value to return when the requested row does not exist.
The LAG function can be used to achieve various functions, such as:
- Retrieve the data from the previous line.
- Calculate the difference between the current row and the previous row.
- Get data from the previous few rows before the current row.
- Calculate the aggregate value of the current row and the data from the previous few rows.
Here is an example using the LAG function:
SELECT
id,
value,
LAG(value, 1, 0) OVER (ORDER BY id) AS lag_value
FROM
table_name;
In this example, the LAG function is used to retrieve data from the previous row and return the result in a new column called “lag_value”.