Chapter 7 · Lesson 2 of 6

PARTITION BY Creates Mini Windows

Split a window into groups with PARTITION BY to show each sale beside its regional total while keeping every row in the result.

PARTITION BY splits the result set into smaller windows before the function runs.

If you want each sale to carry its region total, you do not want one giant company-wide window anymore. You want one window per region:

SELECT id, region, amount,
       SUM(amount) OVER (PARTITION BY region) AS region_total
FROM sales_2

Now every East row gets the East total, every West row gets the West total, and so on.

This is one of the most useful patterns in SQL because it lets you compare a row to its group without losing row-level detail.

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 each sale with its regional total. Return id, region, amount, and region_total, ordered by id.

Hint: Use SUM(amount) OVER (PARTITION BY region) AS region_total.

Run your query in the editor and the lesson checks the result automatically.

Open this lesson in the SQL editor

Lessons in Window Functions

Calculate totals, running sums, rankings, and previous-row comparisons with OVER and PARTITION BY while keeping every detail row.

  1. 01 · OVER Keeps the Detail Rows
  2. 02 · PARTITION BY Creates Mini Windows
  3. 03 · Running Totals with ORDER BY
  4. 04 · Ranking Rows with ROW_NUMBER
  5. 05 · Looking Back with LAG
  6. 06 · Other Common Window Functions

Related guides