# Query with SQL

SMTS executes bounded SQL queries using DataFusion. These examples use the standalone HTTP endpoint and the data from the [quickstart](/smts/getting-started/).

## Submit a query

```sh
curl --fail-with-body http://127.0.0.1:9070/query \
  -H 'Content-Type: application/json' \
  --data-binary '{"sql":"SELECT timestamp, device, value FROM temperature ORDER BY timestamp, device LIMIT 100"}'
```

Use explicit projections for application queries. Add an order when the result order matters, and set a limit suitable for your consumer. Check HTTP errors before interpreting the response as data.

## Filter a time interval

```sql
SELECT timestamp, device, value
FROM temperature
WHERE timestamp >= 1791504000000000000
  AND timestamp < 1791504002000000000
  AND device = 'dev-001'
ORDER BY timestamp
```

Half-open intervals (`>= start`, `< end`) compose cleanly without double-counting the boundary. Integer timestamp values are nanoseconds. Unquoted SQL identifiers fold to lowercase; quote names containing punctuation or uppercase characters.

## Aggregate by device

```sql
SELECT device,
       COUNT(*) AS samples,
       MIN(value) AS minimum,
       MAX(value) AS maximum,
       AVG(value) AS average
FROM temperature
GROUP BY device
ORDER BY device
```

Supported aggregates include COUNT, SUM, MIN, MAX, and AVG. Give output expressions distinct aliases. Missing fields are NULL; use SQL's NULL semantics rather than treating missing values as zero.

## Bucket time explicitly

```sql
SELECT date_bin(INTERVAL '1 second',
                to_timestamp_nanos(timestamp),
                to_timestamp_nanos(0)) AS bucket,
       COUNT(*) AS samples,
       AVG(value) AS average
FROM temperature
GROUP BY bucket
ORDER BY bucket
```

This query groups observed rows. It does not promise a row for empty buckets or interpolate missing samples. Make gap-filling an explicit application decision.

## Bound the work

The sample `[query]` config allows 10,000 output rows, a 4 MiB response, 64 MiB of operator memory, 128 MiB of scan memory, and a 30-second timeout. Narrow time filters and projections reduce work. LIMIT bounds returned rows; it does not guarantee that an aggregate scans few input rows.

Current source also supports `rows` and `offset` for bounded result pages. Separate requests need not share a snapshot, so pagination under concurrent writes is not a durable export strategy.

## Consistency and failures

A standalone query captures a committed view; later writes and compaction do not change that captured result. Capacity or deadline errors fail the query rather than silently returning a truncated answer. Integer SUM checks the exact final total and rejects overflow.

For the SELECT grammar, function catalog, supported joins, and administrative commands, see the [Pulse SQL language reference](/smts/docs/sql-reference/). Use [typed scans](/smts/docs/scans/) for bounded time-range reads.
