Druid SQL queries on Apache Druid: a production guide

Sebastian Zontek
.
September 5, 2022
Druid SQL queries on Apache Druid: a production guide
Sebastian Zontek

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.

What Druid SQL is good at, and what it isn't

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:

  • You need low-latency updates of existing records by primary key. Updates run as background batch jobs.
  • You need "big" joins of one large fact table to another.
  • You are building an offline reporting system where query latency is not important.

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.

How a Druid SQL query runs

Planning happens on the Broker. Each statement becomes one of four native query types:

  • Scan, for queries with no aggregation.
  • Timeseries, for queries that group only by FLOOR(__time TO unit) or TIME_FLOOR(__time, period).
  • TopN, by default for one grouping expression with ORDER BY and LIMIT and no HAVING. Rankings can be approximate.
  • GroupBy, for all other aggregations. Results are exact.

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.

Time is the first filter

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 1

This 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' HOUR

Timestamp literals use SQL format (2016-06-27 00:00:00), not ISO 8601. For other formats, use TIME_PARSE.

Distinct counts are approximate by default

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 10

Both 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.

Read the plan with EXPLAIN PLAN FOR

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 10

The 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?
  • Joins: a query datasource under left or right, or a join whose condition is "1", means a subquery or a cartesian product.

Joins and their limits

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 20

Lookup 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:

  • The SQL syntax supports INNER and LEFT joins.
  • A join runs efficiently when the condition is an equality between same-type fields, or between a function on one side and a field on the other. Other conditions fall back to a subquery under the join, or to a cross join plus a filter.
  • Druid SQL does not reorder joins or push filters past a join into its inputs. Where you place a filter changes the plan. Avoid comma joins.
  • Unsupported: joins between datasources and system tables, conditions containing constants, and joins on multi-value dimensions.
  • 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.

Running queries: HTTP API and JDBC

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.json

Result 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.

Query context parameters

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 channel

The 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.

SQL-based ingestion with INSERT and REPLACE

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 channel

REPLACE 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 page

Rules from the reference:

  • PARTITIONED BY is required. CLUSTERED BY is optional and controls secondary partitioning and sort order within segments.
  • Columns load by name. Their position in the SELECT list is ignored, so use AS to set names.
  • An OVERWRITE WHERE range must match the PARTITIONED BY granularity.
  • REPLACE takes an exclusive lock on its time range. INSERT takes a shared lock.
  • INSERT suits larger batches. Use streaming ingestion for continuous loading instead of many small INSERT statements.

Common mistakes in production

  • No __time filter. The query reads every segment. Check intervals in EXPLAIN PLAN.
  • Treating approximate results as exact. COUNT(DISTINCT) and TopN rankings are approximate by default. Set the context flags when the number has to be exact.
  • Comparing a string column to a number. WHERE stringDim = 1 works, but WHERE stringDim = '1' performs better.
  • Deep pagination with OFFSET. Skipped rows are still computed, and OFFSET forces a Scan or GroupBy query.
  • Joining two large tables interactively. Every non-base input must fit in memory. Use a lookup, or a sort-merge join on MSQ.
  • Ignoring truncated responses. Check for the trailing newline in line-based result formats.

FAQ

Is Druid SQL standard SQL?

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.

Can I use Druid as an OLTP database?

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.

Is Druid SQL slower than native JSON queries?

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.

Which JDBC driver should I use?

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.

Can I query data that isn't loaded on Historicals?

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.

How do I see the native query Druid runs?

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.

Subscribe and stay in the loop with the latest on Druid, Flink, and more!

Thank you for joining our newsletter!
Oops! Something went wrong while submitting the form.
Deep.BI needs the contact information you provide to contact you. You may unsubscribe at any time. For information on how to unsubscribe and more, please review our Privacy Policy.

You Might Also Like