LEAD and LAG Functions

Stay ahead with LEAD, remember the past with LAG!
Stay ahead with LEAD, remember the past with LAG!

LAG and LEAD are SQL analytic functions that allow you to access data from a previous or subsequent row in a query result set. LAG provides access to a previous row, while LEAD provides access to the following row.

For example, imagine you have a table of sales data with columns for date, product, and revenue. (to be used in subsequent examples)

dateproductrevenue
2022-01-01A100
2022-01-01B200
2022-01-02A150
2022-01-02B300
2022-01-03A200
2022-01-03B250
SALES DATA

Using the LAG and LEAD functions, we can retrieve the revenue from the previous or next day for each row in the table.

LAG

LAG retrieves information from the preceding row within the same query output without requiring a self-join.

SYNTAX
LAG (scalar_expression [,offset] [,default])  
    OVER ( [ partition_by_clause ] order_by_clause )

For example, to retrieve the revenue from the previous day, we can use the following SQL query:

SELECT date, product, revenue, LAG(revenue) OVER (PARTITION BY product ORDER BY date) AS prev_day_revenue
FROM sales_data

This will give us the following result:

dateproductrevenueprev_day_revenue
2022-01-01A100NULL
2022-01-02A150100
2022-01-03A200150
2022-01-01B200NULL
2022-01-02B300200
2022-01-03B250300
RESULT FOR LAG EXAMPLE QUERY
LEAD

LEAD retrieves information from the subsequent row within the same query output without requiring a self-join.

For example, to retrieve the revenue from the next day, we can use the LEAD function as follows:

SELECT date, product, revenue, LEAD(revenue) OVER (PARTITION BY product ORDER BY date) AS next_day_revenue
FROM sales_data

This will give us the following result:

dateproductrevenuenext_day_revenue
2022-01-01A100150
2022-01-02A150200
2022-01-03A200NULL
2022-01-01B200300
2022-01-02B300250
2022-01-03B250NULL
RESULT FOR LEAD EXAMPLE QUERY

Note:

The first and last rows have NULL values for the previous and next day revenue, respectively, since there is no data for the days before or after them.
References

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top