TECHNOLOGIESTieInn Technologies

Running totals, LAG, and LEAD

SQL · 15 questions

Short notes

Key idea

Window functions can also look at earlier or later rows: a running total adds up as you go, LAG peeks at the previous row and LEAD at the next one. Use them for growth, change and gaps.

Syntax

SUM(amount) OVER (ORDER BY order_date)                 -- running total
SUM(amount) OVER (PARTITION BY city ORDER BY order_date)
AVG(amount) OVER (ORDER BY d ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)  -- 7-row moving average
LAG(revenue, 1)  OVER (ORDER BY month)
LEAD(revenue, 1) OVER (ORDER BY month)

Example

Month-on-month change in revenue:

SELECT month, revenue,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM monthly_revenue;

The first month has no previous row, so its change is NULL.

Traps

  • Ties in the ORDER BY make the default running total jump: rows with the same date are added together. Add ROWS UNBOUNDED PRECEDING or a tiebreaker.
  • LAG gives NULL on the first row; pass a default: LAG(x, 1, 0).
  • Percent change: divide by the previous value, not the current one.

Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Running totals, LAG, and LEAD

  1. Question 1easy

    What does LAG(orders) OVER (ORDER BY month) return for the earliest month?

  2. Running totals, LAG, and LEAD

  3. Question 2medium

    What does SUM(amount) OVER (PARTITION BY customer_id) return on each row?

  4. Running totals, LAG, and LEAD

  5. Question 3medium

    7 orders were placed in January 2023. What does this return?

    WITH daily AS (
      SELECT order_date, COUNT(*) AS n
      FROM orders
      WHERE order_date < '2023-02-01'
      GROUP BY order_date
    )
    SELECT MAX(running) FROM (
      SELECT SUM(n) OVER (ORDER BY order_date) AS running FROM daily
    );
  6. Running totals, LAG, and LEAD

  7. Question 4medium

    31 different customers placed orders. What does this return?

    SELECT COUNT(*) FROM (
      SELECT LAG(order_date) OVER (
               PARTITION BY customer_id ORDER BY order_date, order_id
             ) AS prev
      FROM orders
    )
    WHERE prev IS NULL;
  8. Running totals, LAG, and LEAD

  9. Question 5hard

    Order 21 (₹1,647) was placed on 31 May 2023. Orders 22 (₹9,808.30) and 23 (₹17,494.99) were both placed on 1 June 2023. What is running for order 22?

    SELECT running FROM (
      SELECT order_id,
             SUM(amount) OVER (ORDER BY order_date) AS running
      FROM orders
      WHERE order_date BETWEEN '2023-05-25' AND '2023-06-05'
    )
    WHERE order_id = 22;

10 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.