Skip to content
SQLSimplified
window

Running Total With SUM() OVER

Build a cumulative salary total across employees ordered by hire date.

Overview

A running total accumulates a value as you move down the ordered window. Using SUM(salary) OVER (ORDER BY hire_date) with a frame that grows row by row gives the cumulative payroll to date — a classic finance/reporting pattern.

The Query

Employees & Departments

Loading database engine...

Step-by-Step Breakdown

  1. SUM(salary) OVER (ORDER BY hire_date) — by default the frame is ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, so it sums from the first row up to the current one.
  2. Each row's running_payroll includes all employees hired on or before that row's date.
  3. No PARTITION BY means the running total spans the whole table.

Frame matters

The default frame for ORDER BY windows accumulates to the current row. If you want a fixed window, specify ROWS BETWEEN … AND … explicitly.

Variations

Running total of units per customer over time:

Store (Customers/Orders/Products)

Loading database engine...

Common Mistakes

  • Forgetting ORDER BY. Without it, the frame is the whole partition and you get the grand total on every row, not a running sum.
  • Wrong PARTITION BY. Omitting PARTITION BY customer_id merges all customers into one running total.
  • Assuming reset per group. Without PARTITION BY, the total never resets between entities.

Search

Search lessons, functions, examples, and practice problems