LAG looks at the row before
LAG hands you a value from the previous row, so each row can be compared with the one just before it — this month against last month. ORDER BY inside OVER decides what previous means. The very first row has nothing before it, so its LAG value is NULL.
A tiny example
In plain English: Show me each term's score next to the score from the term before it.
SELECT term, score, LAG(score) OVER (ORDER BY term) AS previous
FROM results;What comes back
| term | score | previous |
|---|---|---|
| Autumn | 85 | NULL |
| Spring | 80 | 85 |
| Winter | 90 | 80 |
Each row's previous column is the score from the row above it — Autumn is first, so there's nothing before it.
Related SQL lessons
Ready for a break?
Take on today's cozy puzzle. A fresh, bite-sized query waits every morning — no timers, no pressure.
play today's sip