LAG()
Access the previous row's value — essential for trend analysis
Looking at the Previous Row
LAG() retrieves a value from a previous row in the window. It's the essential tool for comparing each row to what came before it in a sequence. Here's how to use it:
total - LAG(total) OVER (ORDER BY date) gives you the row-over-row change for each record. This is fundamental for trend detection, growth analysis, and spotting anomalies in sequential data.LAG(total) OVER (PARTITION BY customer_id ORDER BY date) looks back within each customer's orders separately, so customer boundaries never cross over.How LAG Works
Access the previous row's value
- LAG(col, n, default) looks back n rows (default: 1)
- Returns NULL if no previous row exists (unless default set)
- ORDER BY inside OVER() defines "previous"
- PARTITION BY creates independent sequences
LAG Patterns
Time-series analysis essentials
- Period-over-period change:
value - LAG(value) - Growth rate:
(value - LAG(value)) * 100.0 / LAG(value) - Gap detection:
date - LAG(date)shows intervals - Session boundaries: flag when gap exceeds threshold
NULL Handling
Edge cases with LAG
- First row in partition → LAG returns NULL
- Provide default:
LAG(val, 1, 0)returns 0 instead - LAG over NULL values → returns the NULL from previous row
- COALESCE(LAG(val), 0) for safe calculations
When to Use LAG
Classic time-series scenarios
- Month-over-month revenue comparison
- Day-over-day user growth
- Detecting streaks and breaks in sequences
- Calculating moving differences and velocities
LAG(col)Previous row value (1 row back by default)LAG(col, n)Value from n rows backLAG(col, 1, default)Replace NULL (no previous row) with default| order_date | total |
|---|---|
| 2024-01-15 | 59.98 |
| 2024-02-20 | 12.5 |
Worked Example
Show customer C1001's orders with the previous order total and the change.
| order_date | total | prev_total | change |
|---|---|---|---|
| 2024-01-15 | 59.98 | NULL | NULL |
| 2024-02-20 | 12.5 | 59.98 | -47.48 |
Key Concepts
Pro Tip
Comparing a value to its predecessor — last month's revenue, yesterday's price, the previous quarter — is fundamental to time-series analysis.
When to Use
Month-over-month growth, day-over-day changes, identifying spikes or drops, comparing sequential measurements.
For all orders (sorted by date), show order_date, total, the previous order total (prev_total), and whether the total increased or decreased (label it trend: "Up", "Down", or "First" for the first row). Show top 8 rows.