// window reference

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.

카테고리
창
Returns
type of the expression
In this category
4 of 79

구문

LAG(expression [, offset [, default]]) OVER (PARTITION BY g ORDER BY x)

엔진 지원

엔진Support메모
SQL Server 예 Supported under this name.
PostgreSQL 예 Supported under this name.
MySQL 예 MySQL 8.0+
SQLite 예 SQLite 3.25+
Oracle 예 Supported under this name.

예시

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;

알아 두면 좋은 정보

  • 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.

// fewer lookups

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.