
For an instructor lead, in-depth look at learning SQL click below.
In SQL, LAG and LEAD are functions that provide a simple way to access data from a previous or following row without using a self-join. These are particularly important in business situations where comparisons between consecutive rows are constantly required, such as in inventory management or financial data analysis. In this blog post, we will explore these functions in more detail.
What is LAG function?
LAG function is a window function that allows you to look data from a previous row, or any row before the current row. This function is invaluable when you need to compare the current row’s values with the values of previous rows.
1 2 3 4 5 6 7 |
SELECT product, sales, LAG(sales, 1, 0) OVER(ORDER BY product) as prev_sales FROM Sales; |
In this example, the LAG function returns sales data from the previous row (1 row back) for comparison with the current row’s sales data. The third parameter represents a default value that will be returned when there are no more rows to ‘lag’ behind, in this case, the value is zero.
What is LEAD function?
LEAD function, on the other hand, is a window function that allows you to look data from a following row or any row ahead of the current row. It is particularly useful when you need to compare a current row with the following rows.
1 2 3 4 5 6 7 |
SELECT product, sales, LEAD(sales, 1, 0) OVER(ORDER BY product) as next_sales FROM Sales; |
This SQL statement uses the LEAD function to return sales data from the following row (1 row ahead) to be compared with the current row’s sales data. Similar to the LAG function, the third parameter determines a value to return when there are no more rows left to ‘lead’, which is set as zero in this example.
In conclusion, LAG and LEAD functions provide valuable ways to create a comparison or a relationship between rows. By using these functions, we are saved from implementing more complex SQL tasks such as self-joining tables.