GROUP BY keyword

Groups aggregation calculations by one or several keys. In QuestDB, this clause is optional.

Syntax

SELECT column [, column ...], aggregation [, aggregation ...]
FROM tableName
[GROUP BY column [, column ...]];
note

QuestDB groups aggregation results implicitly and does not require the GROUP BY keyword. It is only supported for convenience. Using the GROUP BY clause explicitly will return the same results as if the clause was omitted.

Examples

The below queries perform aggregations on a single key. Using GROUP BY explicitly or implicitly yields the same results:

Single key aggregation, explicit GROUP BYDemo this query
SELECT symbol, avg(price), count()
FROM fx_trades
WHERE timestamp IN '$today'
GROUP BY symbol
LIMIT 5;
symbolavgcount
EURCAD1.595631597
EURUSD1.1701315311
USDMXN17.24331852
GBPJPY212.1231442
AUDJPY113.1032153
Single key aggregation, implicit GROUP BYDemo this query
SELECT symbol, avg(price), count()
FROM fx_trades
WHERE timestamp IN '$today'
LIMIT 5;

The below queries perform aggregations on multiple keys. Using GROUP BY explicitly or implicitly yields the same results:

Multiple key aggregation, explicit GROUP BYDemo this query
SELECT symbol, side, avg(price), count()
FROM fx_trades
WHERE timestamp IN '$today'
GROUP BY symbol, side
LIMIT 5;
symbolsideavgcount
USDCADsell1.360179061
NZDUSDbuy0.594431364
EURUSDsell1.1697157235
EURCHFbuy0.914915206
EURUSDbuy1.1705158076
Multiple key aggregation, implicit GROUP BYDemo this query
SELECT symbol, side, avg(price), count()
FROM fx_trades
WHERE timestamp IN '$today'
LIMIT 5;

When used explicitly, every non-aggregated column in the SELECT clause must appear in GROUP BY, otherwise an error will be returned:

Error - side is missing in the GROUP BY clause
SELECT symbol, side, avg(price)
FROM fx_trades
GROUP BY symbol;

The reverse is allowed. Extra columns in GROUP BY that are not in SELECT will produce a valid result, but the same symbol may appear multiple times (once per value of the extra key). This can be misleading, which is a good reason to prefer implicit GROUP BY where QuestDB always groups by exactly the non-aggregated columns in SELECT:

Extra GROUP BY key not in SELECTDemo this query
SELECT symbol, avg(price)
FROM fx_trades
WHERE timestamp IN '$today'
GROUP BY symbol, side
ORDER BY symbol
LIMIT 6;
symbolavg
AUDCAD0.9846
AUDCAD0.9838
AUDJPY113.1422
AUDJPY113.0659
AUDNZD1.2127
AUDNZD1.2118

See also