Redshift window functions add ranking, running totals, and moving averages without collapsing rows.
Window functions keep every row visible while adding aggregated metrics like rankings or running totals. GROUP BY collapses rows and hides detail.
Use function_name(arg) OVER (PARTITION BY expr ORDER BY expr ROWS BETWEEN frame)
. Only the OVER clause is mandatory; other clauses are optional.
PARTITION BY resets calculations for each group, while ORDER BY sets the sequence inside each partition for cumulative logic.
RANK() OVER (ORDER BY SUM(total_amount) DESC)
ranks customers after aggregating their spend.
Yes—use a frame like ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
to sum all prior rows up to the current one.
SUM(total_amount) OVER (ORDER BY order_date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
You can reference any column from the FROM clause; no need to add it to GROUP BY.
Create sort keys that match the ORDER BY inside large window frames, minimize partitions, and avoid DISTINCT inside window subqueries.
They scan all rows in each partition. Create sort keys aligned with ORDER BY and limit partitions to reduce cost.
No. Use a subquery or QUALIFY clause to reference the computed window column after it is calculated.