LESSON 10 / 24·2 min readIntermediate

What are LAG, LEAD and running totals?

01 Understand02 Recall03 Prepare

Understand the concept

LAG and LEAD read values from earlier or later rows within an ordered window. A running total uses an aggregate window that expands through the current row. These calculations support trends, comparisons and cumulative reports while preserving detail records.

Important ideas

  • LAG reads a previous row's value; LEAD reads a later row's value.

  • A running total adds values from the start through the current row.

  • Use a stable order and an explicit window frame when row-by-row totals matter.

  • An explicit ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW frame gives a row-by-row running total; stable ordering resolves ties.

Work through the example

SQL
SELECT id, customer_id, amount,
       SUM(amount) OVER (
         PARTITION BY customer_id
         ORDER BY created_at, id
         ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
       ) AS running_total
FROM orders
ORDER BY customer_id, created_at, id;
  • Each customer has a separate running total; id breaks timestamp ties.
PAUSE & RECALL

Can you explain it without the notes?

What are LAG, LEAD and running totals?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

LAG and LEAD read values from earlier or later rows within an ordered window. A running total uses an aggregate window that expands through the current row. These calculations support trends, comparisons and cumulative reports while preserving detail records.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Explain both the partition boundary and ordering, because “previous” has no meaning without them.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: What are primary keys, foreign keys and constraints?

Adapted from 05_SQL_POSTGRESQL.md · “What are LAG, LEAD and running totals?”. Examples are study fragments; framework behavior can depend on your version.