SQL LEAD and LAG Window Functions: Period-over-Period Calculations
By Sharon Ben-Moshe · October 2, 2026 · 1 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Master SQL LEAD() and LAG() window functions. Calculate month-over-month growth, compare sequential events, and supply default values without self-joins.
Quick answer
LEAD() and LAG() are SQL window functions used to access data from subsequent (LEAD) or previous (LAG) rows relative to the current row without writing expensive self-joins. Both functions accept three parameters: LEAD(expression, [offset], [default_value]), allowing period-over-period growth and time-delta calculations.
FAQs
What is the difference between LEAD and LAG?
LAG looks backwards in the sorted partition to return values from preceding rows. LEAD looks forwards to return values from succeeding rows.
What is the default offset if not specified?
If omitted, the offset defaults to 1 (the immediately previous or next row). You can pass higher integers like LAG(revenue, 12) for year-over-year monthly comparisons.
How do I prevent NULL on the first or last row?
Provide the third argument as a fallback default value: `LAG(amount, 1, 0)` returns 0 instead of NULL when no previous row exists.
Can LEAD and LAG be used without an ORDER BY clause?
No. Positional window functions require an unambiguous row sequence defined by ORDER BY inside the OVER() clause.
Keep reading
The Comprehensive Guide to SQL Data Types: Storage, Precision, and Cross-Dialect Portability
By Sharon Ben-Moshe · Oct 13, 2026
The complete guide to SQL data types across PostgreSQL, MySQL, SQL Server, and SQLite. Numeric precision, character sets, timestamps, and JSON.
Read postThe Definitive Guide to SQL Window Functions: Syntax, Framing, and Real-World Recipes
By Sharon Ben-Moshe · Oct 13, 2026
The comprehensive guide to SQL window functions. Master OVER, PARTITION BY, ORDER BY, window frames (ROWS vs RANGE), and ranking recipes.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.