SUM() OVER()
beginnerwindow-functions
2 min read
What is SUM() OVER()?
SUM() OVER() is a window function that calculates a sum across a set of rows without collapsing the result. It lets you see individual row values alongside cumulative or partitioned totals.
Syntax
-- Total sum across all rows
SELECT col, SUM(col) OVER () AS total_sum FROM table_name;
-- Running total
SELECT col, SUM(col) OVER (ORDER BY date_col) AS running_total FROM table_name;
-- Sum per partition
SELECT col, SUM(col) OVER (PARTITION BY group_col) AS group_sum FROM table_name;When to Use
- Showing each row with its percentage of the total
- Computing running totals (cumulative sums)
- Comparing individual values to group totals
Key Points
- Empty OVER() — SUM() OVER() computes the total across all rows, repeated on every row.
- Running Total — SUM() OVER(ORDER BY col) computes a cumulative sum.
- Partitioned Sum — SUM() OVER(PARTITION BY col) computes a sum per group.
- Percentage — Compute percentage: col / SUM(col) OVER() * 100.
- No Collapsing — Unlike GROUP BY, every row remains visible.
Guided Practice
Solve the challenge below. Use hints when stuck and check your answer for instant feedback.
Practice challengeGuided learning mode
SUM() OVER() Challenge
Write a query that solve this task: show each order with a cumulative total.
Expected result
Each order with a running total of amounts.
Hidden checks
- Returned rows and values
- Output columns and result shape
- Final database state after the query runs
Lesson guidance
What is SUM() OVER()?
Initializing database...Each run starts from fresh sample data.
More Examples
Each row as a percentage of total
Show each product price as a percentage of the total.
Initializing database...Each run starts from fresh sample data.
Sum per category
Show each product with the total price for its category.
Initializing database...Each run starts from fresh sample data.
Frequently Asked Questions
What is the difference between SUM() and SUM() OVER()?
SUM() is an aggregate that collapses rows. SUM() OVER() is a window function that keeps all rows and adds the sum as an extra column.
Why is my running total including all rows?
If you omit ORDER BY in OVER(), the sum includes all rows. Add ORDER BY to get a cumulative sum.