LAG & LEAD (Accessing Adjacent Rows)
Look backward and forward in result streams to compute periods-over-period growth using LAG and LEAD.
LAG & LEAD (Accessing Adjacent Rows) is an essential topic in SQL and relational database engineering.
Overview
Building on foundational principles introduced in ranking-functions, mastering lag & lead (accessing adjacent rows) provides the core mental model and practical query skills needed for production relational database engineering.
SELECT
sales_month,
revenue,
LAG(revenue, 1) OVER (ORDER BY sales_month) AS prev_month_revenue,
revenue - LAG(revenue, 1) OVER (ORDER BY sales_month) AS monthly_growth
FROM monthly_sales;
Key Concepts
- Understand the fundamental syntax, conventions, and mental model.
- Avoid common beginner traps, data type mismatches, and performance pitfalls.
- Apply practical idioms directly in production applications.
[!TIP] Master this concept to build a rock-solid foundation. Next, proceed to running-totals.