Module 04 · Lesson 11 of 16Detailed study · about 24 min

LAG, LEAD and changes over time

LAG reads an earlier row and LEAD reads a later row within an ordered partition.

Understand the idea

Each row is a fictional sale event. Dates use one calendar and amounts use one currency. Tied dates, tied amounts, an unknown amount and a known zero make the edge cases visible. Every SQL block includes these rows.

Key ideas in simple English
ConceptWhat it means
LAGCompare with the preceding record.
LEADInspect the following record.
Boundary / NULLA missing neighbor and a neighbor with NULL are different cases.

A concrete example

Comparing customer B amounts 80, 20 and 0 reveals changes of -60 and -20 after the first row.

Remember: Define partition, ordering and NULL behavior before interpreting a change.

Explain it step by step · full theory

The seven input events

Each row is a fictional sale event. Dates use one calendar and amounts use one currency. Tied dates, tied amounts, an unknown amount and a known zero make the edge cases visible. Every SQL block includes these rows.

Sample inputs for this window lesson
EVENT_IDCUSTOMEREVENT_DATEAMOUNT
1A2025-01-01100
2A2025-01-0250
3A2025-01-0250
4A2025-01-05NULL
5B2025-01-0180
6B2025-01-0320
7B2025-01-040

What does LAG do?

LAG reads a value from an earlier row in the window order. With its usual offset of one, it reads the previous row. LEAD reads a later row instead. These functions let us compare related events without joining the table to itself.

Partition by customer to keep A’s neighbors separate from B’s. Order by date and ID so we know which event is previous when dates tie.

Walk through A’s previous amounts

The first A event has no previous event, so its previous amount is NULL by default. Event 2 sees 100, event 3 sees 50 and event 4 sees 50.

amount - LAG(amount) is therefore NULL, -50, 0 and NULL. The last difference is unknown because the current amount is unknown. It is not a drop of 50.

No previous row versus a previous NULL

An absent neighbor and a neighbor whose value is NULL can both produce NULL. An optional default addresses an out-of-range offset; it should not be described as a universal replacement for all missing input values.

RESPECT NULLS is the default behavior. IGNORE NULLS skips NULL-valued expressions when locating the offset. That can be useful, but it changes “previous record” to “previous qualifying value.” Explain the change explicitly.

Record order is not calendar regularity

Our customer A has two events on January 2 and then an event on January 5. LAG does not promise a comparison with yesterday. It follows the defined records, including same-day records and gaps.

If the requirement is daily growth, first establish one row per relevant date and a missing-day policy. A percentage change also needs a policy for zero or missing prior values; dividing by a protected denominator should not hide an undefined metric.

Words used in this lesson
LAG
Reads a value from an earlier ordered record.
LEAD
Reads a value from a later ordered record.
Offset
How many qualifying positions away to read.

See how it works

Choose a step to explore the idea at your own pace.

Open the interactive explanation
Interactive explainer1 / 4

LAG, LEAD and changes over time

Event 1
No previous event
Previous amount: NULL

First

The first record has no earlier record in its partition.

Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.

Read the complete diagram explanation
  1. First

    The first record has no earlier record in its partition.

  2. Next

    Event 2 reads event 1’s 100 and compares it with its own 50.

  3. Tie day

    Event ID places event 3 after event 2, although their dates match.

  4. Unknown current

    Event 4 has a known previous 50 but an unknown current amount.

Try the SQL or command

Read → predict → run in your learning environment → compare. You can also learn by reading without an account.

New to SQL? Where to run it and how to read it

A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.

  1. No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
  2. For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
  3. Read the entire example, including comments beginning with --. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor.
  4. Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
SELECT / FROM
Choose the values to return / identify their input.
VALUES / COLUMN1
VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
AS / WITH
AS gives a result a readable name. WITH names a temporary query step within one statement.
NULL / ::
NULL means missing or unknown. The :: notation converts a value to a named data type.
Session
One connection and its settings. Keep related transaction steps in the same session.
Database.schema.table
A full address for stored data. It is separate from the warehouse that processes queries.

Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →

Help with common practice errors
  • No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
  • Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
  • Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
  • Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.

Before running this lesson

Seven fictional events are included in each SQL block below. Run each block independently in an authorized learning session with a warehouse; no stored SALES table is required. Results are illustrative.

Compare with the previous event

SQL · example
WITH sales AS (
 SELECT column1::NUMBER AS event_id,
        column2::VARCHAR AS customer,
        TO_DATE(column3::VARCHAR, 'YYYY-MM-DD') AS event_date,
        column4::NUMBER(12,2) AS amount
 FROM VALUES
  (1, 'A', '2025-01-01', 100),
  (2, 'A', '2025-01-02', 50),
  (3, 'A', '2025-01-02', 50),
  (4, 'A', '2025-01-05', NULL),
  (5, 'B', '2025-01-01', 80),
  (6, 'B', '2025-01-03', 20),
  (7, 'B', '2025-01-04', 0)
)
SELECT event_id, customer, amount,
 LAG(amount) OVER (PARTITION BY customer ORDER BY event_date, event_id) AS previous_amount,
 amount - LAG(amount) OVER (PARTITION BY customer ORDER BY event_date, event_id) AS amount_change
FROM sales
ORDER BY customer, event_date, event_id;

What to expect and why

The first row of each customer has no previous value. Differences are meaningful only where current and previous values are known.

Expected result for the supplied input (not live output)
EVENT_IDCUSTOMERAMOUNTPREVIOUS_AMOUNTAMOUNT_CHANGE
1A100NULLNULL
2A50100-50
3A50500
4ANULL50NULL
5B80NULLNULL
6B2080-60
7B020-20

Look forward and decide whether to skip NULL

SQL · example
WITH sales AS (
 SELECT column1::NUMBER AS event_id,
        column2::VARCHAR AS customer,
        TO_DATE(column3::VARCHAR, 'YYYY-MM-DD') AS event_date,
        column4::NUMBER(12,2) AS amount
 FROM VALUES
  (1, 'A', '2025-01-01', 100),
  (2, 'A', '2025-01-02', 50),
  (3, 'A', '2025-01-02', 50),
  (4, 'A', '2025-01-05', NULL),
  (5, 'B', '2025-01-01', 80),
  (6, 'B', '2025-01-03', 20),
  (7, 'B', '2025-01-04', 0)
)
SELECT event_id,
 LEAD(amount) OVER (ORDER BY event_date DESC, event_id DESC) AS next_value,
 LEAD(amount) IGNORE NULLS OVER (ORDER BY event_date DESC, event_id DESC) AS next_known
FROM sales
WHERE customer = 'A'
ORDER BY event_date DESC, event_id DESC;

What to expect and why

This descending example reads toward older events. The next values are 50, 50, 100 and no value. Both expressions match here because the only NULL is the starting record, not a later neighbor. IGNORE NULLS does not replace the current record.

Expected result for the supplied input (not live output)
EVENT_IDNEXT_VALUENEXT_KNOWN
45050
35050
2100100
1NULLNULL

Check your understanding

Choose an answer, then check your reasoning. This is practice, not a scored test.

Does LAG always read yesterday’s value?

Try it yourself

Why is A’s final amount change NULL rather than -50?

Compare your reasoning

The current amount is unknown. Subtracting the previous known 50 from an unknown value does not establish a numeric difference.

Official sources and curriculum

Module 04 · See module scope