Which of the following best explains why window functions are needed instead of just using GROUP BY?
Think about whether the original rows remain visible after aggregation.
GROUP BY groups rows and returns one row per group, losing individual row details. Window functions compute values across rows but keep each row visible.
Given a table sales with columns id, region, and amount, what is the output of this query?
SELECT id, region, amount, ROW_NUMBER() OVER (PARTITION BY region ORDER BY amount DESC) AS rank FROM sales;
CREATE TABLE sales (id INT, region VARCHAR(10), amount INT); INSERT INTO sales VALUES (1, 'East', 100), (2, 'East', 200), (3, 'West', 150), (4, 'West', 50);
Look at the PARTITION BY and ORDER BY inside the OVER clause.
ROW_NUMBER() assigns a unique number starting at 1 for each partition (region), ordered by amount descending.
Which option contains a syntax error in using a window function?
SELECT id, SUM(amount) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM sales;
Check the order of frame boundaries in the ROWS clause.
The frame must start with a preceding boundary and end with a following or current row boundary. 'UNBOUNDED FOLLOWING' cannot come before 'CURRENT ROW'.
Which reason best explains why window functions are preferred over self-joins to calculate running totals?
Think about query performance and code simplicity.
Window functions compute running totals efficiently in a single pass, while self-joins require multiple joins and are slower.
What error will this query produce?
SELECT id, region, amount, RANK() OVER (PARTITION BY region ORDER BY amount) AS rank FROM sales WHERE rank <= 2;
Consider when window functions are evaluated in SQL query processing.
Window functions are computed after WHERE clause filtering, so they cannot be used directly in WHERE. Use a subquery or HAVING instead.