Chapter 7 · Lesson 5 of 6

Looking Back with LAG

Compare each row with the previous one using LAG, such as showing each salesperson's prior sale amount next to the current sale.

LAG lets you reach into an earlier row in the same partition.

For example, you can show each salesperson's previous sale amount beside the current one:

SELECT salesperson, sale_date, amount,
       LAG(amount) OVER (
         PARTITION BY salesperson
         ORDER BY sale_date
       ) AS previous_amount
FROM sales_2

The first row in each salesperson's partition has no earlier row, so LAG returns NULL there.

The companion function is LEAD, which looks forward instead of backward. For example, LEAD(amount) OVER (...) can show the next sale amount beside the current sale.

This is useful for change-over-time questions like month-over-month growth, previous status, or the gap from the last event.

Sample data

This lesson loads the sales_2 table (16 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for sales_2
CREATE OR REPLACE TABLE sales_2 (
    id INTEGER,
    salesperson VARCHAR,
    region VARCHAR,
    amount DECIMAL(10,2),
    quantity INTEGER,
    sale_date DATE
  );

INSERT INTO sales_2 VALUES
    (1, 'Alice', 'West', 1200, 3, '2024-01-05'),
    (2, 'Bob', 'East', 850, 2, '2024-01-08'),
    (3, 'Alice', 'West', 640, 1, '2024-01-11'),
    (4, 'Diana', 'South', 430, 5, '2024-01-12'),
    (5, 'Eve', 'West', 1500, 4, '2024-02-01'),
    (6, 'Frank', 'East', 920, 2, '2024-02-03'),
    (7, 'Grace', 'North', 760, 2, '2024-02-07'),
    (8, 'Bob', 'East', 1100, 3, '2024-02-10'),
    (9, 'Alice', 'West', 780, 2, '2024-03-02'),
    (10, 'Bob', 'East', 990, 3, '2024-03-05'),
    (11, 'Diana', 'South', 610, 2, '2024-03-08'),
    (12, 'Eve', 'West', 700, 1, '2024-03-12'),
    (13, 'Frank', 'East', 1150, 4, '2024-03-15'),
    (14, 'Grace', 'North', 840, 2, '2024-03-18'),
    (15, 'Alice', 'West', 1320, 5, '2024-04-01'),
    (16, 'Bob', 'East', 730, 1, '2024-04-05');

Practice challenge

Show each sale together with the salesperson's previous sale amount. Return salesperson, sale_date, amount, and previous_amount, ordered by salesperson and sale_date.

Hint: Use LAG(amount) OVER (PARTITION BY salesperson ORDER BY sale_date).

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Window Functions

Calculate totals, running sums, rankings, and previous-row comparisons with OVER and PARTITION BY while keeping every detail row.

  1. 01 · OVER Keeps the Detail Rows
  2. 02 · PARTITION BY Creates Mini Windows
  3. 03 · Running Totals with ORDER BY
  4. 04 · Ranking Rows with ROW_NUMBER
  5. 05 · Looking Back with LAG
  6. 06 · Other Common Window Functions

Related guides