Skip to main content
SQL โ€ข LESSON 145

LAG

How can we access the previous order amount in chronological order?

Advancedโฑ 3 Minutesโญ 1580 XP
๐Ÿค” THE QUESTION

How can we access the previous order amount in chronological order?

๐Ÿ’ก WHAT IS IT?

LAG(column) accesses the value from the preceding row within the window without a self-join.

๐ŸŽฏ WHAT IS IT USED FOR?

Period-over-period delta calculation, day-over-day growth tracking, churn detection.

๐Ÿ’ป EXAMPLE
SELECT
order_date,
amount,
LAG(amount) OVER (ORDER BY order_date) AS previous_amount
FROM orders;

๐ŸŽฏ Mission Objectives

Practice typing production-grade SQL code for LAG.

  • โœ“ LAG() function
  • โœ“ Preceding row value
  • โœ“ Time-series lookback
  • โœ“ Delta tracking