SQL Window Functions: Performance, EXPLAIN, and Dialect Notes
How to tune window queries, reduce sorts, structure indexes, and account for cross-dialect differences.
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Performance patterns
WITH recent_orders AS (
SELECT *
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '90 days'
)
SELECT customer_id,
order_date,
amount,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY order_date DESC
) AS rn
FROM recent_orders;# Reduce the working set first.
## Dialect notes
More in SQL Window Functions
SQL Window Functions: Deduplication, Gaps and Islands, and Sessionization
Use ROW_NUMBER, LAG, and running groups to deduplicate rows, detect gaps, and form islands or sessions.
SQL Window Functions: Percentiles, Bucketing, and Distribution Analysis
Percent rank, cumulative distribution, percentile-style bucketing, and segmentation patterns.
SQL Window Functions: FIRST_VALUE, LAST_VALUE, NTH_VALUE, and Positional Analytics
Positional window functions for first, last, and nth values inside ordered partitions.
SQL Window Functions: LAG, LEAD, Deltas, and Time-Series Comparisons
Compare rows to prior or next rows with LAG and LEAD for change detection, retention, and trend analysis.
SQL Window Functions: Running Totals, Moving Averages, and Cumulative Metrics
Rolling metrics, cumulative sums, moving averages, and period-over-period analytics with frame clauses.
SQL Window Functions: Ranking, Top N per Group, and Percent Rank
Ranking functions such as ROW_NUMBER, RANK, DENSE_RANK, NTILE, PERCENT_RANK, and CUME_DIST.