SQL LAG function
Reads a value from an earlier row in the same partition, without a self-join. It is the usual tool for period-over-period deltas and for gaps between events.
- Kategorie
- Fenster
- Returns
type of the expression- In this category
- 4 of 79
Syntax
LAG(expression [, offset [, default]]) OVER (PARTITION BY g ORDER BY x)
Engine-Unterstützung
| Engine | Support | Notizen |
|---|---|---|
| SQL Server | Ja | Supported under this name. |
| PostgreSQL | Ja | Supported under this name. |
| MySQL | Ja | MySQL 8.0+ |
| SQLite | Ja | SQLite 3.25+ |
| Oracle | Ja | Supported under this name. |
Beispiele
Any engine
-- CHANGE is a reserved word in MySQL, so the alias is delta
SELECT day, revenue,
revenue - LAG(revenue) OVER (ORDER BY day) AS delta
FROM daily_sales;
PostgreSQL
-- timestamp - timestamp is an interval here; date arithmetic differs per engine
SELECT user_id, at,
at - LAG(at) OVER (PARTITION BY user_id ORDER BY at) AS gap
FROM events;
Gut zu wissen
- The first row has no previous one: LAG returns NULL unless you pass a default (LAG(x, 1, 0)).
- LAG needs an ORDER BY in the OVER clause; without it the previous row is undefined.
- Filtering on a LAG result needs a CTE: window functions evaluate after WHERE.
- IGNORE NULLS (take the previous non-NULL value) works on Oracle and SQL Server 2022+, not on PostgreSQL, MySQL or SQLite.
Questions about LAG
What does LAG return for the first row?
NULL, or the default you pass as the third argument: LAG(revenue, 1, 0) returns 0 instead.
Do I still need a self-join for period-over-period?
Not when the comparison is the previous row: revenue - LAG(revenue) OVER (ORDER BY month) reads the table once. A self-join is still needed when the match is by value rather than position, such as the same month last year when some months are missing.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Lag compare within a group Snippet
- Month-over-month delta Snippet
- SQL window function interview questions Interview questions
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.