Consider the following table sales with columns region, month, and amount. What is the output of this query?
SELECT region, month, amount, SUM(amount) OVER w AS running_total FROM sales WINDOW w AS (PARTITION BY region ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) ORDER BY region, month;
CREATE TABLE sales (region TEXT, month INT, amount INT); INSERT INTO sales VALUES ('North', 1, 100), ('North', 2, 150), ('South', 1, 200), ('South', 2, 100); SELECT region, month, amount, SUM(amount) OVER w AS running_total FROM sales WINDOW w AS (PARTITION BY region ORDER BY month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) ORDER BY region, month;
Think about how the window function sums amounts partitioned by region and ordered by month.
The named window w partitions rows by region and orders them by month. The SUM(amount) is cumulative from the first month to the current month within each region.
Which option contains a syntax error in the use of the WINDOW clause in PostgreSQL?
SELECT id, value, AVG(value) OVER w FROM data WINDOW w AS (PARTITION BY category ORDER BY id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW);
Check the syntax for the ROWS BETWEEN clause carefully.
Option A is missing the keyword BETWEEN before the frame boundaries, which is required syntax.
Given the named window w defined as PARTITION BY dept ORDER BY salary DESC, what is the effect of using SUM(salary) OVER w and RANK() OVER w in the same query?
Think about how named windows help reuse the same window definition.
Named windows allow multiple window functions to share the same partitioning and ordering, ensuring consistent calculations.
Consider this query:
SELECT employee_id, department, salary,
AVG(salary) OVER w1 AS avg_dept_salary,
AVG(salary) OVER w2 AS avg_high_salary
FROM employees
WINDOW w1 AS (PARTITION BY department),
w2 AS (w1 ORDER BY salary DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW);Why might avg_high_salary not produce the expected cumulative average of high salaries per department?
Recall how named windows can be extended by adding clauses but must keep partitioning consistent.
When a named window references another and adds ORDER BY and frame clauses, it inherits partitioning but the frame affects cumulative calculations. If misunderstood, results may seem off but syntax is valid.
You have a large table transactions with columns customer_id, transaction_date, and amount. You want to calculate both the cumulative sum of amount per customer ordered by date and the rank of each transaction per customer by amount descending.
Which query uses named windows to optimize performance by avoiding repeated window definitions?
Think about how named windows can be reused and extended to avoid repeating complex window definitions.
Option C defines two named windows w and w2 with different orderings for different calculations, avoiding repeating window clauses inline. This improves readability and can help the planner optimize.