sqladvanced
Window Frame ROWS vs RANGE Clauses
Control exactly which rows a window function considers using frame specifications.
sqlPress ⌘/Ctrl + Shift + C to copy
-- 7-day moving average using ROWS
SELECT
date,
daily_revenue,
AVG(daily_revenue) OVER (
ORDER BY date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS moving_avg_7d
FROM daily_metrics;
-- Running total with ROWS UNBOUNDED
SELECT
month,
revenue,
SUM(revenue) OVER (
ORDER BY month
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS running_total
FROM monthly_revenue;
-- RANGE: group ties together
SELECT
employee_id,
salary,
COUNT(*) OVER (
ORDER BY salary
RANGE BETWEEN 5000 PRECEDING AND 5000 FOLLOWING
) AS peers_in_range
FROM employees;Use Cases
- Moving averages
- Running totals
- Range-based peer analysis
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
sqladvanced
NTILE and Percentile Window Functions
Distribute rows into buckets and compute percentiles with window functions.
Best for: Customer segmentation
#sql#ntile
sqladvanced
SQL Window Functions for Analytics
Advanced SQL window functions for running totals, rankings, moving averages, and gap analysis.
Best for: Building analytics dashboards with running totals
#sql#window-functions
sqladvanced
SQL Window Functions for Analytics
Use window functions for running totals, rankings, moving averages, and gap detection in analytics.
Best for: Building cumulative revenue dashboards
#sql#window-functions
sqlintermediate
SQL Running Totals and Cumulative Metrics
Calculate running totals, cumulative counts, and percent-of-total using window functions and partitions.
Best for: Building cumulative revenue dashboards
#sql#window-functions