Welcome to our deep dive into SQL LAG and LEAD functions! These powerful tools will help you tackle common data analysis challenges, making your SQL queries even more powerful. Let's get started!
LAG and LEAD are window functions in SQL that allow you to refer to rows that are not the current row. LAG looks backward to the preceding rows, while LEAD looks forward to the following rows.
The LAG function returns the value of an expression from a specified row that is offset a given number of rows before the current row.
LAG(expression, offset, default_value) OVER (ORDER BY sort_expression)The LEAD function returns the value of an expression from a specified row that is offset a given number of rows after the current row.
LEAD(expression, offset, default_value) OVER (ORDER BY sort_expression)Let's consider a simple table of sales data:
CREATE TABLE sales_data (
sale_id INT PRIMARY KEY,
product VARCHAR(20),
sale_date DATE,
sales INT
);
INSERT INTO sales_data VALUES
(1, 'Product A', '2022-01-01', 100),
(2, 'Product B', '2022-01-02', 200),
(3, 'Product C', '2022-01-03', 150),
(4, 'Product D', '2022-01-04', 250),
(5, 'Product E', '2022-01-05', 300);Let's find the sales amount of the previous day for each sale:
SELECT
sale_id,
product,
sale_date,
sales,
LAG(sales) OVER (ORDER BY sale_date) AS prev_day_sales
FROM sales_data;Now, let's find the sales amount of the next day for each sale:
SELECT
sale_id,
product,
sale_date,
sales,
LEAD(sales) OVER (ORDER BY sale_date) AS next_day_sales
FROM sales_data;Which SQL function returns the value of an expression from a specified row that is offset a given number of rows before the current row?
Happy learning, and remember to practice with different data sets to fully grasp the power of LAG and LEAD functions! 💪