Introduction
Window frame specification lets you control which rows are included when calculating values over a group of rows in a table.
OVER (ORDER BY column_name ROWS BETWEEN frame_start AND frame_end)
SUM(sales) OVER (ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AVG(score) OVER (ORDER BY game_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)
COUNT(*) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING)
CREATE TABLE sales_data ( id INT, sale_date DATE, amount INT ); INSERT INTO sales_data VALUES (1, '2024-01-01', 100), (2, '2024-01-02', 150), (3, '2024-01-03', 200), (4, '2024-01-04', 50), (5, '2024-01-05', 300); SELECT id, sale_date, amount, SUM(amount) OVER (ORDER BY sale_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS running_sum_last_3 FROM sales_data ORDER BY sale_date;
ROWS BETWEEN clause specify in a window function?ROWS BETWEEN clause specifies the exact range of rows relative to the current row to include in the calculation.ROWS BETWEEN?ROWS BETWEEN X AND Y where X is the start and Y is the end of the frame.ROWS BETWEEN 2 PRECEDING AND CURRENT ROW.sales(date, amount) ordered by date, what is the output of this query?SELECT date, amount, SUM(amount) OVER (ORDER BY date ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS running_sum FROM sales;
date | amount
2024-01-01 | 100
2024-01-02 | 200
2024-01-03 | 300SELECT id, value, AVG(value) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND 2 PRECEDING) AS avg_val FROM data;
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW, not the other way around.ROWS counts physical rows, while RANGE counts logical values like dates, which can skip rows if dates have gaps.ROWS BETWEEN 2 PRECEDING AND CURRENT ROW always includes exactly 3 rows regardless of date gaps.Pass the test and this pattern moves unknown