Running Total In Sql Using Window Function

6 min read

A running total in SQL using window function syntax represents one of the most powerful analytical tools available to data professionals today. Unlike traditional aggregate functions that collapse rows into a single summary line, window functions perform calculations across a set of table rows related to the current row while preserving the individual row details. This capability allows analysts to calculate cumulative sums, moving averages, and ranking metrics without resorting to complex self-joins or correlated subqueries that degrade performance on large datasets. Mastering this technique transforms how you approach time-series analysis, financial reporting, and inventory tracking, turning multi-step procedural logic into a single, declarative, and highly optimized query Not complicated — just consistent..

Understanding the Core Concept: Frames and Partitions

Before writing the syntax, Understand the mechanics driving the calculation — this one isn't optional. Plus, a window function operates on a window frame—a specific subset of rows defined relative to the current row. This frame is constructed using three key clauses: PARTITION BY, ORDER BY, and the frame specification (ROWS or RANGE).

The PARTITION BY clause divides the result set into distinct groups, such as by customer_id, region, or product_category. That's why the running total resets to zero whenever the partition changes. The ORDER BY clause defines the logical sequence of rows within each partition, typically a date or timestamp column. Without ordering, the concept of a "running" total is meaningless because there is no defined sequence.

The frame clause is where the magic happens. This leads to the default frame for an ORDER BY clause is RANGE UNBOUNDED PRECEDING AND CURRENT ROW. This means: "Start at the first row of the partition and end at the current row." Understanding the difference between ROWS and RANGE is critical for accuracy, especially when dealing with duplicate values in the ordering column.

The Standard Syntax Pattern

The generic template for a running total using the SUM() window function looks like this:

SELECT 
    column_list,
    SUM(numeric_column) OVER (
        PARTITION BY partition_column
        ORDER BY order_column
        ROWS UNBOUNDED PRECEDING
    ) AS running_total
FROM table_name;

Let’s break down the frame clause ROWS UNBOUNDED PRECEDING.

  • ROWS: Indicates the frame is defined by physical row offsets.
  • UNBOUNDED PRECEDING: The frame starts at the first row of the partition. And * (Implicit CURRENT ROW): Since no BETWEEN ... AND ... is specified, the default upper bound is the current row.

Using ROWS instead of the default RANGE is widely considered a best practice for running totals. RANGE treats rows with identical ORDER BY values as peers, summing all of them simultaneously for every row in that peer group. ROWS calculates the sum strictly based on physical position, providing a distinct cumulative step for every single row, which usually aligns better with business expectations for ledger-style reports The details matter here. And it works..

Practical Example: Sales Ledger Analysis

Imagine a table named daily_sales tracking revenue per store per day.

sale_date store_id revenue
2023-01-01 A 100
2023-01-02 A 150
2023-01-03 A 200
2023-01-01 B 50
2023-01-02 B 75

To generate a report showing the cumulative revenue for each store over time, the query would be:

SELECT 
    sale_date,
    store_id,
    revenue,
    SUM(revenue) OVER (
        PARTITION BY store_id 
        ORDER BY sale_date
        ROWS UNBOUNDED PRECEDING
    ) AS cumulative_revenue
FROM daily_sales
ORDER BY store_id, sale_date;

The output preserves the granular daily rows while adding the calculated context:

sale_date store_id revenue cumulative_revenue
2023-01-01 A 100 100
2023-01-02 A 150 250
2023-01-03 A 200 450
2023-01-01 B 50 50
2023-01-02 B 75 125

This changes depending on context. Keep that in mind.

Notice how the cumulative_revenue resets when store_id changes from A to B. Even so, this is the direct result of the PARTITION BY store_id clause. If you omitted the partition, the calculation would run across the entire table, mixing stores together—a common error for beginners Worth knowing..

Advanced Framing: Rows vs. Range Deep Dive

The distinction between ROWS and RANGE becomes critical when your ordering column contains duplicates. Consider a scenario where a store records two transactions on the same day That's the part that actually makes a difference..

sale_date store_id revenue
2023-01-01 A 100
2023-01-01 A 50
2023-01-02 A 200

Using RANGE UNBOUNDED PRECEDING (Default): The database sees the two rows for 2023-01-01 as peers. It calculates the sum for the peer group (150) and assigns that same value to both rows.

  • Row 1: 150
  • Row 2: 150
  • Row 3: 350

Using ROWS UNBOUNDED PRECEDING: The database treats them as distinct physical rows (Row 1, Row 2) That's the part that actually makes a difference..

  • Row 1: 100
  • Row 2: 150
  • Row 3: 350

For financial auditing or inventory tracking where every transaction increments the balance, ROWS is almost always the correct choice. RANGE is better suited for analytical smoothing where you want the "value as of this date" regardless of transaction volume on that specific date Which is the point..

Performance Implications and Optimization

Window functions are generally highly optimized in modern relational databases (PostgreSQL, SQL Server, Oracle, Snowflake, BigQuery). They typically require a single pass over the data (or a sort operation) rather than the quadratic complexity of a correlated subquery:

-- INEFFICIENT CORRELATED SUBQUERY (Avoid this pattern)
SELECT 
    t1.sale_date, 
    t1.store_id, 
    t1.revenue,
    (SELECT SUM(t2.revenue) 
     FROM daily_sales t2 
     WHERE t2.store_id = t1.store_id 
     AND t2.sale_date <= t1.sale_date) AS running_total
FROM daily_sales t1;

The window function version allows the query optimizer to use a Window Spool or Sort + Stream Aggregate operation. To maximize performance: 1 That's the whole idea..

To maximize performance, follow these guidelines:

  1. Order the input correctly – make sure the base table (daily_sales) is sorted by sale_date and then by store_id. Most modern engines can stream the rows in a single pass, which avoids the costly re‑ordering that a correlated subquery would trigger Small thing, real impact. Less friction, more output..

  2. Create a covering index that matches the partition key and the columns used in the window frame. For this case an index on (sale_date, store_id, revenue) gives both fast lookups and efficient computation of the running total per store.

    CREATE INDEX idx_daily_sales_ts_store ON daily_sales (sale_date, store_id, revenue);
    
  3. Use the window frame explicitly – the most common mistake is mixing ROWS and RANGE. Since each record represents a distinct transaction, ROWS UNBOUNDED PRECEDING guarantees that every row contributes its own value, producing a true cumulative balance. If you need “value as of the day” regardless of how many transactions occurred, switch to RANGE UNBOUNDED PRECEDING TO CURRENT ROW and adjust the logic accordingly The details matter here..

New Releases

Hot Topics

Others Explored

One More Before You Go

Thank you for reading about Running Total In Sql Using Window Function. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home