PostgreSQL 18 reference · Window Functions
PostgreSQL LAG() Function
Return a value from a previous row in the window, or a default when there isn't one. Ideal for comparing with the last period.
PostgreSQL 18 Since 8.4
Syntax
lag(value, offset, default) OVER (PARTITION BY ... ORDER BY ...)
Parameters
| Parameter | Description |
|---|---|
value |
The expression to read. |
offset optional |
Rows back. Default: 1 |
default optional |
Used when there's no such row. Default: NULL |
Return value
The value from that row.
Examples
SELECT order_id, order_date, order_date - lag(order_date) OVER (ORDER BY order_date) AS days_since_previous
FROM orders
LIMIT 4;
Output
order_id | order_date | days_since_previous
----------+------------+---------------------
1 | 2026-01-05 | NULL
2 | 2026-01-12 | 7
3 | 2026-02-02 | 21
4 | 2026-02-14 | 12
(4 rows)Run this on your computer — see “Get Started” for setup.
SELECT month, orders, orders - lag(orders, 1, 0) OVER (ORDER BY month) AS change
FROM (SELECT date_trunc('month', order_date)::date AS month, count(*) AS orders FROM orders GROUP BY 1) AS m
ORDER BY month
LIMIT 4;
Output
month | orders | change ------------+--------+-------- 2026-01-01 | 2 | 2 2026-02-01 | 3 | 1 2026-03-01 | 2 | -1 2026-04-01 | 2 | 0 (4 rows)
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| PostgreSQL 8.4 | Added |
In other languages
LAG()· SQLite
Related
LEAD()· Return a value from a following row in the window, or a default when there isn't one.FIRST_VALUE()· Return a value from the first row of the window frame, such as each department's highest salary.- SQL Window Functions · tutorial