LAG / LEAD: Read a value from a previous (LAG) or following (LEAD) row in the window — perfect for diffs over time. LAG and LEAD are window functions that read a value from a previous or following row. revenue - LAG(revenue) OVER (ORDER BY day) calculates the change from the day before, for every day, in one query.
They make comparisons over time simple: growth per month, time between a customer's orders, or the next scheduled appointment. Without them, you would need self-joins or post-processing in application code.
What should you keep in mind with LAG / LEAD?
The OVER clause controls the order, and PARTITION BY restarts the comparison per group, such as per customer. The first row has no previous row, so LAG returns NULL; you can pass a default as the third argument. MySQL 8, PostgreSQL and SQLite all support these functions, so most modern stacks can use them.
What does an example of LAG / LEAD look like?
SELECT day, revenue, revenue - LAG(revenue) OVER (ORDER BY day) AS delta FROM daily_sales;