QuestDB Window Functions, in Practice: The OVER Clause, Moving Averages, and VWAP
“What’s the 20-bar average price? How much volume has accumulated today? Where does this ticker rank by turnover?” These questions come up more often than any other class of SQL task in time-series work. The traditional answer is to export to pandas and run rolling(), or to write a self-join. QuestDB pulls all of this back into SQL with a single construct: function(...) OVER (...), computed per row with the raw rows kept intact.
1. The three building blocks of OVER
The general shape is:
function(args) OVER (
[PARTITION BY column] -- split into groups, each computed independently
[ORDER BY column] -- logical order inside each group
[frame clause] -- which rows around the current row to include
);
- PARTITION BY carves the table into groups; the function resets for each one. When many instruments share one table, this is what keeps BTC’s cumulative volume from bleeding into ETH’s.
- ORDER BY defines the row order inside the window, independent of any outer query-level ORDER BY.
- The frame decides how many rows around the current row are in scope, e.g.
ROWS BETWEEN 3 PRECEDING AND CURRENT ROWis “this row plus the three before it.”
QuestDB has a time-series-specific optimization here: when the window’s ORDER BY column is the table’s designated timestamp, the data is already time-ordered on disk, and the engine skips a redundant sort.
2. ROWS frames vs RANGE frames
The two frame types produce genuinely different results, and picking the wrong one changes your numbers:
-- ROWS: physical row count
sum(price) OVER (ORDER BY ts ROWS BETWEEN 2 PRECEDING AND CURRENT ROW);
-- RANGE: timestamp value
sum(price) OVER (ORDER BY ts RANGE BETWEEN '1' MINUTE PRECEDING AND CURRENT ROW);
The ROWS frame always covers exactly three rows. The RANGE frame covers everything in the minute before each row’s timestamp — one tick if the market is quiet, hundreds if it’s busy. In market data, “volatility over the last minute” is a time-width question, so it wants RANGE.
One known limitation: RANGE frames with ties (“peers” sharing the ORDER BY value) are processed as distinct rows in QuestDB today, rather than producing identical results for all peers as the SQL standard requires — upstream is tracking this. If your ticks contain multiple rows at the same timestamp, don’t lean on RANGE-frame semantics; downsample with SAMPLE BY first.
3. A quick reference of the functions you’ll actually use
| Category | Functions | Notes |
|---|---|---|
| Offset | lag / lead | previous / following row; supports IGNORE NULLS |
| Ranking | rank / dense_rank / row_number / ntile | within-partition ranks |
| Aggregates | sum / avg / min / max / count / stddev / variance / covar_samp / corr | respect the frame |
| Distribution | percentile_cont / percentile_disc / cume_dist / percent_rank | partition-level |
| Precision | ksum | Kahan-compensated sum for long accumulations |
A practical detail: lag, lead, and the ranking functions ignore frame clauses entirely — they only look at PARTITION and ORDER. The aggregate family is what consumes frames.
4. Four runnable examples
Start an instance and seed some data:
docker run -t -i --rm \
-p 8812:8812 -p 9009:9009 -p 8817:8817 -p 8900-8999:8900-8999 \
-v $(pwd):/var/lib/questdb questdb/questdb:latest
CREATE TABLE ticks (
symbol SYMBOL,
price DOUBLE,
volume DOUBLE
) TIMESTAMP (ts) PARTITION BY DAY;
ILP: ticks,30s symbol=BTC-USDT price=101320.5 volume=1.2 ts=1753000000000000000
ILP: ticks,30s symbol=BTC-USDT price=101400.0 volume=0.8 ts=1753000010000000000
ILP: ticks,30s symbol=BTC-USDT price=101350.0 volume=1.5 ts=1753000020000000000
① Moving average (ROWS frame) — average of the current row plus three predecessors:
SELECT symbol, price, ts,
avg(price) OVER (
PARTITION BY symbol
ORDER BY ts
ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
) AS moving_avg_4
FROM ticks;
② Running total — QuestDB has a CUMULATIVE shorthand, equivalent to ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW:
SELECT ts, volume,
sum(volume) OVER (ORDER BY ts CUMULATIVE) AS running_total
FROM ticks;
③ VWAP — build 1-minute OHLCV with SAMPLE BY, then a cumulative volume-weighted average using a named window. Arithmetic between two window functions (like sum(...) / sum(...)) needs QuestDB 9.3.1+; on older versions wrap the terms in a CTE.
WITH ohlcv AS (
SELECT ts, symbol,
first(price) AS open,
max(price) AS high,
min(price) AS low,
last(price) AS close,
sum(volume) AS volume
FROM ticks
SAMPLE BY 1m
)
SELECT ts, symbol, open, high, low, close, volume,
sum((high + low + close) / 3 * volume) OVER w
/ sum(volume) OVER w AS vwap
FROM ohlcv
WINDOW w AS (ORDER BY ts CUMULATIVE)
ORDER BY ts;
④ Previous-row delta:
SELECT ts, price,
lag(price) OVER (PARTITION BY symbol ORDER BY ts) AS prev_price,
price - lag(price) OVER (PARTITION BY symbol ORDER BY ts) AS delta
FROM ticks;
5. Two gotchas you will hit
Gotcha one: window functions are not allowed in WHERE. WHERE avg(price) OVER (...) > 100 is rejected by the engine. Compute it first in a CTE, then filter:
WITH x AS (
SELECT ts, avg(price) OVER (ORDER BY ts CUMULATIVE) AS cum
FROM ticks
)
SELECT * FROM x WHERE cum > 1000;
Gotcha two: no ORDER BY is not “from the start” — it is “the whole group.” avg(price) OVER (PARTITION BY symbol) returns the group-wide mean on every row. If you want the “up to now” semantics you must write ORDER BY ts explicitly.
6. A QuestDB-specific extra: SUBSAMPLE keep-flags
Beyond the standard catalog, QuestDB ships time-series-native downsampling keep-flag functions: cadence (keep every Nth row), lttb (Largest-Triangle-Three-Buckets, chart-friendly), minmax (keep the extremes per bucket so you never lose a high or low), m4 (first, last, min, max per bucket), sdt (Swinging Door Trending with bounded error), and uniform (evenly spaced). They return keep/retire flags on each row, and the outer layer filters on them — a clean way to collapse a million ticks into a few thousand points for a dashboard. Note these reject explicit frame clauses.
Next steps
- Window functions operate on one table. To aggregate another table’s rows into a time window, that is QuestDB’s
WINDOW JOIN— a different feature, don’t conflate them. - Aligning an order time to the last traded price before it is an ASOF JOIN problem; the ASOF article has a worked pairing.
- Want the window results to refresh live? Use
LIVEqueries withREFRESH EVERY.