Bird
Raised Fist0
PostgreSQLquery~20 mins

Named windows with WINDOW clause in PostgreSQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Named Windows Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of query using named window with WINDOW clause

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;
PostgreSQL
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;
A[{"region": "North", "month": 1, "amount": 100, "running_total": 100}, {"region": "North", "month": 2, "amount": 150, "running_total": 150}, {"region": "South", "month": 1, "amount": 200, "running_total": 200}, {"region": "South", "month": 2, "amount": 100, "running_total": 100}]
B[{"region": "North", "month": 1, "amount": 100, "running_total": 100}, {"region": "North", "month": 2, "amount": 150, "running_total": 250}, {"region": "South", "month": 1, "amount": 200, "running_total": 200}, {"region": "South", "month": 2, "amount": 100, "running_total": 300}]
C[{"region": "North", "month": 1, "amount": 100, "running_total": 250}, {"region": "North", "month": 2, "amount": 150, "running_total": 250}, {"region": "South", "month": 1, "amount": 200, "running_total": 300}, {"region": "South", "month": 2, "amount": 100, "running_total": 300}]
D[{"region": "North", "month": 1, "amount": 100, "running_total": null}, {"region": "North", "month": 2, "amount": 150, "running_total": null}, {"region": "South", "month": 1, "amount": 200, "running_total": null}, {"region": "South", "month": 2, "amount": 100, "running_total": null}]
Attempts:
2 left
💡 Hint

Think about how the window function sums amounts partitioned by region and ordered by month.

📝 Syntax
intermediate
1:30remaining
Identify the syntax error in WINDOW clause usage

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);
AWINDOW w AS (PARTITION BY category ORDER BY id ROWS 1 PRECEDING AND CURRENT ROW)
B)WOR TNERRUC DNA GNIDECERP 1 NEEWTEB SWOR di YB REDRO yrogetac YB NOITITRAP( SA w WODNIW
CWINDOW w AS (PARTITION BY category ORDER BY id ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)
DWINDOW w AS (PARTITION BY category ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
Attempts:
2 left
💡 Hint

Check the syntax for the ROWS BETWEEN clause carefully.

🧠 Conceptual
advanced
2:00remaining
Effect of reusing named windows in multiple window functions

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?

ABoth functions use the same partition and order, so the sum and rank are calculated consistently per department ordered by descending salary.
BThe functions will conflict and cause a runtime error because the same window name cannot be used twice.
CThe rank function ignores the named window and uses default ordering, causing inconsistent results.
DThe sum function will ignore the order clause in the named window, but rank will use it.
Attempts:
2 left
💡 Hint

Think about how named windows help reuse the same window definition.

🔧 Debug
advanced
2:30remaining
Debugging incorrect results with nested named windows

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?

AThe syntax of referencing <code>w1</code> inside <code>w2</code> is invalid and causes a syntax error.
BThe query will fail because you cannot define multiple named windows in one query.
CThe window <code>w2</code> ignores the partitioning from <code>w1</code> and calculates average over the entire table.
DBecause <code>w2</code> references <code>w1</code> but adds an ORDER BY clause, it creates a new window that does not partition correctly, causing unexpected results.
Attempts:
2 left
💡 Hint

Recall how named windows can be extended by adding clauses but must keep partitioning consistent.

❓ optimization
expert
3:00remaining
Optimizing query performance using named windows

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?

A
SELECT customer_id, transaction_date, amount,
       SUM(amount) OVER w AS cum_sum,
       RANK() OVER w AS rank_amount
FROM transactions
WINDOW w AS (PARTITION BY customer_id ORDER BY transaction_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW);
B
SELECT customer_id, transaction_date, amount,
       SUM(amount) OVER (PARTITION BY customer_id ORDER BY transaction_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sum,
       RANK() OVER (PARTITION BY customer_id ORDER BY amount DESC) AS rank_amount
FROM transactions;
C
SELECT customer_id, transaction_date, amount,
       SUM(amount) OVER w AS cum_sum,
       RANK() OVER w2 AS rank_amount
FROM transactions
WINDOW w AS (PARTITION BY customer_id ORDER BY transaction_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW),
       w2 AS (PARTITION BY customer_id ORDER BY amount DESC);
D
SELECT customer_id, transaction_date, amount,
       SUM(amount) OVER w AS cum_sum,
       RANK() OVER w AS rank_amount
FROM transactions
WINDOW w AS (PARTITION BY customer_id ORDER BY amount DESC ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW);
Attempts:
2 left
💡 Hint

Think about how named windows can be reused and extended to avoid repeating complex window definitions.

Practice

(1/5)
1. What is the main purpose of using the WINDOW clause in PostgreSQL?
easy
A. To join multiple tables using window functions
B. To create temporary tables for complex queries
C. To define named window specifications for reuse in the query
D. To specify the order of rows in a SELECT statement

Solution

  1. Step 1: Understand the role of WINDOW clause

    The WINDOW clause allows defining named window specifications once for reuse.
  2. Step 2: Compare options with WINDOW clause purpose

    Options A, B, and C describe other SQL features, not the WINDOW clause.
  3. Final Answer:

    To define named window specifications for reuse in the query -> Option C
  4. Quick Check:

    WINDOW clause = named window reuse [OK]
Hint: WINDOW clause defines reusable window specs [OK]
Common Mistakes:
  • Confusing WINDOW with temporary tables
  • Thinking WINDOW orders rows directly
  • Mixing WINDOW with JOIN operations
2. Which of the following is the correct syntax to define a named window called w1 that orders rows by date ascending?
easy
A. WINDOW w1 (ORDER BY date ASC)
B. WINDOW w1 AS (ORDER BY date ASC)
C. WINDOW w1 BY (ORDER date ASC)
D. WINDOW AS w1 ORDER BY date ASC

Solution

  1. Step 1: Recall WINDOW clause syntax

    The correct syntax is WINDOW name AS (window_definition), e.g., WINDOW w1 AS (ORDER BY date ASC).
  2. Step 2: Check each option's syntax

    WINDOW w1 AS (ORDER BY date ASC) matches correct syntax. Options A, B, and D have incorrect keyword order or missing AS.
  3. Final Answer:

    WINDOW w1 AS (ORDER BY date ASC) -> Option B
  4. Quick Check:

    WINDOW name AS (definition) syntax [OK]
Hint: Use WINDOW name AS (definition) syntax [OK]
Common Mistakes:
  • Omitting AS keyword
  • Using BY instead of ORDER BY
  • Misplacing parentheses
3. Given the query:
SELECT department, employee, salary, AVG(salary) OVER w AS avg_salary
FROM employees
WINDOW w AS (PARTITION BY department ORDER BY employee)
ORDER BY department, employee;

What does the avg_salary column show?
medium
A. The average salary of employees in the same department up to the current employee
B. The average salary of all employees in the company
C. The average salary of employees partitioned by department without order
D. The average salary of employees ordered by employee name across all departments

Solution

  1. Step 1: Analyze the WINDOW clause

    The window named w partitions rows by department and orders by employee.
  2. Step 2: Understand AVG() OVER w behavior

    AVG(salary) OVER w calculates the average salary for rows in the same department up to the current employee in order.
  3. Final Answer:

    The average salary of employees in the same department up to the current employee -> Option A
  4. Quick Check:

    Partition + order = running average per department [OK]
Hint: Partition + order means running calculation per group [OK]
Common Mistakes:
  • Ignoring ORDER BY in window
  • Assuming average over entire table
  • Confusing partition with no partition
4. Consider this query:
SELECT name, salary, SUM(salary) OVER w
FROM employees
WINDOW w AS (PARTITION BY department ORDER BY name BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW);

It returns an error. What is the likely cause?
medium
A. The window frame clause requires ROWS or RANGE keyword explicitly
B. The window frame clause is invalid without RANGE keyword
C. The WINDOW clause must come after ORDER BY clause
D. The window name cannot be used in the OVER clause

Solution

  1. Step 1: Check window frame syntax

    The frame clause must specify ROWS or RANGE explicitly before frame boundaries.
  2. Step 2: Identify error cause

    The query has ORDER BY name BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, missing the required ROWS or RANGE keyword before BETWEEN.
  3. Final Answer:

    The window frame clause requires ROWS or RANGE keyword explicitly -> Option A
  4. Quick Check:

    Window frame needs ROWS or RANGE keyword [OK]
Hint: Always specify ROWS or RANGE in window frame [OK]
Common Mistakes:
  • Placing WINDOW clause after ORDER BY
  • Omitting ROWS or RANGE keyword
  • Using window name incorrectly in OVER
5. You want to calculate the cumulative sum of sales per region ordered by date, and reuse this window in multiple queries. Which is the best way to define and use a named window for this purpose?
hard
A. Define WINDOW sales_win AS (PARTITION BY region ORDER BY date ROWS UNBOUNDED PRECEDING) and use SUM(sales) OVER sales_win
B. Use SUM(sales) OVER (PARTITION BY region ORDER BY date) without WINDOW clause
C. Define WINDOW sales_win AS (ORDER BY date PARTITION BY region) and use SUM(sales) OVER sales_win
D. Define WINDOW sales_win AS (PARTITION BY region ORDER BY date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and use SUM(sales) OVER sales_win

Solution

  1. Step 1: Understand cumulative sum window frame

    Cumulative sum requires a frame from the start to current row, so use RANGE or ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
  2. Step 2: Check window definition correctness

    Define WINDOW sales_win AS (PARTITION BY region ORDER BY date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and use SUM(sales) OVER sales_win correctly defines WINDOW with PARTITION BY region, ORDER BY date, and RANGE frame for cumulative sum.
  3. Step 3: Compare with other options

    Define WINDOW sales_win AS (PARTITION BY region ORDER BY date ROWS UNBOUNDED PRECEDING) and use SUM(sales) OVER sales_win uses ROWS UNBOUNDED PRECEDING which sums the entire partition, not cumulatively. Define WINDOW sales_win AS (ORDER BY date PARTITION BY region) and use SUM(sales) OVER sales_win has wrong order of clauses. Use SUM(sales) OVER (PARTITION BY region ORDER BY date) without WINDOW clause does not reuse named window.
  4. Final Answer:

    Define WINDOW sales_win AS (PARTITION BY region ORDER BY date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and use SUM(sales) OVER sales_win -> Option D
  5. Quick Check:

    Named window with correct frame = Define WINDOW sales_win AS (PARTITION BY region ORDER BY date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) and use SUM(sales) OVER sales_win [OK]
Hint: Use RANGE UNBOUNDED PRECEDING for cumulative sums [OK]
Common Mistakes:
  • Omitting frame clause for cumulative sum
  • Incorrect order of PARTITION BY and ORDER BY
  • Not using named window for reuse
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard