The LAG() Function

The LAG() function in SQL is used to access data from a previous row in the same result set without the need for a self-join. This function is often used in time series analysis or to calculate differences between consecutive rows.

LAG(column_name, offset, default_value) OVER (PARTITION BY partition_column ORDER BY order_column)

Parameters:

We can use the LAG() function to calculate the difference in sales amount from the previous day:

SELECT
    sale_id,
    sale_date,
    sale_amount,
    sale_amount - LAG(sale_amount, 1, 0) OVER (ORDER BY sale_date) AS difference_from_previous_day
FROM
    sales;

Powered by Forestry.md