Druid SQL is the SQL interface to Apache Druid. You write SELECT statements, the Broker plans them with Apache Calcite and translates them into Druid's native JSON queries, and the cluster runs them. It is built for fast aggregations over large, time-partitioned event data. It is not an OLTP database: Druid supports streaming inserts but not streaming updates of existing rows by primary key.
This guide covers the syntax you need in production, the APIs, query context, joins and their limits, and SQL-based ingestion with INSERT and REPLACE. Examples use the wikipedia sample datasource from the Druid quickstart. They were checked against the Apache Druid 39.0.0 documentation.
The Druid docs say Druid is likely a good fit when most queries are aggregation and reporting queries, the data has a time component, and you target latencies of 100 ms to a few seconds. High insert rates with rare updates also fit.
It is likely a poor fit when:
Druid SQL has hard limits too. The interactive engine runs no DDL or DML, and there is no CREATE TABLE: a table exists once ingestion writes to it. In a query without aggregation, ORDER BY works only on __time.
Planning happens on the Broker. Each statement becomes one of four native query types:
FLOOR(__time TO unit) or TIME_FLOOR(__time, period).The docs call the SQL-to-native translation the only minor performance cost of using SQL. The native query type you end up with has a much bigger effect, and EXPLAIN PLAN shows it.
Every Druid table has a primary timestamp column, __time, which SQL reports as TIMESTAMP. Druid partitions data by time. A filter on __time becomes the native query's intervals, so Druid skips segments outside the range. Filter on __time in every query you can.
SELECT
TIME_FLOOR(__time, 'PT1H') AS hour_start,
COUNT(*) AS edits,
SUM(added) AS chars_added
FROM wikipedia
WHERE __time >= TIMESTAMP '2016-06-27 00:00:00'
AND __time < TIMESTAMP '2016-06-28 00:00:00'
GROUP BY 1
ORDER BY 1This query groups only by a time bucket, so it plans as Timeseries. TIME_FLOOR accepts any ISO 8601 period, with an optional origin and time zone. FLOOR(__time TO DAY) covers the standard units.
Relative filters become intervals too:
WHERE __time >= CURRENT_TIMESTAMP - INTERVAL '8' HOURTimestamp literals use SQL format (2016-06-27 00:00:00), not ISO 8601. For other formats, use TIME_PARSE.
SELECT
channel,
APPROX_COUNT_DISTINCT("user") AS approx_users,
COUNT(DISTINCT "user") AS distinct_users
FROM wikipedia
WHERE __time >= TIMESTAMP '2016-06-27 00:00:00'
AND __time < TIMESTAMP '2016-06-28 00:00:00'
GROUP BY channel
ORDER BY approx_users DESC
LIMIT 10Both columns are approximate. COUNT(DISTINCT) uses a HyperLogLog variant unless you set useApproximateCountDistinct to false, and APPROX_COUNT_DISTINCT is always approximate. With the DataSketches extension loaded, you can call APPROX_COUNT_DISTINCT_DS_HLL or APPROX_COUNT_DISTINCT_DS_THETA directly.
The ranking can be approximate as well, because one grouping column with ORDER BY and LIMIT plans as TopN. For an exact ranking, set useApproximateTopN to false and Druid uses GroupBy.
Put EXPLAIN PLAN FOR in front of a query and Druid returns the plan without running it.
EXPLAIN PLAN FOR
SELECT channel, COUNT(*) AS edits
FROM wikipedia
WHERE __time >= CURRENT_TIMESTAMP - INTERVAL '1' DAY
GROUP BY channel
ORDER BY edits DESC
LIMIT 10The result has three columns. PLAN holds the native queries as JSON, RESOURCES describes the resources used, and ATTRIBUTES includes the statement type. In PLAN, check:
queryType: is it the Timeseries, TopN or GroupBy you expected?intervals: is your time filter there, or does the query scan all time?query datasource under left or right, or a join whose condition is "1", means a subquery or a cartesian product.Interactive Druid SQL joins use a broadcast hash join. Every input except the leftmost base table must fit in memory. Joins are meant mainly for joining a table to lookups, inline data or subqueries. This example assumes a registered lookup named country_names:
SELECT
c.v AS country,
COUNT(*) AS edits
FROM wikipedia w
INNER JOIN lookup.country_names c ON w.countryIsoCode = c.k
WHERE w.__time >= CURRENT_TIMESTAMP - INTERVAL '1' DAY
GROUP BY 1
ORDER BY 2 DESC
LIMIT 20Lookup tables always have two columns, k and v. For a simple mapping, LOOKUP(countryIsoCode, 'country_names') does the same job without a join.
Before you write a join:
WHERE col IN (SELECT ...) runs as an inner join.For a join of two large inputs, use the multi-stage query (MSQ) task engine with sqlJoinAlgorithm set to sortMerge. It runs as a batch task.
The SQL endpoint is POST /druid/v2/sql on the Router or Broker. Writing the body to a file keeps shell quoting simple:
cat > query.json <<'JSON'
{
"query": "SELECT channel, COUNT(*) AS edits FROM wikipedia WHERE __time >= CURRENT_TIMESTAMP - INTERVAL '1' DAY GROUP BY channel ORDER BY edits DESC LIMIT 10",
"resultFormat": "objectLines",
"header": true,
"context": {
"sqlQueryId": "top-channels-001",
"sqlTimeZone": "Etc/UTC",
"timeout": 60000
}
}
JSON
curl -X POST "http://ROUTER_HOST:8888/druid/v2/sql" \
-H 'Content-Type: application/json' \
--data @query.jsonResult formats are object, array, objectLines, arrayLines and csv. If an error occurs while the body is streaming, Druid stops the response midstream. Line formats end with a newline, so a missing final newline means a truncated result: treat it as an error. To cancel the query, send DELETE /druid/v2/sql/top-channels-001.
Use ? placeholders and parameters rather than building SQL strings:
{
"query": "SELECT COUNT(*) FROM wikipedia WHERE channel = ?",
"parameters": [{"type": "VARCHAR", "value": "#en.wikipedia"}]
}For JDBC, the Druid 39.0.0 docs describe Druid's own JDBC driver (class org.apache.druid.jdbc.DruidJdbcDriver). It needs Java 17 or later and uses the same HTTP endpoint:
jdbc:druid:http://ROUTER_HOST:8888/druid/v2/sql/Druid keeps no per-connection state on the server: each query is an independent HTTP request, so you don't need sticky load balancing.
Context parameters change how one query is planned and run. Set them in the context field, or with SET statements before the query. If both set the same parameter, SET wins.
SET useApproximateCountDistinct = false;
SET sqlTimeZone = 'America/New_York';
SET timeout = 30000;
SELECT channel, COUNT(DISTINCT "user") AS users
FROM wikipedia
WHERE __time >= CURRENT_TIMESTAMP - INTERVAL '7' DAY
GROUP BY channelThe ones you will use most:
sqlTimeZone: time zone for time functions and timestamp literals. Default UTC.useApproximateCountDistinct and useApproximateTopN: both default to true.timeout: in milliseconds. The default comes from druid.server.http.defaultQueryTimeout.sqlQueryId: your own query ID, which you need to cancel a query.maxPlanningTimeMs: caps Broker planning time, for example against very large IN lists.INSERT and REPLACE run as batch tasks on the MSQ task engine, not on the interactive engine. Submit them through POST /druid/v2/sql/task or the web console's Query view. Each statement uses at least two task slots, one controller and at least one worker.
INSERT INTO wikipedia_edits
SELECT
TIME_PARSE("timestamp") AS __time,
channel,
page,
"user",
added,
deleted
FROM TABLE(
EXTERN(
'{"type": "http", "uris": ["https://druid.apache.org/data/wikipedia.json.gz"]}',
'{"type": "json"}',
'[{"name": "timestamp", "type": "string"}, {"name": "channel", "type": "string"}, {"name": "page", "type": "string"}, {"name": "user", "type": "string"}, {"name": "added", "type": "long"}, {"name": "deleted", "type": "long"}]'
)
)
PARTITIONED BY DAY
CLUSTERED BY channelREPLACE overwrites a whole table or a time range. This example rolls one day of the table up to minute granularity in place:
REPLACE INTO wikipedia_edits
OVERWRITE WHERE __time >= TIMESTAMP '2016-06-27 00:00:00'
AND __time < TIMESTAMP '2016-06-28 00:00:00'
SELECT
FLOOR(__time TO MINUTE) AS __time,
channel,
page,
SUM(added) AS added,
SUM(deleted) AS deleted
FROM wikipedia_edits
WHERE __time >= TIMESTAMP '2016-06-27 00:00:00'
AND __time < TIMESTAMP '2016-06-28 00:00:00'
GROUP BY 1, 2, 3
PARTITIONED BY DAY
CLUSTERED BY pageRules from the reference:
__time filter. The query reads every segment. Check intervals in EXPLAIN PLAN.COUNT(DISTINCT) and TopN rankings are approximate by default. Set the context flags when the number has to be exact.WHERE stringDim = 1 works, but WHERE stringDim = '1' performs better.It is based on Apache Calcite, so the syntax is standard SQL plus Druid functions such as TIME_FLOOR, APPROX_COUNT_DISTINCT and LOOKUP. Some features are missing, including DDL and, on the interactive engine, DML.
No. Druid does not support low-latency updates of existing records by primary key. Updates run as batch jobs, for example a REPLACE over a time range. The Druid JDBC driver also rejects writes and transactions.
Only by the planning step on the Broker, according to the docs. The native query type the planner picks has a much bigger effect, so check it with EXPLAIN PLAN.
On Druid 39.0.0, use the Druid JDBC driver described in the docs. It needs Java 17 or later and talks to the same /druid/v2/sql/ endpoint as the HTTP API.
Yes, through POST /druid/v2/sql/statements, which reads segments from deep storage and returns results asynchronously. To plan the query, Druid needs either at least one segment of the datasource loaded on a Historical, or the centralized datasource schema feature turned on.
Use EXPLAIN PLAN FOR, or turn on request logging, which records the exact native queries.
Running Druid in production and want help with query performance? See our Apache Druid services.