โ†•๏ธ LEAD & LAG #2

LAG and LEAD let each row read a value from the row before it or the row after it. They are the standard tools for questions like "how much did revenue change since yesterday?" or "how many days passed between a customer's orders?".

This is the second tutorial on windows. If OVER (PARTITION BY ... ORDER BY ...) is new to you, read Window Functions first.


1. Sample Data

This tutorial uses two small tables. daily_sales holds four days of revenue for two stores. One value is NULL: store S2 did not report revenue on March 3rd.

CREATE OR REPLACE TEMP VIEW daily_sales AS
SELECT * FROM VALUES
  ('S1', DATE'2024-03-01', 100),
  ('S1', DATE'2024-03-02', 120),
  ('S1', DATE'2024-03-03', 90),
  ('S1', DATE'2024-03-04', 150),
  ('S2', DATE'2024-03-01', 200),
  ('S2', DATE'2024-03-02', 180),
  ('S2', DATE'2024-03-03', NULL),
  ('S2', DATE'2024-03-04', 210)
AS daily_sales(store, sale_date, revenue)

orders holds a few orders from three customers:

CREATE OR REPLACE TEMP VIEW orders AS
SELECT * FROM VALUES
  (101, 'Asha', DATE'2024-01-05', 250),
  (102, 'Ben',  DATE'2024-01-07', 120),
  (103, 'Asha', DATE'2024-01-20', 80),
  (104, 'Chen', DATE'2024-02-02', 300),
  (105, 'Asha', DATE'2024-02-14', 60),
  (106, 'Ben',  DATE'2024-03-01', 90)
AS orders(order_id, customer, order_date, amount)

2. Looking at the Previous and Next Row

LAG(revenue) returns revenue from the previous row; LEAD(revenue) returns it from the next row. "Previous" and "next" are defined by the ORDER BY inside OVER, and PARTITION BY store keeps each store separate:

SELECT store,
       sale_date,
       revenue,
       LAG(revenue)  OVER (PARTITION BY store ORDER BY sale_date) AS prev_revenue,
       LEAD(revenue) OVER (PARTITION BY store ORDER BY sale_date) AS next_revenue
FROM daily_sales
ORDER BY store, sale_date
+-----+----------+-------+------------+------------+
|store|sale_date |revenue|prev_revenue|next_revenue|
+-----+----------+-------+------------+------------+
|S1   |2024-03-01|100    |NULL        |120         |
|S1   |2024-03-02|120    |100         |90          |
|S1   |2024-03-03|90     |120         |150         |
|S1   |2024-03-04|150    |90          |NULL        |
|S2   |2024-03-01|200    |NULL        |180         |
|S2   |2024-03-02|180    |200         |NULL        |
|S2   |2024-03-03|NULL   |180         |210         |
|S2   |2024-03-04|210    |NULL        |NULL        |
+-----+----------+-------+------------+------------+

Two things to notice:

  • The first row of each store has no previous row, so prev_revenue is NULL. The last row has no next row, so next_revenue is NULL.
  • Store S2 on March 2nd gets NULL as next_revenue because the next row's revenue really is NULL.

LAG and LEAD always need an ORDER BY in the window. Without an order, "previous row" has no meaning.


3. The Full Syntax: Offset and Default

Both functions take up to three arguments:

-- Syntax
LAG(column, offset, default)  OVER (PARTITION BY ... ORDER BY ...)
LEAD(column, offset, default) OVER (PARTITION BY ... ORDER BY ...)
ArgumentMeaningIf you leave it out
columnThe value to read(required)
offsetHow many rows back (LAG) or ahead (LEAD)1
defaultReturned when that row does not existNULL

Here LAG(revenue, 2) reads two days back, and LAG(revenue, 1, 0) returns 0 instead of NULL on the first day:

SELECT store,
       sale_date,
       revenue,
       LAG(revenue, 2)    OVER (PARTITION BY store ORDER BY sale_date) AS two_days_ago,
       LAG(revenue, 1, 0) OVER (PARTITION BY store ORDER BY sale_date) AS prev_or_zero
FROM daily_sales
ORDER BY store, sale_date
+-----+----------+-------+------------+------------+
|store|sale_date |revenue|two_days_ago|prev_or_zero|
+-----+----------+-------+------------+------------+
|S1   |2024-03-01|100    |NULL        |0           |
|S1   |2024-03-02|120    |NULL        |100         |
|S1   |2024-03-03|90     |100         |120         |
|S1   |2024-03-04|150    |120         |90          |
|S2   |2024-03-01|200    |NULL        |0           |
|S2   |2024-03-02|180    |NULL        |200         |
|S2   |2024-03-03|NULL   |200         |180         |
|S2   |2024-03-04|210    |180         |NULL        |
+-----+----------+-------+------------+------------+

Look closely at S2 on March 4th: prev_or_zero is NULL, not 0.

Common mistake: The default is only used when the row at that offset does not exist. If the row exists but its value is NULL, you get NULL. S2's March 4th row has a previous row (March 3rd); its revenue just happens to be NULL. To replace NULL values too, wrap the result: COALESCE(LAG(revenue) OVER (...), 0).


4. Day-over-Day Change

The most common use of LAG is comparing a row with the one before it. Subtract the previous value for the change, and divide by it for the percent change:

SELECT store,
       sale_date,
       revenue,
       revenue - LAG(revenue) OVER (PARTITION BY store ORDER BY sale_date) AS change,
       ROUND(100.0 * (revenue - LAG(revenue) OVER (PARTITION BY store ORDER BY sale_date))
             / LAG(revenue) OVER (PARTITION BY store ORDER BY sale_date), 1) AS pct_change
FROM daily_sales
ORDER BY store, sale_date
+-----+----------+-------+------+----------+
|store|sale_date |revenue|change|pct_change|
+-----+----------+-------+------+----------+
|S1   |2024-03-01|100    |NULL  |NULL      |
|S1   |2024-03-02|120    |20    |20.0      |
|S1   |2024-03-03|90     |-30   |-25.0     |
|S1   |2024-03-04|150    |60    |66.7      |
|S2   |2024-03-01|200    |NULL  |NULL      |
|S2   |2024-03-02|180    |-20   |-10.0     |
|S2   |2024-03-03|NULL   |NULL  |NULL      |
|S2   |2024-03-04|210    |NULL  |NULL      |
+-----+----------+-------+------+----------+

S1 went from 100 to 120 on March 2nd (+20, or +20.0%), then dropped to 90 (-30, or -25.0%). Any calculation with a NULL gives NULL, so the first day of each store, and both S2 days next to the missing value, have no change.

Writing the same OVER (...) three times is noisy. A WINDOW clause names it once:

SELECT store,
       sale_date,
       revenue,
       revenue - LAG(revenue) OVER w AS change
FROM daily_sales
WINDOW w AS (PARTITION BY store ORDER BY sale_date)
ORDER BY store, sale_date
+-----+----------+-------+------+
|store|sale_date |revenue|change|
+-----+----------+-------+------+
|S1   |2024-03-01|100    |NULL  |
|S1   |2024-03-02|120    |20    |
|S1   |2024-03-03|90     |-30   |
|S1   |2024-03-04|150    |60    |
|S2   |2024-03-01|200    |NULL  |
|S2   |2024-03-02|180    |-20   |
|S2   |2024-03-03|NULL   |NULL  |
|S2   |2024-03-04|210    |NULL  |
+-----+----------+-------+------+

5. Skipping NULLs with IGNORE NULLS

Sometimes you want "the last value that is not NULL". Add IGNORE NULLS after the function call, and LAG skips over NULL values until it finds one:

SELECT store,
       sale_date,
       revenue,
       LAG(revenue) OVER (PARTITION BY store ORDER BY sale_date) AS prev_revenue,
       LAG(revenue) IGNORE NULLS OVER (PARTITION BY store ORDER BY sale_date) AS prev_known_revenue
FROM daily_sales
WHERE store = 'S2'
ORDER BY sale_date
+-----+----------+-------+------------+------------------+
|store|sale_date |revenue|prev_revenue|prev_known_revenue|
+-----+----------+-------+------------+------------------+
|S2   |2024-03-01|200    |NULL        |NULL              |
|S2   |2024-03-02|180    |200         |200               |
|S2   |2024-03-03|NULL   |180         |180               |
|S2   |2024-03-04|210    |NULL        |180               |
+-----+----------+-------+------------+------------------+

On March 4th, the previous row (March 3rd) is NULL, so plain LAG returns NULL. With IGNORE NULLS, Spark keeps looking back and finds 180 from March 2nd. This is handy for comparing against the last reported value when some days are missing.


6. Gaps Between Events

LAG also works on dates. Combined with datediff, it tells you how long a customer waited between orders. Note that datediff(end, start) takes the later date first:

SELECT customer,
       order_id,
       order_date,
       LAG(order_date) OVER (PARTITION BY customer ORDER BY order_date) AS prev_order_date,
       datediff(order_date,
                LAG(order_date) OVER (PARTITION BY customer ORDER BY order_date)) AS days_since_prev
FROM orders
ORDER BY customer, order_date
+--------+--------+----------+---------------+---------------+
|customer|order_id|order_date|prev_order_date|days_since_prev|
+--------+--------+----------+---------------+---------------+
|Asha    |101     |2024-01-05|NULL           |NULL           |
|Asha    |103     |2024-01-20|2024-01-05     |15             |
|Asha    |105     |2024-02-14|2024-01-20     |25             |
|Ben     |102     |2024-01-07|NULL           |NULL           |
|Ben     |106     |2024-03-01|2024-01-07     |54             |
|Chen    |104     |2024-02-02|NULL           |NULL           |
+--------+--------+----------+---------------+---------------+

Asha ordered again after 15 days, then after 25 days. Chen has only one order, so there is no previous order and days_since_prev is NULL.

To find repeat orders placed within 20 days, compute the gap in a CTE and filter outside it. You cannot use a window function in WHERE directly:

WITH gaps AS (
  SELECT customer,
         order_id,
         order_date,
         datediff(order_date,
                  LAG(order_date) OVER (PARTITION BY customer ORDER BY order_date)) AS days_since_prev
  FROM orders
)
SELECT customer, order_id, order_date, days_since_prev
FROM gaps
WHERE days_since_prev <= 20
ORDER BY customer, order_date
+--------+--------+----------+---------------+
|customer|order_id|order_date|days_since_prev|
+--------+--------+----------+---------------+
|Asha    |103     |2024-01-20|15             |
+--------+--------+----------+---------------+

LEAD answers the opposite question, "when did they order next?". Each customer's latest order has no next order, so it gets NULL:

SELECT customer,
       order_date,
       LEAD(order_date) OVER (PARTITION BY customer ORDER BY order_date) AS next_order_date
FROM orders
ORDER BY customer, order_date
+--------+----------+---------------+
|customer|order_date|next_order_date|
+--------+----------+---------------+
|Asha    |2024-01-05|2024-01-20     |
|Asha    |2024-01-20|2024-02-14     |
|Asha    |2024-02-14|NULL           |
|Ben     |2024-01-07|2024-03-01     |
|Ben     |2024-03-01|NULL           |
|Chen    |2024-02-02|NULL           |
+--------+----------+---------------+

Note: LAG and LEAD count rows, not calendar days. If a date is missing from the data, LAG simply returns the last date that exists. To compare with "exactly yesterday", join the table to itself on date_sub(sale_date, 1) instead.


7. First Value in the Partition

LAG looks one row back. To compare every row with the first row of its partition, such as each order against the customer's first order, use FIRST_VALUE:

SELECT customer,
       order_date,
       amount,
       FIRST_VALUE(order_date) OVER (PARTITION BY customer ORDER BY order_date) AS first_order_date,
       FIRST_VALUE(amount)     OVER (PARTITION BY customer ORDER BY order_date) AS first_order_amount
FROM orders
ORDER BY customer, order_date
+--------+----------+------+----------------+------------------+
|customer|order_date|amount|first_order_date|first_order_amount|
+--------+----------+------+----------------+------------------+
|Asha    |2024-01-05|250   |2024-01-05      |250               |
|Asha    |2024-01-20|80    |2024-01-05      |250               |
|Asha    |2024-02-14|60    |2024-01-05      |250               |
|Ben     |2024-01-07|120   |2024-01-07      |120               |
|Ben     |2024-03-01|90    |2024-01-07      |120               |
|Chen    |2024-02-02|300   |2024-02-02      |300               |
+--------+----------+------+----------------+------------------+

LAST_VALUE looks like the mirror image, but with an ORDER BY it does not return the last row of the partition by default. It returns the current row's value. The reason is the window frame, explained in the next tutorial, Window Frames.


8. Common Mistakes

Forgetting PARTITION BY. Without it, the whole table is one sequence, so values leak from one group into the next. Here, S2's first day picks up S1's last revenue:

SELECT store,
       sale_date,
       revenue,
       LAG(revenue) OVER (ORDER BY store, sale_date) AS prev_revenue
FROM daily_sales
ORDER BY store, sale_date
+-----+----------+-------+------------+
|store|sale_date |revenue|prev_revenue|
+-----+----------+-------+------------+
|S1   |2024-03-01|100    |NULL        |
|S1   |2024-03-02|120    |100         |
|S1   |2024-03-03|90     |120         |
|S1   |2024-03-04|150    |90          |
|S2   |2024-03-01|200    |150         |
|S2   |2024-03-02|180    |200         |
|S2   |2024-03-03|NULL   |180         |
|S2   |2024-03-04|210    |NULL        |
+-----+----------+-------+------------+

S2 on March 1st shows 150 as its previous revenue, which is S1's March 4th value. The number looks reasonable, which is what makes this bug easy to miss.

Adding a frame. LAG and LEAD always read a fixed number of rows away, so they do not accept a ROWS BETWEEN frame:

SELECT store,
       sale_date,
       LAG(revenue) OVER (PARTITION BY store ORDER BY sale_date
                          ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS prev_revenue
FROM daily_sales
Cannot specify window frame for lag function.

Ties in the ORDER BY. If two rows in the same partition have the same order value, Spark does not promise which one comes first, so LAG may return a different row from run to run. Add a second column to the ORDER BY, such as an id, to make it predictable.


9. Try It in the Online Compiler

Copy this into the PySpark Online Compiler. Each spark.sql() call holds one statement:

from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("Spark SQL LEAD and LAG").getOrCreate()

spark.sql("""
CREATE OR REPLACE TEMP VIEW daily_sales AS
SELECT * FROM VALUES
  ('S1', DATE'2024-03-01', 100),
  ('S1', DATE'2024-03-02', 120),
  ('S1', DATE'2024-03-03', 90),
  ('S1', DATE'2024-03-04', 150),
  ('S2', DATE'2024-03-01', 200),
  ('S2', DATE'2024-03-02', 180),
  ('S2', DATE'2024-03-03', NULL),
  ('S2', DATE'2024-03-04', 210)
AS daily_sales(store, sale_date, revenue)
""")

# Day-over-day change per store
spark.sql("""
SELECT store, sale_date, revenue,
       LAG(revenue) OVER w AS prev_revenue,
       revenue - LAG(revenue) OVER w AS change
FROM daily_sales
WINDOW w AS (PARTITION BY store ORDER BY sale_date)
ORDER BY store, sale_date
""").show(truncate=False)

# Compare with the last known value, skipping NULLs
spark.sql("""
SELECT store, sale_date, revenue,
       LAG(revenue) IGNORE NULLS OVER (PARTITION BY store ORDER BY sale_date) AS prev_known_revenue
FROM daily_sales
ORDER BY store, sale_date
""").show(truncate=False)

Summary

  • LAG(col) reads the previous row's value and LEAD(col) reads the next row's, in the order set by the window's ORDER BY.
  • LAG(col, offset, default): offset sets how many rows away, default replaces NULL only when that row does not exist.
  • LAG(col) IGNORE NULLS skips NULL values and returns the last known value.
  • value - LAG(value) OVER (...) gives the change from the previous row; datediff(date, LAG(date) OVER (...)) gives the gap between events.
  • FIRST_VALUE compares each row with the first row of its partition.
  • Always PARTITION BY the entity (store, customer), or values leak between groups.

Next, you will learn window frames (ROWS and RANGE) for running totals and moving averages.