> ## Documentation Index
> Fetch the complete documentation index at: https://docs.alginte.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SQL Query

> Query Kafka topics and state stores with SQL, inside the console: aggregate, join two topics, or join a topic with a file, with nothing to install.

**SQL Query** answers a question about your topics with one SQL query, run inside the console.
A table function, `kafka_topic()`, reads a bounded range of a topic the way the
[message viewer](https://docs.alginte.com/guides/messages.md) does, so you can count, aggregate and join records without
creating a stream or installing anything. The SQL is [DuckDB](https://duckdb.org/docs/stable/sql/introduction)'s,
run in a locked-down, in-memory engine for each query.

> [!NOTE]
>
> Available from Alginte 0.16.0, in the free Community edition. It is on by default, in the
> sidebar's Kafka group, behind the same login as the rest of the console. Reading files is off
> until you configure a folder (see [Files](#joining-a-topic-with-a-file)).

SQL Query and [ksqlDB](https://docs.alginte.com/guides/ksqldb.md) answer different questions. ksqlDB keeps a query running
on its own server and writes to topics. SQL Query reads a range of records once, answers, and
keeps nothing: no server, no state, no topic written.

## Your first query

In the [playground](https://docs.alginte.com/installation/playground.md), open **SQL Query** and run (Ctrl+Enter):

```sql theme={null}
SELECT customerId, count(*) AS orders,
       round(sum(quantity * priceEur), 2) AS revenue
FROM kafka_topic('orders', value_format := 'Avro')
GROUP BY ALL
ORDER BY revenue DESC
```

The seeded `orders` topic holds Avro records, so `value_format` names Avro. The columns come from
the registered `orders-value` schema, and each answer shows its columns' types in the header.

To start from a topic you are already reading, use the round **Query with SQL** button in the
message viewer's controls. It opens a new tab in SQL Query with a starter query over that
topic, written with the deserializers the viewer shows it with. Pick the right value
deserializer in the viewer first, so the starter names it too.

## Reading a topic

`kafka_topic('<topic>', ...)` is a table function. It goes in `FROM`, where a table name would,
and returns rows. Each call reads one range of one topic.

| Parameter | Meaning |
| - | - |
| `last := n` | The newest *n* records. The default, with *n* = 1000. |
| `from_offset := n`, `after := <epoch-ms>`, `before := <epoch-ms>` | Another range, each with `max := n` records (default 1000). |
| `key_format`, `value_format` | The message viewer's deserializer names: `String` (the default for both), `JSON`, `Avro`, `Protobuf`, `JSONSchema`, `Long`, `Integer` and the rest. |

Only one of `last`, `from_offset`, `after` and `before` may be given. A range larger than
`alginte.sql.max-records` is refused, not cut.

An answer covers the range read, not the whole topic: a `count(*)` or a `sum()` over the default
range counts the newest 1,000 records. When the range does not cover the topic, a note above the
result says so, with the offsets the topic spans and how to read it all, for example
`kafka_topic('orders') read 1,000 records, not the whole topic: it spans 25,400 offsets on 3
partitions …` followed by `To read it all: from_offset := 0, max := 25400.` A topic larger than
`alginte.sql.max-records` takes more than one call, and the note says that instead. A compacted
topic read from its start to its end is covered, though it holds fewer records than offsets.

The columns:

* `_partition`, `_offset`, `_timestamp` (UTC), `_key`, and `_value`, the whole value as JSON
  text. When the key or value is one number, as a Streams count or sum is, the format you name
  types it: with `Long`, `Integer` or `Short` the column is BIGINT, with `Double` or `Float`
  DOUBLE. So `ORDER BY _value DESC` puts 100 above 9, and `sum(_value)` needs no cast;
* one column per top-level field of the value. For Avro, Protobuf and JSON Schema the columns and
  their types come from the latest schema under `<topic>-value`, so `DESCRIBE` answers without
  reading a record. For other formats they are sampled from the records read.

Run `DESCRIBE SELECT * FROM kafka_topic(...)` to see the columns, or `SUMMARIZE` in its place to
profile them.

A wrong `value_format` is the usual mistake. A record the formats cannot read is left out, and a
note above the result names its partition and offset, the deserializer's reason, and the format
to read it with instead. The other records still answer. The message viewer shows such a record
as an error instead.

### Nested values

Only the top level becomes columns. A field holding an object or an array is a column of JSON
text, and `_value` holds the whole value, so DuckDB's JSON functions reach anything inside. Avro
and Protobuf nested records come out the same way. For a value such as:

```json theme={null}
{"customerId": "c-1",
 "address": {"city": "Zagreb", "geo": {"lat": 45.8}},
 "items": [{"sku": "a", "qty": 2}, {"sku": "b", "qty": 1}]}
```

| To get | Write | Answer |
| - | - | - |
| A nested field, as text | `address ->> '$.city'`, or `_value ->> '$.address.city'` | `Zagreb` |
| A deeper field, typed | `(_value -> '$.address.geo.lat')::DOUBLE` | `45.8` |
| An array's length | `json_array_length(_value, '$.items')` | `2` |
| The value's shape | `json_structure(_value)` | each field with its type |

`->>` answers text and `->` keeps JSON, so cast a number you want to compute with. To get one row
per element of an array, unnest it in `FROM`:

```sql theme={null}
SELECT customerId, i ->> 'sku' AS sku, (i ->> 'qty')::INT AS qty
FROM kafka_topic('orders', value_format := 'JSON'),
     unnest(from_json(_value -> '$.items', '["JSON"]')) AS u(i)
ORDER BY sku
```

In the result, a cell holding an object or an array opens formatted on a click.

### Joining two topics

A query can read several topics. In the playground, `customer-tiers` holds a tier per customer:

```sql theme={null}
SELECT c.tier, count(*) AS orders,
       round(sum(o.quantity * o.priceEur), 2) AS revenue
FROM kafka_topic('orders', value_format := 'Avro') o
JOIN kafka_topic('customer-tiers', value_format := 'JSON') c USING (customerId)
GROUP BY ALL
ORDER BY revenue DESC
```

An inner join drops an order whose customer has no tier, without a word. A `LEFT JOIN` finds
them:

```sql theme={null}
SELECT o.orderId, o.customerId
FROM kafka_topic('orders', value_format := 'Avro') o
LEFT JOIN kafka_topic('customer-tiers', value_format := 'JSON') c USING (customerId)
WHERE c.tier IS NULL
```

To keep the latest record per key, the way a compacted topic or a table sees it:
`QUALIFY row_number() OVER (PARTITION BY _key ORDER BY _offset DESC) = 1`.

## Joining a topic with a file

Kafka is the subject of every query, and a file can only add to it: a price list, a mapping, the
data that lives in a spreadsheet. The console reads files from one folder, the one you set in
`alginte.sql.allowed-directory`, and from nowhere else.

The folder must be mounted **read-only**. DuckDB can write where it reads, so when the folder is
writable the console turns SQL off and says why.

```shell theme={null}
docker run -p 8888:8888 \
  -e SPRING_KAFKA_BOOTSTRAPSERVERS=<kafka-host>:9092 \
  -e ALGINTE_SQL_ALLOWEDDIRECTORY=/data \
  -v ./files:/data:ro \
  alginte/alginte:latest
```

The playground mounts its `files/` folder this way, with `products.csv`, a price list for the
seeded orders:

```sql theme={null}
SELECT p.category,
       round(sum(o.quantity * (o.priceEur - p.unitCostEur)), 2) AS margin
FROM kafka_topic('orders', value_format := 'Avro') o
JOIN read_csv('/data/products.csv') p USING (item)
GROUP BY ALL
ORDER BY margin DESC
```

`read_csv`, `read_parquet` and `read_json` read a file by its path under the folder.

## Querying a state store

`kafka_store('<app>', '<store>')` reads a state store of a Kafka Streams app this console runs:
what its counts, aggregates and tables hold now, through Kafka's interactive queries. `<app>` is
the stream's application id.

```sql theme={null}
SELECT _key, _value
FROM kafka_store('<app>', '<store>')
ORDER BY _value DESC
```

The columns are `_partition`, `_key`, `_window_start` and `_window_end` (UTC) for a windowed or
session store, `_value`, then one per top-level field when the values are objects. `_value` is
typed when every value is one kind of number, text or boolean, so a count sums without a cast.

* **From a stream's page.** On a stream's [State tab](https://docs.alginte.com/streams/monitoring.md#the-state-tab), each
  store's name links to SQL Query with this query written for it.
* **Recent windows only.** A windowed store keeps the windows within its retention (the window
  size plus its grace, unless the app sets more), so older windows are not there to read.
* **This instance's partitions.** When the same application id also runs elsewhere, this console
  holds only some of the store's partitions. The answer then carries a note that it is partial,
  with how many partitions it read.

### An app deployed elsewhere

`kafka_store()` reads only the apps this console runs. A key-value store of any app can still be
read from its changelog topic, `<app>-<store>-changelog`: the newest record per key is what the
store holds. `value_format` is the store's value serde, Long for a count:

```sql theme={null}
SELECT _key, _value
FROM kafka_topic('<app>-<store>-changelog', value_format := 'Long')
QUALIFY row_number() OVER (PARTITION BY _key ORDER BY _offset DESC) = 1
```

A record with no value is a deleted key. To leave deleted keys out, filter the newest records in
an outer query, `SELECT * FROM (...) WHERE _value IS NOT NULL`. A `WHERE` beside the `QUALIFY`
runs first, and would answer the value from before the delete.

This works for key-value stores only. A windowed store's changelog key is the key followed by
binary window bytes, so it does not read as the key.

## The editor

* **Tabs** above the editor hold one query each, with its own result. Click **+** for a new
  tab, double-click a tab to rename it. A reload keeps your tabs; a new browser tab starts with
  one. *Query with SQL* opens its query in a new tab, so it never writes over yours. Up to 10
  tabs.
* **Run** (Ctrl+Enter) sends the active tab's text, or only the selected text when there is a
  selection. One tab can hold several queries, run one at a time.
* **Completions** offer topic names inside `kafka_topic('`, the deserializer names after
  `key_format` and `value_format`, the apps and their stores inside `kafka_store('`, and
  elsewhere the query's columns, then DuckDB's functions with their signatures.
* **Error marks** underline the place DuckDB points at as you type, with its message on hover.
  Nothing runs: the query is only prepared.
* **History** lists the last 30 queries you ran, in any tab, newest first. A click puts one
  back in the active tab. The history stays in this browser.
* **Help** above the editor is a cheat sheet: the functions, their parameters and columns, and
  the DuckDB features most useful for topic data.

## The result

The answer shows each column's DuckDB type in its header, the row count, and the time taken.

* Click a column's header to sort the rows on the page. `ORDER BY` sorts the whole answer.
* A cell holding a JSON object or array shows one line. Click it to open the value formatted.
* **Export** copies the rows to the clipboard or downloads them, as CSV or JSON.
* An answer longer than `alginte.sql.max-rows` is cut, and marked **cut at N rows**. An export
  of it is named `sql-result-cut-at-<N>-rows`.
* A note above the table says when a function left something out: records that could not be
  read, or a store read in part.

## Limits and safety

Each query runs in a fresh in-memory DuckDB, with these switched off: extensions (`INSTALL`,
`LOAD`), URLs and other network access, other databases (`ATTACH`), writing files
(`COPY ... TO`), files outside the allowed folder, and changing these settings from a query.

The limits are properties, listed under [Configuration](https://docs.alginte.com/operate/configuration.md#sql-query): the
query timeout (30 s), DuckDB's memory per query (256 MB), the records one call reads (100,000)
and the rows one answer returns (1,000).

### Spilling to disk

With the defaults, a query writes nothing anywhere: not in the allowed folder, not in a temp
folder. A query that needs more memory than `alginte.sql.memory-limit` fails with DuckDB's
out-of-memory error, and the console stays up. Such a query is usually a `GROUP BY`, `JOIN`,
`ORDER BY` or window function over many distinct keys, which must hold its whole input before
it answers.

When such a query must finish, you can let it spill to disk, as DuckDB does for
[larger-than-memory workloads](https://duckdb.org/docs/2.0/guides/performance/how_to_tune_workloads#larger-than-memory-workloads-out-of-core-processing):

```shell theme={null}
docker run -p 8888:8888 \
  -e SPRING_KAFKA_BOOTSTRAPSERVERS=<kafka-host>:9092 \
  -e ALGINTE_SQL_SPILL=true \
  -e ALGINTE_SQL_SPILLDIRECTORY=/spill \
  -v alginte-spill:/spill \
  alginte/alginte:latest
```

* **What it does.** A query over the memory limit writes its intermediate results to a folder of
  its own under `alginte.sql.spill-directory`, and the folder is deleted when the query ends.
  Without a spill directory, the folders go under the system temp folder.
* **What it costs.** DuckDB lets SQL read and write its spill folder, so with spilling on a query
  can write files into its own folder until it ends or the timeout cancels it. It never reaches
  another query's folder, and nothing outside it. Put the spill directory on a disk with room to
  spare, and keep the timeout short.
* **What it does not fix.** Spilling is DuckDB's, with
  [its limitations](https://duckdb.org/docs/2.0/guides/performance/how_to_tune_workloads#limitations):
  a query with several blocking operators, or an aggregate such as `string_agg()` that cannot
  move to disk, may still run out of memory. Raising `alginte.sql.memory-limit` is the other
  lever.

DuckDB unpacks its native library into the system temp folder the first time a query runs. A
container with a read-only root file system needs a writable `/tmp` for it, and, with spilling
on, a writable spill directory.

## For agents

The same queries are open to AI agents through the console's MCP server, as the read-only
`run_sql` tool. See [MCP server](https://docs.alginte.com/operate/mcp.md#querying-with-sql).

## Related

> [card] [Messages](https://docs.alginte.com/guides/messages.md)
>
> Browse, filter and decode records; Query with SQL starts here.

> [card] [ksqlDB](https://docs.alginte.com/guides/ksqldb.md)
>
> Continuous queries on a ksqlDB server.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.