What if you could get complex running totals and averages instantly without fiddling with formulas every time?
Why Window frame (ROWS BETWEEN, RANGE BETWEEN) in PostgreSQL? - Purpose & Use Cases
Imagine you have a long list of daily sales numbers in a spreadsheet. You want to find the average sales for each day, but not just for that day alone -- you want to include the days before and after it to see trends. Doing this manually means copying and pasting formulas for each row, adjusting ranges every time.
Manually adjusting formulas for each row is slow and easy to mess up. You might select the wrong range or forget to update the formula when new data arrives. This leads to errors and wastes a lot of time, especially with big data.
Window frames like ROWS BETWEEN and RANGE BETWEEN let you tell the database exactly how many rows or what range of values to include around each row automatically. This means you get running totals, moving averages, and other calculations done correctly and instantly for every row without manual effort.
Calculate average sales for each day by manually adjusting formulas for each row in a spreadsheet.
SELECT day, sales, AVG(sales) OVER (ORDER BY day ROWS BETWEEN 2 PRECEDING AND 2 FOLLOWING) AS moving_avg FROM sales_table;
This lets you analyze trends and patterns over sliding windows of data easily, unlocking powerful insights from your data without extra manual work.
A store manager wants to see the average sales over the past 3 days and next 3 days for each day to understand sales trends and plan inventory better.
Manual calculations for moving averages are slow and error-prone.
Window frames automate range-based calculations around each row.
This makes trend analysis and running totals easy and reliable.