What if your database could do all the running totals and averages for you, instantly and perfectly?
Why SUM, AVG, COUNT as window functions in PostgreSQL? - Purpose & Use Cases
Imagine you have a big list of sales data for a store, and you want to know the running total of sales, the average sale amount so far, and how many sales have happened up to each point in time.
Doing this by hand means writing many separate queries or copying numbers into a spreadsheet and calculating step-by-step.
Manually adding up numbers or calculating averages for each row is slow and easy to mess up.
It's hard to keep track of running totals or counts without missing something or making mistakes.
Also, if the data changes, you have to redo all the work again.
Using SUM, AVG, and COUNT as window functions lets you calculate running totals, averages, and counts directly in your query.
This means the database does the hard work for you, updating results automatically for each row without extra queries.
SELECT date, sale_amount FROM sales;
-- Then manually add running totals in a spreadsheetSELECT date, sale_amount,
SUM(sale_amount) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING) AS running_total,
AVG(sale_amount) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING) AS running_avg,
COUNT(*) OVER (ORDER BY date ROWS UNBOUNDED PRECEDING) AS running_count
FROM sales;You can quickly see running totals, averages, and counts for each row, making data analysis faster and more accurate.
A store manager can instantly see how daily sales add up over the month, the average sale amount so far, and how many sales have been made, all in one report.
Manual calculations are slow and error-prone.
Window functions calculate running totals, averages, and counts automatically.
This makes data analysis easier, faster, and more reliable.
Practice
COUNT(*) OVER() window function do in PostgreSQL?Solution
Step 1: Understand COUNT(*) OVER() usage
The function counts all rows in the query result but does not group or collapse rows.Step 2: Difference from GROUP BY
Unlike GROUP BY, it keeps all rows visible and adds the count as a column.Final Answer:
Counts all rows in the result set without grouping them. -> Option AQuick Check:
COUNT(*) OVER() counts all rows [OK]
- Confusing window COUNT with GROUP BY count
- Thinking it returns a single aggregated row
- Assuming it counts distinct values only
Solution
Step 1: Identify correct window function syntax
SUM(sales) OVER (ORDER BY date) calculates cumulative sum ordered by date.Step 2: Check other options for syntax errors
The other options misuse window function syntax or omit OVER keyword.Final Answer:
SELECT sales, SUM(sales) OVER (ORDER BY date) AS running_total FROM sales_data; -> Option AQuick Check:
SUM() OVER (ORDER BY ...) is correct syntax [OK]
- Omitting OVER() clause
- Using PARTITION BY without OVER()
- Confusing GROUP BY with window functions
employees with columns department and salary, what will the following query return?SELECT department, salary, AVG(salary) OVER (PARTITION BY department) AS avg_dept_salary FROM employees;
Solution
Step 1: Understand PARTITION BY in AVG window function
AVG(salary) OVER (PARTITION BY department) calculates average salary per department for each row.Step 2: Confirm output per row
Each row keeps salary and adds average salary of that row's department without grouping rows.Final Answer:
Each row shows salary and average salary of its department. -> Option DQuick Check:
AVG() OVER (PARTITION BY ...) averages per group per row [OK]
- Thinking it aggregates to one row per group
- Confusing window AVG with GROUP BY AVG
- Expecting overall average without PARTITION BY
SELECT employee_id, salary, COUNT(*) OVER PARTITION BY department FROM employees;
Solution
Step 1: Check syntax of window function
OVER clause must have parentheses: OVER (PARTITION BY department).Step 2: Validate other parts
COUNT(*) is valid as window function; selecting employee_id is allowed.Final Answer:
Missing parentheses around PARTITION BY clause in OVER(). -> Option BQuick Check:
OVER() requires parentheses [OK]
- Omitting parentheses in OVER()
- Thinking COUNT(*) can't be window function
- Assuming window functions require GROUP BY
Solution
Step 1: Understand cumulative count per customer
COUNT(*) OVER (PARTITION BY customer_id ORDER BY order_date) counts rows per customer in order of order_date cumulatively.Step 2: Check other options for correctness
SELECT customer_id, order_date, COUNT(*) FROM orders GROUP BY customer_id, order_date ORDER BY order_date; uses GROUP BY, not cumulative count; C lacks partition by customer; D partitions by order_date, not customer.Final Answer:
SELECT customer_id, order_date, COUNT(*) OVER (PARTITION BY customer_id ORDER BY order_date) AS cumulative_orders FROM orders; -> Option CQuick Check:
Use PARTITION BY customer_id with ORDER BY for cumulative count [OK]
- Missing PARTITION BY customer_id
- Using GROUP BY instead of window function
- Partitioning by wrong column
Ready to prove it?
Pass the test and this pattern moves unknown
