SQL LESSON 23 OF 32

Running totals & LAG

A running sum uses SUM(...) OVER an ordered window. Specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for row-by-row accumulation. LAG reads a prior row, useful for comparing consecutive values.

हिन्दी में समझें

रनिंग टोटल क्रम वाली विंडो पर SUM से मिलता है। ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW स्पष्ट सीमा है। LAG पिछली पंक्ति पढ़ता है।

अभ्यास: id, price और id क्रम में LAG(price) AS previous_price दिखाएँ।

Hinglish mein samjhein

Running total ordered window par SUM se banta hai. ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW clear frame hai. LAG previous row padhta hai.

Practice: id,price aur LAG(price) AS previous_price id order mein dikhao.

A small SQL example

SELECT id,name,price,SUM(price) OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total FROM products ORDER BY id;

Examples use the fictional shop database bundled with the SQL playground: customers, products, orders, order_items and employees. The engine is SQLite; other SQL dialects may differ.

Try this example in the SQL playground →

Practise this idea

Show id, price and previous_price using LAG(price) ordered by id; final order by id.

Check answer & explanation
SELECT id,price,LAG(price) OVER(ORDER BY id) AS previous_price FROM products ORDER BY id;

LAG looks at the prior row in id order. The first product has no previous row, so its previous_price is NULL.

Stuck in the course? Choose Check answer for either the challenge or quiz. Read the explanation and continue to the next lesson at your own pace.

Check your understanding

LAG reads…

  1. A prior row
  2. Only the current row
  3. The database password
Check the quiz answer

A prior row

A running sum uses SUM(...) OVER an ordered window. Specify ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW for row-by-row accumulation. LAG reads a prior row, useful for comparing consecutive values.

References & corrections

Use the official SQLite documentation for full language rules. Read how these lessons are made and checked. Found a mistake? Report it to Excel Keys with this lesson URL and a reproducible example.

FROM LEARNING TO BUSINESS RESULTS

Need a dashboard for your team?

Excel Keys designs custom Excel and HTML dashboards around your own KPIs and Excel files. They run offline in the browser, so your data stays on your computer.