Window functions in ClickHouse perform calculations across sets of query rows that are related to the current row without collapsing the result into groups.
Need running totals, rankings, or moving averages without losing individual rows? Window functions let you compute these metrics in a single query, keeping all detail intact.
ClickHouse supports OVER
with optional PARTITION BY
, ORDER BY
, and a frame clause such as ROWS BETWEEN
or RANGE BETWEEN
. The frame controls which rows feed each calculation.
Add OVER ()
after an aggregate-like function.Example: sum(total_amount) OVER ()
returns the grand total on every row.
Place PARTITION BY customer_id
inside OVER
. Each customer gets its own running or ranking calculation.
Add ORDER BY
to control calculation order. Commonly you use ORDER BY order_date
for chronological metrics.
Omit the frame to default to RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
.Explicitly set ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
for 3-row moving windows.
Any aggregate—sum
, avg
, count
, min
, max
—plus ranking helpers such as row_number()
, rank()
, and dense_rank()
.
Combine sum(total_amount)
, PARTITION BY customer_id
, and ORDER BY order_date
to get per-customer cumulative revenue.
Smaller frames scan fewer rows and run faster.Prefer ROWS BETWEEN
limits when the business logic allows.
Fetching unnecessary columns expands intermediate data. List just the fields you actually use.
Without ORDER BY
, ClickHouse has no deterministic order, so running totals are meaningless. Always specify an ordering column.
RANGE
frames require numeric or date types. On strings you’ll get an error; switch to ROWS
instead.
.
Yes. Each function can use its own OVER
clause or share one by referencing OVER win_name
after defining it with WINDOW win_name AS (...)
.
They read extra rows but avoid subqueries. Add proper partitions, small frames, and selective columns to keep performance high.
Window functions reached production stability in ClickHouse 21.8. Upgrade if you run an earlier release.