# SQL on Kafka: 5 ways to query a Kafka topic with SQL

Published Oct 30, 2026

Five working ways to run SQL on Kafka: ksqlDB, Flink SQL, ClickHouse, Trino and Otterstax. For each one you get what to run, a minimal example from the official docs, and the limits. The last part shows how each tool joins a Kafka stream with a PostgreSQL or MariaDB table.

Kafka keeps events in topics. To query a topic with SQL you need a tool that reads it and maps the events to table rows. The tools differ in two ways: whether a query runs once (batch) or keeps running (streaming), and whether you can JOIN the topic with a database table in the same statement. In most projects the second point decides the choice, because a stream of orders is useful only when you can join it with the customer table it refers to.

**Which tool fits**

| Tool | What you run | Query style | JOIN with a database table directly | Latency model | Fits when |
| --- | --- | --- | --- | --- | --- |
| ksqlDB | ksqlDB server next to Kafka | Streaming (push), limited pull | No, the table must be a Kafka topic first | Continuous, per event | You run Confluent and keep everything inside Kafka |
| Flink SQL | Flink cluster + Kafka and JDBC connectors | Streaming and batch | Yes, JDBC lookup join | Continuous, per event | Large stateful pipelines with a platform team |
| ClickHouse Kafka engine | ClickHouse server, Kafka table + materialized view | Batch on the stored copy | Yes, `PostgreSQL` / `MySQL` engines and dictionaries | Rows land in ClickHouse within seconds, then batch SQL | Analytics on event history in ClickHouse |
| Trino Kafka connector | Trino cluster + `kafka` catalog | Batch (topic scan) | Yes, across catalogs | Per query, scans the topic | Ad-hoc inspection next to a lake or warehouse |
| Otterstax (federated query engine) | One process, `CREATE SOURCE` | Batch on the materialized source, plus `CREATE STREAM` | Yes, federated JOIN with PostgreSQL, MariaDB, ClickHouse | Rows land in the engine within seconds, then SQL over a database driver | Apps, risk checks and agents that need Kafka next to databases |

## ksqlDB

ksqlDB is Confluent's SQL layer on Kafka Streams. You run a ksqlDB server next to the brokers and connect with the ksqlDB CLI or REST API. A `STREAM` maps to a topic, and a `TABLE` holds the latest value per key.

```sql
CREATE STREAM orders (
    order_id BIGINT KEY,
    customer_id VARCHAR,
    amount DOUBLE
  ) WITH (
    KAFKA_TOPIC = 'orders-topic',
    VALUE_FORMAT = 'JSON'
  );

SELECT customer_id, amount FROM orders EMIT CHANGES;
```

`KAFKA_TOPIC` is required, and the topic must exist unless you set `PARTITIONS`. `EMIT CHANGES` turns the SELECT into a push query that keeps running.

**Limitations.** Every input and output is a Kafka topic. Reference data from a database has to be copied into Kafka first. Stream-table joins allow INNER and LEFT only, on a single equality column, with co-partitioned inputs. Confluent's docs now name Flink as "the recommended stream processing engine" for new workloads. ksqlDB "remains fully supported for existing applications". The same note appears in the Confluent Cloud docs.

## Flink SQL

Apache Flink runs SQL as streaming or batch jobs on a cluster. The Kafka connector exposes a topic as a table. You submit the statement through the SQL client or SQL Gateway.

```sql
CREATE TABLE KafkaTable (
  `user_id` BIGINT,
  `item_id` BIGINT,
  `behavior` STRING,
  `ts` TIMESTAMP_LTZ(3) METADATA FROM 'timestamp'
) WITH (
  'connector' = 'kafka',
  'topic' = 'user_behavior',
  'properties.bootstrap.servers' = 'localhost:9092',
  'properties.group.id' = 'testGroup',
  'scan.startup.mode' = 'earliest-offset',
  'format' = 'csv'
);

SELECT behavior, COUNT(*) FROM KafkaTable GROUP BY behavior;
```

The table is unbounded by default. Set `scan.bounded.mode` to stop at an offset or timestamp and run the same SQL as a batch job. The Kafka sink offers `sink.delivery-guarantee = 'exactly-once'`, which uses Kafka transactions and needs checkpointing on.

**Limitations.** Flink is a distributed runtime with job managers, task managers, checkpoints and state backends. Someone has to operate it. Connectors and JDBC drivers are not in the binary distribution. Apps get results from the output topic or table that Flink writes, so they do not connect to Flink with a database driver.

## ClickHouse Kafka engine

ClickHouse can consume a topic itself. The `Kafka` table engine is a consumer and a `MergeTree` table stores the rows. A materialized view moves data from one to the other.

```sql
CREATE TABLE queue (
    timestamp UInt64,
    level String,
    message String
) ENGINE = Kafka()
SETTINGS
    kafka_broker_list = 'localhost:9092',
    kafka_topic_list = 'topic',
    kafka_group_name = 'group1',
    kafka_format = 'JSONEachRow',
    kafka_num_consumers = 4;

CREATE TABLE daily (
    day Date,
    level String,
    total UInt64
) ENGINE = SummingMergeTree
PARTITION BY toYYYYMM(day)
ORDER BY (day, level);

CREATE MATERIALIZED VIEW consumer TO daily
    AS SELECT toDate(toDateTime(timestamp)) AS day, level, count() AS total
    FROM queue GROUP BY day, level;
```

Once the view exists, ClickHouse collects data in the background, and you run your queries against `daily`.

**Limitations.** A `SELECT` on the Kafka table "is not particularly useful for reading messages (except for debugging)". Each message can be read only once. The number of consumers must not exceed the topic's partitions. The docs describe a loss window around offset commits. If the page cache is lost before the target part is synced, the rows are gone with no error. `fsync_after_insert = 1` narrows it. This is a copy of the events in ClickHouse, so you also pay for that storage.

## Trino Kafka connector

Trino is a distributed SQL engine with a catalog per data source. The Kafka connector lists topics as tables. Trino needs Kafka 3.3 or later with KRaft enabled.

`etc/catalog/example.properties`:

```properties
connector.name=kafka
kafka.table-names=table1,table2
kafka.nodes=host1:port,host2:port
```

Without a table description file a topic exposes only internal columns such as `_message`, `_partition_id`, `_partition_offset` and `_timestamp`. A JSON file in `kafka.table-description-dir` maps message fields to typed columns.

```sql
SELECT _partition_id, _partition_offset, _timestamp, _message
FROM example.default.table1
LIMIT 10;
```

**Limitations.** Every query reads the topic again. Trino does not store the events, and the docs note that rows "disappear as segments get dropped". The `_timestamp` upper bound is pushed down only for `LogAppendTime` topics, or with force push-down enabled. `INSERT` works with an encoder but is at-least-once, so duplicates are possible. Trino is a JVM cluster with a coordinator and workers, and apps connect through Trino's own drivers. See [when you need a Trino cluster →](/guides/when-you-need-a-trino-cluster).

## Otterstax: a federated query engine with a Kafka source

Otterstax is an open-source (Apache 2.0) federated query engine for MariaDB, PostgreSQL, ClickHouse, S3 and Kafka. It runs as one process. Databases are listed in `config.yaml` and read at startup; a Kafka topic is declared in SQL with `CREATE SOURCE`. A background poller consumes the topic and materializes each record into a table inside the engine. Apps and tools connect with their existing drivers over the PostgreSQL wire protocol (port 8817) or the MariaDB / MySQL wire protocol (port 8816).

```sql
-- psql -h localhost -p 8817 -U demo demo
CREATE SOURCE qs_orders (
    event_id    VARCHAR,
    customer_id VARCHAR,
    product_id  VARCHAR,
    amount      DOUBLE,
    status      VARCHAR,
    channel     VARCHAR
) WITH (KAFKA_TOPIC       = 'qs_orders',
        VALUE_FORMAT      = 'JSON',
        BOOTSTRAP_SERVERS = 'qs-kafka:9092',
        OFFSET_RESET      = 'earliest',
        TRANSACTIONAL     = true);

-- a few seconds later
SELECT status, COUNT(*) AS n, SUM(amount) AS total
FROM   kafka.qs_orders
GROUP BY status
ORDER BY n DESC;
```

Ingestion is asynchronous. If the first `SELECT` returns 0 rows, wait and run it again. `CREATE STREAM ... AS SELECT` starts a continuous transform that writes to another topic, and `INSERT INTO kafka.<source>` produces to the topic. The quickstart ships all of this with a demo broker and runs locally in about five minutes.

**Limitations.** Kafka data is loaded into the engine, so this is a copy. The "no data copies" rule holds for the database sources only: MariaDB, PostgreSQL and ClickHouse are read in place. Sources from `config.yaml` cannot be added at runtime. Every query adds one network hop, and a query across several sources waits for the slowest one. For an overview of the engine, see [how it works →](/how-it-works).

## Join a Kafka stream with a table in PostgreSQL or MariaDB

Events need customer, product or account data that lives in a database. This section shows how each of the five tools joins the two.

**ksqlDB.** The reference table must be a Kafka topic before you can join it. In practice you run a Kafka Connect JDBC or CDC source connector that copies the database table into a topic. Then you declare a `TABLE` over that topic and join. Only records arriving on the stream trigger output, and the join key must be a single column.

```sql
CREATE STREAM pageviews_enriched AS
  SELECT users.userid AS userid, pageid, regionid, gender
  FROM pageviews
    LEFT JOIN users ON pageviews.userid = users.userid
  EMIT CHANGES;
```

**Flink SQL.** The JDBC connector serves as a lookup source. You declare the database table with a primary key and join it with `FOR SYSTEM_TIME AS OF`. Flink queries the database per key. Turn on `lookup.cache = 'PARTIAL'` with `lookup.partial-cache.max-rows` and an expiry to protect the database.

```sql
CREATE TABLE MyUserTable (
  id BIGINT,
  name STRING,
  age INT,
  status BOOLEAN,
  PRIMARY KEY (id) NOT ENFORCED
) WITH (
   'connector' = 'jdbc',
   'url' = 'jdbc:mysql://localhost:3306/mydatabase',
   'table-name' = 'users'
);

SELECT * FROM myTopic
LEFT JOIN MyUserTable FOR SYSTEM_TIME AS OF myTopic.proctime
ON myTopic.key = MyUserTable.id;
```

For PostgreSQL the URL starts with `jdbc:postgresql://`. The MariaDB / MySQL driver and the PostgreSQL driver ship as separate artifacts.

**ClickHouse.** Create a table with the `PostgreSQL` engine, or `ENGINE = MySQL(...)` for MariaDB. Join it with the `MergeTree` table that the materialized view fills. Each `SELECT` on that table runs a query on the remote database. Simple `WHERE` comparisons are pushed down to the remote database, and joins run in ClickHouse. For small reference tables the docs recommend a dictionary with a refresh interval set by `LIFETIME`. They call it "easier and more efficient" than "a JOIN with reference tables".

```sql
CREATE TABLE default.postgresql_table
(
    `float_nullable` Nullable(Float32),
    `str` String,
    `int_id` Int32
)
ENGINE = PostgreSQL('localhost:5432', 'public', 'test', 'postgres_user', 'postgres_password');
```

**Trino.** Add a `postgresql` catalog next to the `kafka` catalog and join `kafka.default.orders` with `example.web.customers` in one statement. The PostgreSQL connector pushes joins down only inside one PostgreSQL database. The join between Kafka and PostgreSQL runs in Trino workers. Each PostgreSQL catalog can access one database.

```properties
connector.name=postgresql
connection-url=jdbc:postgresql://example.net:5432/database
connection-user=root
connection-password=secret
```

**Otterstax.** The materialized Kafka source is a table like any other, so the join is a plain federated JOIN. Filters and LIMIT are pushed down to each database. From the quickstart, live orders joined with customers and products in two PostgreSQL databases:

```sql
SELECT o.event_id, c.country, c.tier, p.category, o.amount
FROM   kafka.qs_orders o
JOIN   pgshop.shop.customers  c ON c.customer_id = o.customer_id
JOIN   pgcat.catalog.products p ON p.product_id  = o.product_id
WHERE  o.status = 'paid'
ORDER BY o.amount DESC
LIMIT 10;
```

To join with MariaDB instead, replace `pgshop` with a MariaDB alias from `config.yaml` and keep the rest of the statement as it is. More patterns are in [join tables from different databases →](/guides/join-tables-from-different-databases).

### When another tool is the right choice

Flink SQL is the better choice when you need windowed aggregations over billions of events, event-time semantics and large managed state. ksqlDB suits a pipeline that already lives in Confluent, where nothing leaves Kafka. Use the ClickHouse Kafka engine for historical analytics on event data you want in ClickHouse anyway. A federated query engine fits when the stream has to be queried together with tables in PostgreSQL, MariaDB or ClickHouse, and apps and agents read the result over a normal database driver.

## Example: risk monitoring at a trading company

This is an Otterstax customer case from a trading company. Trades flowed from the exchange into Kafka, then through ETL into Databricks, Greenplum and ClickHouse, and from there to risk monitoring. Fraud was detected about 2 hours after it happened.

The chain became exchange → Kafka → Otterstax → risk monitoring. Risk queries read the Kafka source and the account tables through one engine. Detection moved from about 2 hours to real time, and fraud dropped by 36.8% (−36.8%). ETL plus Greenplum, ClickHouse and Databricks were replaced with queries through one engine. Scoring events with an ML model inside the same SQL uses ONNX functions **(Enterprise)**. See [ML in SQL →](/use-cases/ml-in-sql).

## FAQ

### What are the alternatives to ksqlDB?

Flink SQL is the one Confluent itself recommends for new stream processing workloads. The ClickHouse Kafka engine fits analytics on stored events. The Trino Kafka connector fits ad-hoc scans next to a lake. A federated query engine such as Otterstax fits when the topic has to be joined with PostgreSQL, MariaDB or ClickHouse. Apps read the result through a MariaDB / MySQL or PostgreSQL driver.

### Is the Kafka data copied?

It depends on the tool. Trino reads the topic on every query and keeps nothing. ksqlDB and Flink keep state and write results to new topics. The ClickHouse Kafka engine stores rows in a `MergeTree` table. Otterstax materializes the topic into the engine with `CREATE SOURCE`, so Kafka data is copied there. Database tables stay in place.

### Which tools give exactly-once?

Flink's Kafka sink has `sink.delivery-guarantee = 'exactly-once'`, which needs checkpointing on. The ClickHouse docs do not promise exactly-once and describe a loss window around offset commits. Trino `INSERT` is at-least-once. Otterstax has a `TRANSACTIONAL = true` option on `CREATE SOURCE` that commits the row and the offset together.

### Can I query historical data in a Kafka topic?

Yes, within the topic's retention. Flink reads from `earliest-offset` and can stop at a bounded offset. Trino scans whatever segments still exist. ksqlDB, ClickHouse and Otterstax start from the earliest or latest offset when you create the stream, table or source. They keep what they ingest from that point on.

## Next step

Try the join on your own topic. The [Otterstax quickstart](https://github.com/otterstax/otterstax/tree/main/examples/quick_start) brings up Kafka, MariaDB, PostgreSQL and ClickHouse in about five minutes. To map it onto your production stream, [book a 30-minute pilot call](/demo).

---

## Sources

- [Confluent docs: ksqlDB for Confluent Platform, overview (note recommending Flink for new workloads)](https://docs.confluent.io/platform/current/ksqldb/overview.html) — checked 30.10.2026
- [Confluent docs: ksqlDB on Confluent Cloud, overview](https://docs.confluent.io/cloud/current/ksqldb/overview.html) — checked 30.10.2026
- [Confluent docs: ksqlDB legacy documentation and end of support table](https://docs.confluent.io/platform/current/ksqldb/operate-and-deploy/installation/legacy-documentation.html) — checked 30.10.2026
- [ksqlDB reference: CREATE STREAM](https://docs.confluent.io/platform/current/ksqldb/developer-guide/ksqldb-reference/create-stream.html) — checked 30.10.2026
- [ksqlDB developer guide: join streams and tables](https://docs.confluent.io/platform/current/ksqldb/developer-guide/joins/join-streams-and-tables.html) — checked 30.10.2026
- [Apache Flink docs: Kafka SQL connector (docs source in flink-connector-kafka)](https://raw.githubusercontent.com/apache/flink-connector-kafka/main/docs/content/docs/connectors/table/kafka.md) — checked 30.10.2026
- [Apache Flink docs: JDBC SQL connector, lookup join (docs source in flink-connector-jdbc)](https://raw.githubusercontent.com/apache/flink-connector-jdbc/main/docs/content/docs/connectors/table/jdbc.md) — checked 30.10.2026
- [ClickHouse docs: Kafka table engine](https://clickhouse.com/docs/engines/table-engines/integrations/kafka) — checked 30.10.2026
- [ClickHouse docs: PostgreSQL table engine](https://clickhouse.com/docs/engines/table-engines/integrations/postgresql) — checked 30.10.2026
- [ClickHouse docs: MySQL table engine](https://clickhouse.com/docs/engines/table-engines/integrations/mysql) — checked 30.10.2026
- [ClickHouse docs: dictionaries](https://clickhouse.com/docs/sql-reference/dictionaries) — checked 30.10.2026
- [Trino docs: Kafka connector](https://trino.io/docs/current/connector/kafka.html) — checked 30.10.2026
- [Trino docs: PostgreSQL connector](https://trino.io/docs/current/connector/postgresql.html) — checked 30.10.2026
- [Otterstax quickstart README, Kafka section K1–K4](https://github.com/otterstax/otterstax/tree/main/examples/quick_start) — checked 30.10.2026
- [Otterstax README](https://github.com/otterstax/otterstax) — checked 30.10.2026
- Otterstax: /how-it-works, /use-cases/ml-in-sql, /guides/join-tables-from-different-databases, /guides/when-you-need-a-trino-cluster, /demo

## See Otterstax on your own data sources

In a 30-minute call we'll map your stack and show a working query across your data sources.

[Talk about a pilot](https://otterstax.com/demo) · [Start with open source](https://github.com/otterstax/otterstax/tree/main/examples/quick_start)

---

Source: https://otterstax.com/guides/query-kafka-with-sql · Otterstax · info@otterstax.com
