LAG is an analytic window function that lets you look backward in a result set and retrieve the value of a column from a preceding row determined by the current ORDER BY clause. It is evaluated after the WHERE, GROUP BY, and HAVING phases but before the final SELECT output, making it ideal for calculating differences, running comparisons, or detecting changes between consecutive rows. Because LAG operates on a logical window, it does not alter the underlying table and can be combined with PARTITION BY to restart the backward look for each subgroup. If the requested preceding row falls outside the partition, the function returns NULL or the user-supplied default. Offsets start at 1, meaning LAG(col) is equivalent to LAG(col, 1).
- value_expression
(Any) - Column or expression to return from the previous row.- offset
(Integer, optional) - Number of rows back to look. Default is 1.- default
(Same type as value_expression, optional) - Value to return when the offset row does not exist. Default is NULL.- PARTITION BY
(Expression list, optional) - Defines subsets where the offset calculation restarts.- ORDER BY
(Expression list, required) - Establishes the row order used for offset calculation.LEAD, FIRST_VALUE, LAST_VALUE, ROW_NUMBER, OVER clause, WINDOW FUNCTIONS
SQL:1999
LAG fetches the value of a column from a previous row in the result set so you can compare current and prior values without self-joins.
Pass an integer offset as the second argument: LAG(column, 2) looks two rows earlier. If omitted, the default offset is 1.
LAG returns NULL unless you provide a third argument as a default value. Example: LAG(total, 1, 0) returns 0 instead of NULL.
Most modern databases support it, including PostgreSQL, SQL Server, Oracle, MySQL 8.0+, SQLite 3.25+, BigQuery, and Snowflake. Always verify your specific version.