Snowflake SQL Tutorial 52 - LAG and LEAD in Snowflake

Snowflake SQL · Episode 52

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

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.

Sample data
-- 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.

Query
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;
Result23 rows · 3 columns
MONTH_STARTN_ORDERSTOTAL
2023-01-0125090.50
2023-02-0127650.00
2023-03-0127330.75
2023-04-0129010.00
2023-05-0123980.25
2023-06-01210075.50
2023-07-0127170.00
2023-08-01212110.00
2023-09-0115540.00
2023-10-0128445.00
2023-11-01211380.00
2023-12-0128980.00
2024-01-01215110.00
2024-02-0118340.00
2024-03-0122930.00
2024-04-01212640.00
2024-05-01216875.00
2024-06-01211660.00
2024-07-0118820.00
2024-08-01215640.00
2024-09-0127010.00
2024-10-0119640.00
2024-11-011NULL

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.

Query
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;
Result23 rows · 3 columns
MONTH_STARTTOTALPREV_MONTH
2023-01-015090.50NULL
2023-02-017650.005090.50
2023-03-017330.757650.00
2023-04-019010.007330.75
2023-05-013980.259010.00
2023-06-0110075.503980.25
2023-07-017170.0010075.50
2023-08-0112110.007170.00
2023-09-015540.0012110.00
2023-10-018445.005540.00
2023-11-0111380.008445.00
2023-12-018980.0011380.00
2024-01-0115110.008980.00
2024-02-018340.0015110.00
2024-03-012930.008340.00
2024-04-0112640.002930.00
2024-05-0116875.0012640.00
2024-06-0111660.0016875.00
2024-07-018820.0011660.00
2024-08-0115640.008820.00
2024-09-017010.0015640.00
2024-10-019640.007010.00
2024-11-01NULL9640.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.

Two ORDER BYs, two jobs

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.

Query
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;
Result23 rows · 4 columns
MONTH_STARTTOTALPREV_MONTHCHANGE
2023-01-015090.50NULLNULL
2023-02-017650.005090.502559.50
2023-03-017330.757650.00-319.25
2023-04-019010.007330.751679.25
2023-05-013980.259010.00-5029.75
2023-06-0110075.503980.256095.25
2023-07-017170.0010075.50-2905.50
2023-08-0112110.007170.004940.00
2023-09-015540.0012110.00-6570.00
2023-10-018445.005540.002905.00
2023-11-0111380.008445.002935.00
2023-12-018980.0011380.00-2400.00
2024-01-0115110.008980.006130.00
2024-02-018340.0015110.00-6770.00
2024-03-012930.008340.00-5410.00
2024-04-0112640.002930.009710.00
2024-05-0116875.0012640.004235.00
2024-06-0111660.0016875.00-5215.00
2024-07-018820.0011660.00-2840.00
2024-08-0115640.008820.006820.00
2024-09-017010.0015640.00-8630.00
2024-10-019640.007010.002630.00
2024-11-01NULL9640.00NULL

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.

Query
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;
Result23 rows · 4 columns
MONTH_STARTTOTALPREV_MONTHNEXT_MONTH
2023-01-015090.50NULL7650.00
2023-02-017650.005090.507330.75
2023-03-017330.757650.009010.00
2023-04-019010.007330.753980.25
2023-05-013980.259010.0010075.50
2023-06-0110075.503980.257170.00
2023-07-017170.0010075.5012110.00
2023-08-0112110.007170.005540.00
2023-09-015540.0012110.008445.00
2023-10-018445.005540.0011380.00
2023-11-0111380.008445.008980.00
2023-12-018980.0011380.0015110.00
2024-01-0115110.008980.008340.00
2024-02-018340.0015110.002930.00
2024-03-012930.008340.0012640.00
2024-04-0112640.002930.0016875.00
2024-05-0116875.0012640.0011660.00
2024-06-0111660.0016875.008820.00
2024-07-018820.0011660.0015640.00
2024-08-0115640.008820.007010.00
2024-09-017010.0015640.009640.00
2024-10-019640.007010.00NULL
2024-11-01NULL9640.00NULL

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.

Query
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;
Result1 row · 3 columns
MONTHSROWS_WITH_A_PREVIOUSROWS_WITH_A_NEXT
232221

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.

The distinction that causes the off-by-one

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.

Query
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;
Result23 rows · 4 columns
MONTH_STARTTOTALPREV_DEFAULT_NULLPREV_DEFAULT_ZERO
2023-01-015090.50NULL0.00
2023-02-017650.005090.505090.50
2023-03-017330.757650.007650.00
2023-04-019010.007330.757330.75
2023-05-013980.259010.009010.00
2023-06-0110075.503980.253980.25
2023-07-017170.0010075.5010075.50
2023-08-0112110.007170.007170.00
2023-09-015540.0012110.0012110.00
2023-10-018445.005540.005540.00
2023-11-0111380.008445.008445.00
2023-12-018980.0011380.0011380.00
2024-01-0115110.008980.008980.00
2024-02-018340.0015110.0015110.00
2024-03-012930.008340.008340.00
2024-04-0112640.002930.002930.00
2024-05-0116875.0012640.0012640.00
2024-06-0111660.0016875.0016875.00
2024-07-018820.0011660.0011660.00
2024-08-0115640.008820.008820.00
2024-09-017010.0015640.0015640.00
2024-10-019640.007010.007010.00
2024-11-01NULL9640.009640.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.

Query
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;
Result23 rows · 4 columns
MONTH_STARTTOTALCHANGE_NULLCHANGE_ZERO
2023-01-015090.50NULL5090.50
2023-02-017650.002559.502559.50
2023-03-017330.75-319.25-319.25
2023-04-019010.001679.251679.25
2023-05-013980.25-5029.75-5029.75
2023-06-0110075.506095.256095.25
2023-07-017170.00-2905.50-2905.50
2023-08-0112110.004940.004940.00
2023-09-015540.00-6570.00-6570.00
2023-10-018445.002905.002905.00
2023-11-0111380.002935.002935.00
2023-12-018980.00-2400.00-2400.00
2024-01-0115110.006130.006130.00
2024-02-018340.00-6770.00-6770.00
2024-03-012930.00-5410.00-5410.00
2024-04-0112640.009710.009710.00
2024-05-0116875.004235.004235.00
2024-06-0111660.00-5215.00-5215.00
2024-07-018820.00-2840.00-2840.00
2024-08-0115640.006820.006820.00
2024-09-017010.00-8630.00-8630.00
2024-10-019640.002630.002630.00
2024-11-01NULLNULLNULL

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.

Careful with that third argument

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.

Query
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;
Result23 rows · 4 columns
MONTH_STARTTOTALONE_BACKTWO_BACK
2023-01-015090.50NULLNULL
2023-02-017650.005090.50NULL
2023-03-017330.757650.005090.50
2023-04-019010.007330.757650.00
2023-05-013980.259010.007330.75
2023-06-0110075.503980.259010.00
2023-07-017170.0010075.503980.25
2023-08-0112110.007170.0010075.50
2023-09-015540.0012110.007170.00
2023-10-018445.005540.0012110.00
2023-11-0111380.008445.005540.00
2023-12-018980.0011380.008445.00
2024-01-0115110.008980.0011380.00
2024-02-018340.0015110.008980.00
2024-03-012930.008340.0015110.00
2024-04-0112640.002930.008340.00
2024-05-0116875.0012640.002930.00
2024-06-0111660.0016875.0012640.00
2024-07-018820.0011660.0016875.00
2024-08-0115640.008820.0011660.00
2024-09-017010.0015640.008820.00
2024-10-019640.007010.0015640.00
2024-11-01NULL9640.007010.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.

Query
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;
Result14 rows · 5 columns
CUSTOMER_IDORDER_IDORDER_DATEPREV_ORDER_DATEDAYS_SINCE
10110012023-01-12NULLNULL
10110032023-02-142023-01-1233
10110062023-03-222023-02-1436
10110112023-06-082023-03-2278
10110172023-09-162023-06-08100
10110232023-12-272023-09-16102
10110292024-04-062023-12-27101
10110352024-07-182024-04-06103
10110402024-10-162024-07-1890
10210022023-01-28NULLNULL
10210082023-04-192023-01-2881
10210142023-07-292023-04-19101
10210212023-11-242023-07-29118
10210282024-03-212023-11-24118

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.

Query — the check
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;
Result1 row · 4 columns
TOTAL_ORDERSROWS_WITH_A_PREVIOUSROWS_WITHOUTCUSTOMERS
413388

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.

A check worth reusing

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.

Query
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;
Result23 rows · 3 columns
MONTH_STARTTOTALPREV_MONTH
2023-01-015090.50NULL
2023-02-017650.005090.50
2023-03-017330.757650.00
2023-04-019010.007330.75
2023-05-013980.259010.00
2023-06-0110075.503980.25
2023-07-017170.0010075.50
2023-08-0112110.007170.00
2023-09-015540.0012110.00
2023-10-018445.005540.00
2023-11-0111380.008445.00
2023-12-018980.0011380.00
2024-01-0115110.008980.00
2024-02-018340.0015110.00
2024-03-012930.008340.00
2024-04-0112640.002930.00
2024-05-0116875.0012640.00
2024-06-0111660.0016875.00
2024-07-018820.0011660.00
2024-08-0115640.008820.00
2024-09-017010.0015640.00
2024-10-019640.007010.00
2024-11-01NULL9640.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.

Query — MINUS between the two versions
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);
Result0 rows · 2 columns
MONTH_STARTLAG(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.

The difference that survives this episode

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.

Query — are there any gaps?
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;
Result0 rows · 1 column
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

  • LAG reads a value from an earlier row in the window and LEAD from a later one. Both require an ORDER BY inside OVER, and both take PARTITION 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 n leaves n nulls 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 0 is 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 − 1 can produce the same column, but LAG is one function call instead of a second table reference plus date arithmetic.
  • LAG gives 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.
Next in this series

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.