window

LAG

Reads a preceding row in the partition, independently of frame boundaries. The fallback applies to absent rows, not existing NULL values. Example target: PostgreSQL 17; focused usage form.

Formal Syntax & Structure

sql syntaxsql
LAG(x,1,-1) OVER (PARTITION BY g ORDER BY x,id)

Working Example

Example Snippetsql
WITH t(id,g,x) AS (VALUES (1,'A',10),(2,'A',20),(3,'A',20),(4,'A',40),(5,'B',7)) SELECT id, LAG(x,1,-1) OVER (PARTITION BY g ORDER BY x,id) AS result FROM t ORDER BY id;
SQL Reference