DELAPARRA
Index
Color
NL
Category: SQL

LAG / LEAD

Explained by Updated

What is LAG / LEAD?

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.

Definition source Coders Lingo, CC BY 4.0

Frequently asked questions about LAG / LEAD

How is LAG / LEAD used in practice?

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;

At a glance

CategorySQL
Explained by
Updated

More SQL terms

All terms starting with L

Skills

Download all skills (zip)

Manuals

Related services

Need any help?

Stuck on one of these in your own project? Tell me what you are working on and I will tell you how I would approach it.