Using PARTITION BY for Grouping Windows in PostgreSQL
📖 Scenario: You work at a bookstore that tracks sales data. You want to analyze sales by each book category to see how each sale compares within its category.
🎯 Goal: Build a PostgreSQL query that uses PARTITION BY to group sales by book category and calculate the running total of sales within each category.
📋 What You'll Learn
Create a table called book_sales with columns sale_id, category, and amount.
Insert the exact sales data provided into book_sales.
Write a query that uses SUM(amount) OVER (PARTITION BY category ORDER BY sale_id) to calculate running totals per category.
Select sale_id, category, amount, and the running total as running_total.
💡 Why This Matters
🌍 Real World
Analyzing sales data by category helps businesses understand performance trends within each group.
💼 Career
Using window functions with PARTITION BY is a common skill for data analysts and database developers to perform advanced data analysis.
Progress0 / 4 steps
1
Create the book_sales table and insert data
Create a table called book_sales with columns sale_id as integer, category as text, and amount as numeric. Then insert these exact rows: (1, 'Fiction', 10), (2, 'Fiction', 15), (3, 'Non-Fiction', 20), (4, 'Fiction', 5), (5, 'Non-Fiction', 10).
PostgreSQL
Hint
Use CREATE TABLE to define the table and INSERT INTO to add the rows exactly as shown.
2
Add a variable for ordering sales
Define a variable or alias called order_col that will be used to order sales by sale_id in the query. This will help organize sales in the running total calculation.
PostgreSQL
Hint
In SQL, you don't create variables like in programming languages. Instead, you use column names directly in the query's ORDER BY clause.
3
Write the query using PARTITION BY to calculate running totals
Write a SELECT query that retrieves sale_id, category, amount, and a running total of amount called running_total. Use SUM(amount) OVER (PARTITION BY category ORDER BY sale_id) to calculate the running total grouped by category and ordered by sale_id.
PostgreSQL
Hint
Use the window function SUM() OVER (PARTITION BY category ORDER BY sale_id) to get running totals per category.
4
Complete the query with ordering by sale_id
Add an ORDER BY sale_id clause at the end of the query to display the results sorted by sale_id.
PostgreSQL
Hint
Use ORDER BY sale_id at the end of the query to sort the results by sale ID.
Practice
(1/5)
1. What does the PARTITION BY clause do in a window function in PostgreSQL?
easy
A. It filters rows before the window function is applied.
B. It divides the rows into groups to perform calculations within each group.
C. It sorts the entire table before applying the window function.
D. It removes duplicate rows from the result set.
Solution
Step 1: Understand the role of PARTITION BY
PARTITION BY groups rows so window functions calculate results within each group separately.
Step 2: Differentiate from filtering and sorting
Filtering removes rows, sorting orders rows, but PARTITION BY only groups rows without removing or sorting them globally.
Final Answer:
It divides the rows into groups to perform calculations within each group. -> Option B
Quick Check:
PARTITION BY = grouping rows for window functions [OK]
Hint: Remember: PARTITION BY groups rows, it does not filter or sort [OK]
Common Mistakes:
Confusing PARTITION BY with WHERE filtering
Thinking PARTITION BY sorts all rows
Assuming PARTITION BY removes duplicates
2. Which of the following is the correct syntax to use PARTITION BY in a window function?
easy
A. SELECT col, SUM(value) OVER (PARTITION BY col ORDER BY date) FROM table;
B. SELECT col, SUM(value) PARTITION BY col FROM table;
C. SELECT col, SUM(value) OVER PARTITION BY col FROM table;
D. SELECT col, SUM(value) WHERE PARTITION BY col FROM table;
Solution
Step 1: Identify correct window function syntax
The correct syntax uses OVER() with PARTITION BY inside parentheses.
Step 2: Check each option
SELECT col, SUM(value) OVER (PARTITION BY col ORDER BY date) FROM table; correctly uses SUM(value) OVER (PARTITION BY col ORDER BY date). Others misuse PARTITION BY outside OVER or with WHERE.
Final Answer:
SELECT col, SUM(value) OVER (PARTITION BY col ORDER BY date) FROM table; -> Option A
Quick Check:
Window functions use OVER() with PARTITION BY inside [OK]
Hint: PARTITION BY must be inside OVER() parentheses [OK]
Common Mistakes:
Placing PARTITION BY outside OVER()
Using WHERE instead of PARTITION BY
Omitting OVER() entirely
3. Given the table sales with columns region, month, and amount, what will this query return?
SELECT region, month, amount, SUM(amount) OVER (PARTITION BY region ORDER BY month) AS running_total FROM sales ORDER BY region, month;
medium
A. Monthly sales amount without any cumulative calculation.
B. Total sales amount for all regions combined.
C. An error because PARTITION BY cannot be combined with ORDER BY.
D. A running total of sales amount per region ordered by month.
Solution
Step 1: Understand SUM() OVER with PARTITION BY and ORDER BY
SUM() OVER (PARTITION BY region ORDER BY month) calculates a running total per region ordered by month.
Step 2: Analyze the output
Each row shows the cumulative sum of amount for that region up to the current month.
Final Answer:
A running total of sales amount per region ordered by month. -> Option D
Quick Check:
PARTITION BY groups, ORDER BY defines running total order [OK]
Hint: Running totals use PARTITION BY with ORDER BY inside OVER() [OK]
Common Mistakes:
Thinking it sums all regions together
Ignoring ORDER BY for running total
Assuming syntax error with ORDER BY in window
4. Identify the error in this query:
SELECT employee_id, department, RANK() OVER PARTITION BY department ORDER BY salary DESC FROM employees;
medium
A. Missing parentheses around PARTITION BY and ORDER BY clauses.
B. RANK() cannot be used with PARTITION BY.
C. ORDER BY cannot be used inside window functions.
D. employee_id must be included in PARTITION BY.
Solution
Step 1: Check window function syntax
Window functions require OVER() with parentheses enclosing PARTITION BY and ORDER BY.
Step 2: Identify missing parentheses
The query misses parentheses after OVER, causing syntax error.
Final Answer:
Missing parentheses around PARTITION BY and ORDER BY clauses. -> Option A
Quick Check:
OVER() must enclose PARTITION BY and ORDER BY [OK]
Hint: Always use parentheses after OVER() for window clauses [OK]
Common Mistakes:
Omitting parentheses after OVER
Thinking ORDER BY is not allowed in window functions
Assuming all columns must be in PARTITION BY
5. You want to calculate the average sales per product category and also show each sale's rank within its category by sale date. Which query correctly uses PARTITION BY to achieve this?
hard
A. SELECT product, category, sale_date, amount, AVG(amount) OVER (PARTITION BY sale_date), RANK() OVER (PARTITION BY product ORDER BY category) FROM sales;
B. SELECT product, category, sale_date, amount, AVG(amount) PARTITION BY category, RANK() PARTITION BY category ORDER BY sale_date FROM sales;
C. SELECT product, category, sale_date, amount, AVG(amount) OVER (PARTITION BY category), RANK() OVER (PARTITION BY category ORDER BY sale_date) FROM sales;
D. SELECT product, category, sale_date, amount, AVG(amount) OVER (ORDER BY category), RANK() OVER (ORDER BY sale_date) FROM sales;
Solution
Step 1: Use AVG() with PARTITION BY category
AVG(amount) OVER (PARTITION BY category) calculates average sales per category.
Step 2: Use RANK() with PARTITION BY category ordered by sale_date
RANK() OVER (PARTITION BY category ORDER BY sale_date) ranks sales within each category by date.
Step 3: Verify syntax correctness
SELECT product, category, sale_date, amount, AVG(amount) OVER (PARTITION BY category), RANK() OVER (PARTITION BY category ORDER BY sale_date) FROM sales; uses correct OVER() syntax with PARTITION BY and ORDER BY clauses for both functions.
Final Answer:
SELECT product, category, sale_date, amount, AVG(amount) OVER (PARTITION BY category), RANK() OVER (PARTITION BY category ORDER BY sale_date) FROM sales; -> Option C
Quick Check:
Use PARTITION BY category inside OVER() for grouping [OK]
Hint: Use OVER(PARTITION BY category) for grouping in window functions [OK]
Common Mistakes:
Omitting OVER() or PARTITION BY
Mixing PARTITION BY columns incorrectly
Using PARTITION BY without parentheses
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.