SQL difference from the previous row
Subtract LAG's value from the current row to get the change since the previous row: day-over-day revenue, time between events, price moves.
- 카테고리
- 창
- Returns
type of the expression- In this category
- 18 of 79
구문
x - LAG(x) OVER (ORDER BY d) | x - LAG(x, 1, x) OVER (PARTITION BY g ORDER BY d)
엔진 지원
| 엔진 | 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
SELECT day, closes,
closes - LAG(closes) OVER (ORDER BY day) AS day_change
FROM stock_days;
Any engine
-- per-store delta with a 0 default on the first row
SELECT store_id, day, sales,
sales - LAG(sales, 1, sales) OVER (PARTITION BY store_id ORDER BY day) AS delta
FROM store_sales;
알아 두면 좋은 정보
- The first row's difference is NULL because LAG has nothing to return; wrap in COALESCE if the report needs 0, but consider whether a fake zero belongs in the metric.
- Ordering must be unique for stable deltas: ORDER BY day can reorder tied days and produce a meaningless delta. Add a tiebreaker column.
- Against a fixed baseline (change since the first day) subtract FIRST_VALUE(x) OVER (PARTITION BY g ORDER BY d) instead of LAG.
Questions about Difference From Previous Row
How do I get the difference in days between rows?
LAG the date column, then use each engine's date arithmetic. PostgreSQL and Oracle subtract DATE values directly and return days. SQL Server rejects date - date ('Operand data type date is invalid for subtract operator'), so write DATEDIFF(day, LAG(d) OVER (...), d) for a column d. MySQL's date - date subtracts YYYYMMDD numbers (2024-02-01 minus 2024-01-31 is 70), so use DATEDIFF(d, LAG(d) OVER (...)). SQLite needs julianday(d) - julianday(LAG(d) OVER (...)).
Why is my difference NULL on every first row?
LAG returns the default (NULL unless you pass a third argument) when there is no previous row in the partition. Pass LAG(x, 1, 0) for a zero default or handle NULLs in the report layer.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
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.