Chapter 7 · Lesson 1 of 6
OVER Keeps the Detail Rows
Use a window function with OVER () to show an aggregate like a grand total next to every detail row without collapsing the rows.
A window function calculates across a set of related rows without collapsing the result into one row per group.
That is the big difference from GROUP BY. GROUP BY shrinks many rows into fewer summary rows. A window function keeps every original row visible and adds extra information beside it.
For example, this query shows every sale and the grand total repeated next to each row:
SELECT id, salesperson, amount,
SUM(amount) OVER () AS grand_total
FROM sales_2OVER () means “use the whole result set as the window.” This is a great first example because it shows the basic idea clearly: same rows, extra context.
Sample data
This lesson loads the sales_2 table (16 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for sales_2
CREATE OR REPLACE TABLE sales_2 (
id INTEGER,
salesperson VARCHAR,
region VARCHAR,
amount DECIMAL(10,2),
quantity INTEGER,
sale_date DATE
);
INSERT INTO sales_2 VALUES
(1, 'Alice', 'West', 1200, 3, '2024-01-05'),
(2, 'Bob', 'East', 850, 2, '2024-01-08'),
(3, 'Alice', 'West', 640, 1, '2024-01-11'),
(4, 'Diana', 'South', 430, 5, '2024-01-12'),
(5, 'Eve', 'West', 1500, 4, '2024-02-01'),
(6, 'Frank', 'East', 920, 2, '2024-02-03'),
(7, 'Grace', 'North', 760, 2, '2024-02-07'),
(8, 'Bob', 'East', 1100, 3, '2024-02-10'),
(9, 'Alice', 'West', 780, 2, '2024-03-02'),
(10, 'Bob', 'East', 990, 3, '2024-03-05'),
(11, 'Diana', 'South', 610, 2, '2024-03-08'),
(12, 'Eve', 'West', 700, 1, '2024-03-12'),
(13, 'Frank', 'East', 1150, 4, '2024-03-15'),
(14, 'Grace', 'North', 840, 2, '2024-03-18'),
(15, 'Alice', 'West', 1320, 5, '2024-04-01'),
(16, 'Bob', 'East', 730, 1, '2024-04-05');Practice challenge
Show every sale with the full-company total beside it. Return id, salesperson, amount, and grand_total, ordered by id.
Hint: Use SUM(amount) OVER () AS grand_total, then ORDER BY id.
Run your query in the editor and the lesson checks the result automatically.
Lessons in Window Functions
Calculate totals, running sums, rankings, and previous-row comparisons with OVER and PARTITION BY while keeping every detail row.