In this post we are going to cover LAG and LEAD in Snowflake.
LAG reaches backwards and hands us a value from an earlier row. LEAD reaches forwards and hands us a value from a later row. Once last month’s number is sitting on the same row as this month’s, comparing them is ordinary subtraction.
We will build a monthly series first, then put the previous month beside the current one, then turn that into a change column. After that we will look at the two extra arguments both functions take, and at the one thing that catches everybody out: a null that does not mean what it looks like it means.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 52 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's get one row per month first
- Let's start with LAG and reach back one row
- Now let's turn that into a month-on-month change
- Now let's add LEAD and count the nulls at the edges
- Let's try the third argument: what to use when there is no row
- Now let's change how far back we reach
- Now let's add a PARTITION BY and get days since the last order
- Can we do this without LAG at all?
- One last thing: the previous row is not the previous month
Let's create some sample data
LAG and LEAD are the functions we reach for when the question involves time. So this post works on ORDERS rather than on EMPLOYEES.
The script below creates the table and fills it. Run it once in a worksheet if you have not set it up already.
-- Creates the ORDERS table every query on this page runs against.
-- Part of the shared sample-data script; run it once.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE ORDERS (
ORDER_ID INT,
CUSTOMER_ID INT,
ORDER_DATE DATE,
SHIP_DATE DATE,
STATUS VARCHAR,
AMOUNT NUMBER(10,2),
QUANTITY INT
);
INSERT INTO ORDERS VALUES
(1001, 101, '2023-01-12', '2023-01-15', 'SHIPPED', 4200.00, 12),
(1002, 102, '2023-01-28', '2023-02-02', 'SHIPPED', 890.50, 3),
(1003, 101, '2023-02-14', '2023-02-16', 'SHIPPED', 6150.00, 20),
(1004, 103, '2023-02-27', NULL, 'CANCELLED', 1500.00, 5),
(1005, 104, '2023-03-09', '2023-03-14', 'SHIPPED', 2310.75, 8),
(1006, 101, '2023-03-22', '2023-03-24', 'SHIPPED', 5020.00, 16),
(1007, 105, '2023-04-05', '2023-04-11', 'SHIPPED', 7890.00, 25),
(1008, 102, '2023-04-19', '2023-04-23', 'SHIPPED', 1120.00, 4),
(1009, 103, '2023-05-02', '2023-05-06', 'SHIPPED', 3340.25, 11),
(1010, 106, '2023-05-21', NULL, 'PENDING', 640.00, 2),
(1011, 101, '2023-06-08', '2023-06-10', 'SHIPPED', 8100.00, 27),
(1012, 104, '2023-06-25', '2023-06-30', 'SHIPPED', 1975.50, 7),
(1013, 105, '2023-07-11', '2023-07-15', 'SHIPPED', 6420.00, 21),
(1014, 102, '2023-07-29', '2023-08-03', 'RETURNED', 750.00, 3),
(1015, 107, '2023-08-14', '2023-08-17', 'SHIPPED', 9250.00, 30),
(1016, 103, '2023-08-30', '2023-09-04', 'SHIPPED', 2860.00, 9),
(1017, 101, '2023-09-16', '2023-09-19', 'SHIPPED', 5540.00, 18),
(1018, 106, '2023-10-03', '2023-10-08', 'SHIPPED', 1430.00, 5),
(1019, 105, '2023-10-22', '2023-10-26', 'SHIPPED', 7015.00, 23),
(1020, 107, '2023-11-07', '2023-11-10', 'SHIPPED', 10400.00, 34),
(1021, 102, '2023-11-24', '2023-11-29', 'SHIPPED', 980.00, 4),
(1022, 104, '2023-12-09', NULL, 'CANCELLED', 2250.00, 8),
(1023, 101, '2023-12-27', '2023-12-30', 'SHIPPED', 6730.00, 22),
(1024, 103, '2024-01-15', '2024-01-18', 'SHIPPED', 3910.00, 13),
(1025, 107, '2024-01-31', '2024-02-05', 'SHIPPED', 11200.00, 36),
(1026, 105, '2024-02-17', '2024-02-21', 'SHIPPED', 8340.00, 27),
(1027, 106, '2024-03-04', '2024-03-09', 'SHIPPED', 1690.00, 6),
(1028, 102, '2024-03-21', '2024-03-25', 'SHIPPED', 1240.00, 5),
(1029, 101, '2024-04-06', '2024-04-09', 'SHIPPED', 7460.00, 24),
(1030, 109, '2024-04-23', '2024-04-28', 'SHIPPED', 5180.00, 17),
(1031, 103, '2024-05-10', '2024-05-14', 'SHIPPED', 4025.00, 14),
(1032, 107, '2024-05-28', '2024-06-01', 'SHIPPED', 12850.00, 41),
(1033, 105, '2024-06-13', NULL, 'PENDING', 6900.00, 22),
(1034, 109, '2024-06-30', '2024-07-04', 'SHIPPED', 4760.00, 16),
(1035, 101, '2024-07-18', '2024-07-21', 'SHIPPED', 8820.00, 29),
(1036, 104, '2024-08-02', '2024-08-07', 'SHIPPED', 2540.00, 9),
(1037, 107, '2024-08-25', '2024-08-29', 'SHIPPED', 13100.00, 43),
(1038, 109, '2024-09-11', '2024-09-15', 'SHIPPED', 5930.00, 19),
(1039, 102, '2024-09-29', '2024-10-03', 'RETURNED', 1080.00, 4),
(1040, 101, '2024-10-16', '2024-10-19', 'SHIPPED', 9640.00, 31);
-- One deliberate NULL amount, inserted separately so it is easy to see why it
-- is there. It makes COUNT(*), COUNT(AMOUNT) and SUM() give different answers.
INSERT INTO ORDERS VALUES
(1041, 106, '2024-11-05', NULL, 'PENDING', NULL, 3);One row per order, with a customer, a date and an amount. The very last insert puts in an order with no AMOUNT at all, and that one row is going to matter more than it looks.
Let's get one row per month first
ORDERS holds one row per order, and almost no question about time is asked at that grain. “How are we doing compared to last month?” needs one row per month.
So the first step is a rollup. We truncate the date to the first of its month and aggregate.
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START,
COUNT(*) AS N_ORDERS,
SUM(AMOUNT) AS TOTAL
FROM ORDERS
GROUP BY 1
ORDER BY 1;| MONTH_START | N_ORDERS | TOTAL |
|---|---|---|
| 2023-01-01 | 2 | 5090.50 |
| 2023-02-01 | 2 | 7650.00 |
| 2023-03-01 | 2 | 7330.75 |
| 2023-04-01 | 2 | 9010.00 |
| 2023-05-01 | 2 | 3980.25 |
| 2023-06-01 | 2 | 10075.50 |
| 2023-07-01 | 2 | 7170.00 |
| 2023-08-01 | 2 | 12110.00 |
| 2023-09-01 | 1 | 5540.00 |
| 2023-10-01 | 2 | 8445.00 |
| 2023-11-01 | 2 | 11380.00 |
| 2023-12-01 | 2 | 8980.00 |
| 2024-01-01 | 2 | 15110.00 |
| 2024-02-01 | 1 | 8340.00 |
| 2024-03-01 | 2 | 2930.00 |
| 2024-04-01 | 2 | 12640.00 |
| 2024-05-01 | 2 | 16875.00 |
| 2024-06-01 | 2 | 11660.00 |
| 2024-07-01 | 1 | 8820.00 |
| 2024-08-01 | 2 | 15640.00 |
| 2024-09-01 | 2 | 7010.00 |
| 2024-10-01 | 1 | 9640.00 |
| 2024-11-01 | 1 | NULL |
DATE_TRUNC('MONTH', ORDER_DATE) maps every date in a month to the first day of it. Grouping on it gives us one row per month, in order. This is the series the rest of the post works on.
Look at the final month in that grid before we go any further, because it comes back later. Its TOTAL is NULL. SUM() over a set of amounts that are all NULL is NULL, not zero. The month has an order in it, and no amount to add up.
Let's start with LAG and reach back one row
LAG takes a column and hands us that column’s value from an earlier row in the window. With no offset given it reaches back exactly one row, in the order the OVER clause specifies.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
LAG(TOTAL) OVER (ORDER BY MONTH_START) AS PREV_MONTH
FROM M
ORDER BY MONTH_START;| MONTH_START | TOTAL | PREV_MONTH |
|---|---|---|
| 2023-01-01 | 5090.50 | NULL |
| 2023-02-01 | 7650.00 | 5090.50 |
| 2023-03-01 | 7330.75 | 7650.00 |
| 2023-04-01 | 9010.00 | 7330.75 |
| 2023-05-01 | 3980.25 | 9010.00 |
| 2023-06-01 | 10075.50 | 3980.25 |
| 2023-07-01 | 7170.00 | 10075.50 |
| 2023-08-01 | 12110.00 | 7170.00 |
| 2023-09-01 | 5540.00 | 12110.00 |
| 2023-10-01 | 8445.00 | 5540.00 |
| 2023-11-01 | 11380.00 | 8445.00 |
| 2023-12-01 | 8980.00 | 11380.00 |
| 2024-01-01 | 15110.00 | 8980.00 |
| 2024-02-01 | 8340.00 | 15110.00 |
| 2024-03-01 | 2930.00 | 8340.00 |
| 2024-04-01 | 12640.00 | 2930.00 |
| 2024-05-01 | 16875.00 | 12640.00 |
| 2024-06-01 | 11660.00 | 16875.00 |
| 2024-07-01 | 8820.00 | 11660.00 |
| 2024-08-01 | 15640.00 | 8820.00 |
| 2024-09-01 | 7010.00 | 15640.00 |
| 2024-10-01 | 9640.00 | 7010.00 |
| 2024-11-01 | NULL | 9640.00 |
Read any row across. TOTAL is that month, and PREV_MONTH is the month before it. The second row carries the first row’s total, the third carries the second’s, and so on down the grid.
The first row has no row before it, so its PREV_MONTH is NULL. That is not an error and it is not something to patch over. It is LAG reporting, accurately, that there is nothing there.
The ORDER BY inside OVER is what makes “before” mean anything, so LAG and LEAD both require one. It is also completely independent of the ORDER BY at the end of the statement. The window’s ordering decides which row the value comes from. The statement’s ordering decides how the finished rows are presented to you.
Now let's turn that into a month-on-month change
This is what LAG is for. The previous value is sitting on the same row as the current one, so the comparison everybody wants is just arithmetic. We subtract one column from the other.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
LAG(TOTAL) OVER (ORDER BY MONTH_START) AS PREV_MONTH,
TOTAL - LAG(TOTAL) OVER (ORDER BY MONTH_START) AS CHANGE
FROM M
ORDER BY MONTH_START;| MONTH_START | TOTAL | PREV_MONTH | CHANGE |
|---|---|---|---|
| 2023-01-01 | 5090.50 | NULL | NULL |
| 2023-02-01 | 7650.00 | 5090.50 | 2559.50 |
| 2023-03-01 | 7330.75 | 7650.00 | -319.25 |
| 2023-04-01 | 9010.00 | 7330.75 | 1679.25 |
| 2023-05-01 | 3980.25 | 9010.00 | -5029.75 |
| 2023-06-01 | 10075.50 | 3980.25 | 6095.25 |
| 2023-07-01 | 7170.00 | 10075.50 | -2905.50 |
| 2023-08-01 | 12110.00 | 7170.00 | 4940.00 |
| 2023-09-01 | 5540.00 | 12110.00 | -6570.00 |
| 2023-10-01 | 8445.00 | 5540.00 | 2905.00 |
| 2023-11-01 | 11380.00 | 8445.00 | 2935.00 |
| 2023-12-01 | 8980.00 | 11380.00 | -2400.00 |
| 2024-01-01 | 15110.00 | 8980.00 | 6130.00 |
| 2024-02-01 | 8340.00 | 15110.00 | -6770.00 |
| 2024-03-01 | 2930.00 | 8340.00 | -5410.00 |
| 2024-04-01 | 12640.00 | 2930.00 | 9710.00 |
| 2024-05-01 | 16875.00 | 12640.00 | 4235.00 |
| 2024-06-01 | 11660.00 | 16875.00 | -5215.00 |
| 2024-07-01 | 8820.00 | 11660.00 | -2840.00 |
| 2024-08-01 | 15640.00 | 8820.00 | 6820.00 |
| 2024-09-01 | 7010.00 | 15640.00 | -8630.00 |
| 2024-10-01 | 9640.00 | 7010.00 | 2630.00 |
| 2024-11-01 | NULL | 9640.00 | NULL |
A whole month-on-month change column, in one expression, with no join and no self-reference. It is positive where the month grew on the one before it, and negative where it shrank.
Two rows have a NULL CHANGE, and they are null for two different reasons. The first row has nothing to subtract from. The last row has nothing to subtract, because its own TOTAL is NULL, and NULL minus a number is NULL.
Now let's add LEAD and count the nulls at the edges
LEAD is the same function pointing the other way. Same arguments, same window, and it hands us a value from a later row. Put both on one query and every row carries its neighbours on each side.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
LAG(TOTAL) OVER (ORDER BY MONTH_START) AS PREV_MONTH,
LEAD(TOTAL) OVER (ORDER BY MONTH_START) AS NEXT_MONTH
FROM M
ORDER BY MONTH_START;| MONTH_START | TOTAL | PREV_MONTH | NEXT_MONTH |
|---|---|---|---|
| 2023-01-01 | 5090.50 | NULL | 7650.00 |
| 2023-02-01 | 7650.00 | 5090.50 | 7330.75 |
| 2023-03-01 | 7330.75 | 7650.00 | 9010.00 |
| 2023-04-01 | 9010.00 | 7330.75 | 3980.25 |
| 2023-05-01 | 3980.25 | 9010.00 | 10075.50 |
| 2023-06-01 | 10075.50 | 3980.25 | 7170.00 |
| 2023-07-01 | 7170.00 | 10075.50 | 12110.00 |
| 2023-08-01 | 12110.00 | 7170.00 | 5540.00 |
| 2023-09-01 | 5540.00 | 12110.00 | 8445.00 |
| 2023-10-01 | 8445.00 | 5540.00 | 11380.00 |
| 2023-11-01 | 11380.00 | 8445.00 | 8980.00 |
| 2023-12-01 | 8980.00 | 11380.00 | 15110.00 |
| 2024-01-01 | 15110.00 | 8980.00 | 8340.00 |
| 2024-02-01 | 8340.00 | 15110.00 | 2930.00 |
| 2024-03-01 | 2930.00 | 8340.00 | 12640.00 |
| 2024-04-01 | 12640.00 | 2930.00 | 16875.00 |
| 2024-05-01 | 16875.00 | 12640.00 | 11660.00 |
| 2024-06-01 | 11660.00 | 16875.00 | 8820.00 |
| 2024-07-01 | 8820.00 | 11660.00 | 15640.00 |
| 2024-08-01 | 15640.00 | 8820.00 | 7010.00 |
| 2024-09-01 | 7010.00 | 15640.00 | 9640.00 |
| 2024-10-01 | 9640.00 | 7010.00 | NULL |
| 2024-11-01 | NULL | 9640.00 | NULL |
Now let's count the nulls, because there is something hiding in them. COUNT(column) ignores NULLs, which makes it a null-counter in disguise. The row count minus the count of a column is how many nulls that column has.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
), L AS (
SELECT MONTH_START,
LAG(TOTAL) OVER (ORDER BY MONTH_START) AS PREV_MONTH,
LEAD(TOTAL) OVER (ORDER BY MONTH_START) AS NEXT_MONTH
FROM M
)
SELECT COUNT(*) AS MONTHS,
COUNT(PREV_MONTH) AS ROWS_WITH_A_PREVIOUS,
COUNT(NEXT_MONTH) AS ROWS_WITH_A_NEXT
FROM L;| MONTHS | ROWS_WITH_A_PREVIOUS | ROWS_WITH_A_NEXT |
|---|---|---|
| 23 | 22 | 21 |
ROWS_WITH_A_PREVIOUS is one less than MONTHS, which is what we expected. Only the first month has nothing before it. But ROWS_WITH_A_NEXT is two less, not one, and the second missing row is not an edge at all.
Go back to the LEAD grid and read the final month and the one before it. The final month has no next row, so its NEXT_MONTH is null for the obvious reason. The month before it does have a next row, and its NEXT_MONTH is null anyway, because the value in that next row is itself null.
LAG and LEAD hand you a value, not a row. If the row they reach is there but the value in it is NULL, NULL is what you get. It is indistinguishable from the null you get at the edge of the window. A query that counts nulls to find the edges will quietly count this one too.
There is a way to tell the two cases apart when we need to. We LEAD something that cannot be null, like the month itself, and test that instead. A null LEAD(MONTH_START) means there really is no next row.
Let's try the third argument: what to use when there is no row
LAG takes up to three arguments. The second is how many rows to reach back. The third is the value to return when there is no such row, instead of the default NULL.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
LAG(TOTAL, 1) OVER (ORDER BY MONTH_START) AS PREV_DEFAULT_NULL,
LAG(TOTAL, 1, 0) OVER (ORDER BY MONTH_START) AS PREV_DEFAULT_ZERO
FROM M
ORDER BY MONTH_START;| MONTH_START | TOTAL | PREV_DEFAULT_NULL | PREV_DEFAULT_ZERO |
|---|---|---|---|
| 2023-01-01 | 5090.50 | NULL | 0.00 |
| 2023-02-01 | 7650.00 | 5090.50 | 5090.50 |
| 2023-03-01 | 7330.75 | 7650.00 | 7650.00 |
| 2023-04-01 | 9010.00 | 7330.75 | 7330.75 |
| 2023-05-01 | 3980.25 | 9010.00 | 9010.00 |
| 2023-06-01 | 10075.50 | 3980.25 | 3980.25 |
| 2023-07-01 | 7170.00 | 10075.50 | 10075.50 |
| 2023-08-01 | 12110.00 | 7170.00 | 7170.00 |
| 2023-09-01 | 5540.00 | 12110.00 | 12110.00 |
| 2023-10-01 | 8445.00 | 5540.00 | 5540.00 |
| 2023-11-01 | 11380.00 | 8445.00 | 8445.00 |
| 2023-12-01 | 8980.00 | 11380.00 | 11380.00 |
| 2024-01-01 | 15110.00 | 8980.00 | 8980.00 |
| 2024-02-01 | 8340.00 | 15110.00 | 15110.00 |
| 2024-03-01 | 2930.00 | 8340.00 | 8340.00 |
| 2024-04-01 | 12640.00 | 2930.00 | 2930.00 |
| 2024-05-01 | 16875.00 | 12640.00 | 12640.00 |
| 2024-06-01 | 11660.00 | 16875.00 | 16875.00 |
| 2024-07-01 | 8820.00 | 11660.00 | 11660.00 |
| 2024-08-01 | 15640.00 | 8820.00 | 8820.00 |
| 2024-09-01 | 7010.00 | 15640.00 | 15640.00 |
| 2024-10-01 | 9640.00 | 7010.00 | 7010.00 |
| 2024-11-01 | NULL | 9640.00 | 9640.00 |
The two columns are identical everywhere except the first row, where one says NULL and the other says 0.00. That looks like a tidy-up. Let's see what it does to the change column.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
TOTAL - LAG(TOTAL, 1) OVER (ORDER BY MONTH_START) AS CHANGE_NULL,
TOTAL - LAG(TOTAL, 1, 0) OVER (ORDER BY MONTH_START) AS CHANGE_ZERO
FROM M
ORDER BY MONTH_START;| MONTH_START | TOTAL | CHANGE_NULL | CHANGE_ZERO |
|---|---|---|---|
| 2023-01-01 | 5090.50 | NULL | 5090.50 |
| 2023-02-01 | 7650.00 | 2559.50 | 2559.50 |
| 2023-03-01 | 7330.75 | -319.25 | -319.25 |
| 2023-04-01 | 9010.00 | 1679.25 | 1679.25 |
| 2023-05-01 | 3980.25 | -5029.75 | -5029.75 |
| 2023-06-01 | 10075.50 | 6095.25 | 6095.25 |
| 2023-07-01 | 7170.00 | -2905.50 | -2905.50 |
| 2023-08-01 | 12110.00 | 4940.00 | 4940.00 |
| 2023-09-01 | 5540.00 | -6570.00 | -6570.00 |
| 2023-10-01 | 8445.00 | 2905.00 | 2905.00 |
| 2023-11-01 | 11380.00 | 2935.00 | 2935.00 |
| 2023-12-01 | 8980.00 | -2400.00 | -2400.00 |
| 2024-01-01 | 15110.00 | 6130.00 | 6130.00 |
| 2024-02-01 | 8340.00 | -6770.00 | -6770.00 |
| 2024-03-01 | 2930.00 | -5410.00 | -5410.00 |
| 2024-04-01 | 12640.00 | 9710.00 | 9710.00 |
| 2024-05-01 | 16875.00 | 4235.00 | 4235.00 |
| 2024-06-01 | 11660.00 | -5215.00 | -5215.00 |
| 2024-07-01 | 8820.00 | -2840.00 | -2840.00 |
| 2024-08-01 | 15640.00 | 6820.00 | 6820.00 |
| 2024-09-01 | 7010.00 | -8630.00 | -8630.00 |
| 2024-10-01 | 9640.00 | 2630.00 | 2630.00 |
| 2024-11-01 | NULL | NULL | NULL |
CHANGE_NULL is null on the first row, which is honest. There is nothing to compare that month to. CHANGE_ZERO is a number instead, and the number is the month’s own total. It reads as if the business grew from nothing to its entire first-month revenue inside that month.
A default of 0 is reasonable on a running total, where zero is genuinely what came before. On a change or growth column it invents movement that never happened, and it does it silently, in the one row most likely to end up at the top of a chart. The NULL was telling you the truth.
Read the rest of those two change columns as well. From the second month onwards CHANGE_NULL and CHANGE_ZERO are the same on every row. A default only ever affects rows where the reach falls outside the window, so the damage is always at the edges, which is exactly where nobody checks.
Now let's change how far back we reach
The offset does not have to be one. Let's ask for one row back and two rows back in the same query, so we can see both sequences side by side.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, TOTAL,
LAG(TOTAL, 1) OVER (ORDER BY MONTH_START) AS ONE_BACK,
LAG(TOTAL, 2) OVER (ORDER BY MONTH_START) AS TWO_BACK
FROM M
ORDER BY MONTH_START;| MONTH_START | TOTAL | ONE_BACK | TWO_BACK |
|---|---|---|---|
| 2023-01-01 | 5090.50 | NULL | NULL |
| 2023-02-01 | 7650.00 | 5090.50 | NULL |
| 2023-03-01 | 7330.75 | 7650.00 | 5090.50 |
| 2023-04-01 | 9010.00 | 7330.75 | 7650.00 |
| 2023-05-01 | 3980.25 | 9010.00 | 7330.75 |
| 2023-06-01 | 10075.50 | 3980.25 | 9010.00 |
| 2023-07-01 | 7170.00 | 10075.50 | 3980.25 |
| 2023-08-01 | 12110.00 | 7170.00 | 10075.50 |
| 2023-09-01 | 5540.00 | 12110.00 | 7170.00 |
| 2023-10-01 | 8445.00 | 5540.00 | 12110.00 |
| 2023-11-01 | 11380.00 | 8445.00 | 5540.00 |
| 2023-12-01 | 8980.00 | 11380.00 | 8445.00 |
| 2024-01-01 | 15110.00 | 8980.00 | 11380.00 |
| 2024-02-01 | 8340.00 | 15110.00 | 8980.00 |
| 2024-03-01 | 2930.00 | 8340.00 | 15110.00 |
| 2024-04-01 | 12640.00 | 2930.00 | 8340.00 |
| 2024-05-01 | 16875.00 | 12640.00 | 2930.00 |
| 2024-06-01 | 11660.00 | 16875.00 | 12640.00 |
| 2024-07-01 | 8820.00 | 11660.00 | 16875.00 |
| 2024-08-01 | 15640.00 | 8820.00 | 11660.00 |
| 2024-09-01 | 7010.00 | 15640.00 | 8820.00 |
| 2024-10-01 | 9640.00 | 7010.00 | 15640.00 |
| 2024-11-01 | NULL | 9640.00 | 7010.00 |
TWO_BACK is the ONE_BACK column shifted down by one more row. The third row is the first one that can see two rows back. The top two rows cannot, so both of them are NULL.
An offset of n leaves n nulls at the start of each partition. Remember that before you write LAG(TOTAL, 12) for a year-on-year comparison and wonder where your first twelve rows went.
Now let's add a PARTITION BY and get days since the last order
LAG and LEAD take PARTITION BY like every other window function, and it restarts the reach inside each group. That gives us a genuinely useful column in three lines: the gap between each order and that same customer’s previous one.
SELECT CUSTOMER_ID, ORDER_ID, ORDER_DATE,
LAG(ORDER_DATE) OVER (PARTITION BY CUSTOMER_ID ORDER BY ORDER_DATE) AS PREV_ORDER_DATE,
DATEDIFF('DAY',
LAG(ORDER_DATE) OVER (PARTITION BY CUSTOMER_ID ORDER BY ORDER_DATE),
ORDER_DATE) AS DAYS_SINCE
FROM ORDERS
ORDER BY CUSTOMER_ID, ORDER_DATE
LIMIT 14;| CUSTOMER_ID | ORDER_ID | ORDER_DATE | PREV_ORDER_DATE | DAYS_SINCE |
|---|---|---|---|---|
| 101 | 1001 | 2023-01-12 | NULL | NULL |
| 101 | 1003 | 2023-02-14 | 2023-01-12 | 33 |
| 101 | 1006 | 2023-03-22 | 2023-02-14 | 36 |
| 101 | 1011 | 2023-06-08 | 2023-03-22 | 78 |
| 101 | 1017 | 2023-09-16 | 2023-06-08 | 100 |
| 101 | 1023 | 2023-12-27 | 2023-09-16 | 102 |
| 101 | 1029 | 2024-04-06 | 2023-12-27 | 101 |
| 101 | 1035 | 2024-07-18 | 2024-04-06 | 103 |
| 101 | 1040 | 2024-10-16 | 2024-07-18 | 90 |
| 102 | 1002 | 2023-01-28 | NULL | NULL |
| 102 | 1008 | 2023-04-19 | 2023-01-28 | 81 |
| 102 | 1014 | 2023-07-29 | 2023-04-19 | 101 |
| 102 | 1021 | 2023-11-24 | 2023-07-29 | 118 |
| 102 | 1028 | 2024-03-21 | 2023-11-24 | 118 |
LAG(ORDER_DATE) partitioned by customer gives us the date of that customer’s previous order, and DATEDIFF turns the pair of dates into a number of days. The grid carries the capture’s own LIMIT 14, so it is the first stretch of the result rather than all of ORDERS.
The first customer’s block is complete inside that limit. It is 9 rows, the first of them carrying a null and the other 8 carrying a gap in days. Then the grid reaches the next customer and the numbering starts again. A new partition, so there is no previous row, so DAYS_SINCE is null again. That second block is cut off by the LIMIT, so do not count it.
Which means every customer contributes exactly one null. That is a checkable claim rather than a plausible one, so let's check it.
WITH L AS (
SELECT CUSTOMER_ID,
LAG(ORDER_DATE) OVER (PARTITION BY CUSTOMER_ID ORDER BY ORDER_DATE) AS PREV
FROM ORDERS
)
SELECT COUNT(*) AS TOTAL_ORDERS,
COUNT(PREV) AS ROWS_WITH_A_PREVIOUS,
COUNT(*) - COUNT(PREV) AS ROWS_WITHOUT,
COUNT(DISTINCT CUSTOMER_ID) AS CUSTOMERS
FROM L;| TOTAL_ORDERS | ROWS_WITH_A_PREVIOUS | ROWS_WITHOUT | CUSTOMERS |
|---|---|---|---|
| 41 | 33 | 8 | 8 |
TOTAL_ORDERS minus ROWS_WITH_A_PREVIOUS is ROWS_WITHOUT, and ROWS_WITHOUT equals CUSTOMERS, the number of distinct customers in ORDERS. One null each, for each customer’s first order.
That identity is a good sanity check on any partitioned LAG: the number of nulls should equal the number of partitions. If it is higher, either your data contains nulls of its own in the lagged column, or your partition key is finer than you thought.
Can we do this without LAG at all?
We can. None of this is impossible without window functions. The pre-window way to put last month beside this month is to join the monthly table to itself, matching each row against the row whose month is one month earlier.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT A.MONTH_START, A.TOTAL, B.TOTAL AS PREV_MONTH
FROM M A
LEFT JOIN M B ON B.MONTH_START = DATEADD('MONTH', -1, A.MONTH_START)
ORDER BY A.MONTH_START;| MONTH_START | TOTAL | PREV_MONTH |
|---|---|---|
| 2023-01-01 | 5090.50 | NULL |
| 2023-02-01 | 7650.00 | 5090.50 |
| 2023-03-01 | 7330.75 | 7650.00 |
| 2023-04-01 | 9010.00 | 7330.75 |
| 2023-05-01 | 3980.25 | 9010.00 |
| 2023-06-01 | 10075.50 | 3980.25 |
| 2023-07-01 | 7170.00 | 10075.50 |
| 2023-08-01 | 12110.00 | 7170.00 |
| 2023-09-01 | 5540.00 | 12110.00 |
| 2023-10-01 | 8445.00 | 5540.00 |
| 2023-11-01 | 11380.00 | 8445.00 |
| 2023-12-01 | 8980.00 | 11380.00 |
| 2024-01-01 | 15110.00 | 8980.00 |
| 2024-02-01 | 8340.00 | 15110.00 |
| 2024-03-01 | 2930.00 | 8340.00 |
| 2024-04-01 | 12640.00 | 2930.00 |
| 2024-05-01 | 16875.00 | 12640.00 |
| 2024-06-01 | 11660.00 | 16875.00 |
| 2024-07-01 | 8820.00 | 11660.00 |
| 2024-08-01 | 15640.00 | 8820.00 |
| 2024-09-01 | 7010.00 | 15640.00 |
| 2024-10-01 | 9640.00 | 7010.00 |
| 2024-11-01 | NULL | 9640.00 |
Same column. The LEFT JOIN is what keeps the first month in the result. It has no match, so its PREV_MONTH arrives as NULL, which is what LAG gave us too.
Rather than eyeball two grids, let's subtract one result from the other with MINUS.
WITH M AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, SUM(AMOUNT) AS TOTAL
FROM ORDERS GROUP BY 1
)
SELECT MONTH_START, LAG(TOTAL) OVER (ORDER BY MONTH_START) FROM M
MINUS
SELECT A.MONTH_START, B.TOTAL
FROM M A LEFT JOIN M B ON B.MONTH_START = DATEADD('MONTH', -1, A.MONTH_START);| MONTH_START | LAG(TOTAL) OVER (ORDER BY MONTH_START) |
|---|
No rows. So every (month, previous month) pair the LAG version produced is also produced by the join. MINUS only runs one way, so running it in the other direction as well is what would make it a two-way proof. One direction, plus the fact that both versions returned 23 rows, is already a strong check.
So why prefer LAG? Because of what we have to write and maintain. The join names the same table twice, needs an alias for each, and needs its date arithmetic exactly right: DATEADD in the correct direction, at the correct grain, against a column that has already been truncated. LAG is one function call with no join condition to get wrong.
One last thing: the previous row is not the previous month
Here is the part that matters more than any of the syntax, and it is the reason those two queries are not interchangeable in general.
LAG gives you the previous row. The self join gives you the previous month. Those are the same thing only when every month between the first and the last is actually present in the data.
If a month has no orders at all it produces no row, and LAG will happily hand us the month before it and label the column PREV_MONTH. The join matches on an explicit date, so it returns NULL instead, correctly, because there is no previous month to show.
Which means the LAG version and the join version agreeing was a fact about this data, not a fact about the functions. So let's check that rather than assume it. We build a calendar of every month between the first order and the last, then look for the ones with nothing in them.
WITH RECURSIVE BOUNDS AS (
SELECT DATE_TRUNC('MONTH', MIN(ORDER_DATE)) AS FIRST_M,
DATE_TRUNC('MONTH', MAX(ORDER_DATE)) AS LAST_M
FROM ORDERS
),
CAL (M) AS (
SELECT FIRST_M FROM BOUNDS
UNION ALL
SELECT DATEADD('MONTH', 1, M) FROM CAL WHERE M < (SELECT LAST_M FROM BOUNDS)
),
MONTHLY AS (
SELECT DATE_TRUNC('MONTH', ORDER_DATE) AS MONTH_START, COUNT(*) AS N
FROM ORDERS GROUP BY 1
)
SELECT C.M AS MONTH_START
FROM CAL C
LEFT JOIN MONTHLY T ON T.MONTH_START = C.M
WHERE T.MONTH_START IS NULL
ORDER BY C.M;| MONTH_START |
|---|
No rows, so no gaps, and that is why the two versions agreed. The recursive CTE builds the calendar by starting at the first month and adding one month at a time until it reaches the last. The LEFT JOIN with IS NULL is the anti-join from Level 3, finding calendar months the data does not have.
On data with real gaps, like a seasonal product or a customer who went quiet for a quarter, the fix is to generate the dense calendar first, LEFT JOIN the facts onto it, and then apply LAG. The window function is only as dense as the rows we give it.
Key points
LAGreads a value from an earlier row in the window andLEADfrom a later one. Both require anORDER BYinsideOVER, and both takePARTITION BY.- With the previous value on the row, month-on-month change is a subtraction. No join, no subquery, one expression.
- The second argument is the offset. An offset of
nleavesnnulls at the start of every partition. - The third argument is the value to use when the reach falls outside the window. It only ever changes rows at the edges.
- A default of
0is fine on a running total and wrong on a change column, where it invents growth that never happened. - These functions return a value, not a row. A null can mean “no such row” or “that row’s value is null”, and the two are indistinguishable in the output. That is what made the null count on this page come back one short.
- In a partitioned
LAG, the number of nulls should equal the number of partitions. It is a cheap check and it catches a wrong partition key. - A self join on
month − 1can produce the same column, butLAGis one function call instead of a second table reference plus date arithmetic. LAGgives the previous row, not the previous month. They coincide only when the series has no gaps, so check for gaps, or build a dense calendar first.
Episode 53 — FIRST_VALUE, LAST_VALUE and NTH_VALUE. Instead of one row either side, reach all the way to the ends of the window, and meet the most famous trap in window functions, which Snowflake turns out not to have.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode. The ORDERS data is invented demo data created by that script. No performance or benchmark claims are made anywhere in this series, and nothing on this page is timed. Function behaviour follows the LAG documentation and the LEAD documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.