# Pulse SQL language reference

This reference defines the supported SQL forms for **Pulse 0.2.4**. Submit one statement per HTTP `POST /query` request, for example `{"sql":"SELECT COUNT(*) FROM trades"}`. The enabled PostgreSQL listener uses the same query engine. The MCP `query` tool accepts read-only SELECTs and returns at most 500 rows.

| Statement | Standalone | Sharded cluster |
| --- | --- | --- |
| SELECT from a Pulse table | Yes | Yes, through any serving node |
| Scalar SELECT without FROM | Yes | Requires a table |
| SELECT over aliased derived tables | Yes | Yes, each input has its own read position |
| SHOW TABLES | Use the MCP `list_tables` tool when enabled | Returns the replicated catalog |
| ALTER TABLE for retention | Requires a sharded catalog | Yes, admin role when auth is enabled |
| User and service-account SQL | Authenticated catalog admin | Authenticated catalog admin |

## SELECT grammar

In the grammar below, square brackets mean optional, braces mean repeat zero or more times, and a vertical bar separates alternatives. Uppercase words are SQL keywords. Keywords and unquoted identifiers are case-insensitive. Unquoted names fold to lowercase. Double-quote identifiers to preserve case or punctuation, and single-quote text literals. A single trailing semicolon is optional.

```text
query       = SELECT [ ALL | DISTINCT [ ON "(" expr_list ")" ] ] item { "," item }
              [ FROM source ]
              [ WHERE predicate ]
              [ GROUP BY ( ALL | key { "," key } ) ]
              [ HAVING predicate ]
              [ ORDER BY sort_key { "," sort_key } ]
              [ LIMIT uint [ OFFSET uint | "," uint ] | OFFSET uint ]

item        = "*" | identifier "." "*" | expression [ [ AS ] alias ]
source      = table [ [ AS ] alias ] | derived_sources
derived     = "(" single_table_select ")" [ AS ] alias
derived_sources = joined { "," joined }
joined      = derived { CROSS JOIN derived | join_kind JOIN derived join_on }
join_kind   = [ INNER | ( LEFT | RIGHT | FULL ) [ OUTER ] ]
join_on     = ON predicate | USING "(" identifier { "," identifier } ")"
expr_list   = expression { "," expression }
key         = expression | output_alias | ordinal
sort_key    = key [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ]
```

Here `uint` means a nonnegative integer, `ordinal` is a positive integer, and `predicate` is a boolean expression. A `single_table_select` is a query over one Pulse table. Use either `LIMIT count OFFSET skip` or the unpaged shorthand `LIMIT skip, count`.

A base table is a single, unqualified name from the Pulse catalog. A column can be qualified by its table or alias. Ordinals start at 1. Use distinct output names and add an explicit ORDER BY whenever row order matters. Add tie-breakers if equal sort keys must have a reproducible order. The FROM-less form is available on standalone.

### Filters and expressions

| Form | Supported syntax |
| --- | --- |
| Values and arithmetic | Column references, numeric and string literals, TRUE, FALSE, NULL, parentheses, unary `+` and `-`, binary `+ - * / %` |
| Comparison | `= <> != < <= > >=`, `IS [NOT] DISTINCT FROM`, `[NOT] BETWEEN`, `[NOT] IN (value, …)` |
| Boolean | AND, OR, NOT, `IS [NOT] NULL`, `IS [NOT] TRUE`, `IS [NOT] FALSE` |
| Text | Concatenation with <code>&#124;&#124;</code>, LIKE, ILIKE, and regex operators `~`, `~*`, `!~`, `!~*` |
| Bitwise | `&`, <code>&#124;</code>, `^`, `~`, `<<`, `>>` |
| Conditional | `CASE [expression] WHEN … THEN … [ELSE …] END`, COALESCE, NULLIF |
| Conversion | `CAST(expression AS type)` and `expression::type` |

For function calls, the grammar distinguishes a scalar argument list from aggregate modifiers. The function determines valid arities and input types.

```text
scalar_call    = scalar_name "(" [ expr_list ] ")"
aggregate_call = aggregate_name "(" ( "*" | [ DISTINCT ] expr_list )
                 [ ORDER BY sort_key { "," sort_key } ] ")"
                 [ FILTER "(" WHERE predicate ")" ]
case_expr      = CASE [ expression ] WHEN expression THEN expression
                 { WHEN expression THEN expression } [ ELSE expression ] END
cast_expr      = CAST "(" expression AS type ")" | expression "::" type
```

Use `COUNT(*)` to count rows and `COUNT(column)` to count non-NULL values. Missing historical fields read as NULL. Use IS NULL to test for a missing value. Supported cast targets include BOOLEAN, SMALLINT, INT, BIGINT, UINT64 (also BIGINT UNSIGNED), REAL, DOUBLE, TEXT, VARCHAR, TIMESTAMP, and DECIMAL or NUMERIC with precision 1–38 and scale 0–precision. SQL output supports scalar columns. For a binary digest, return text with `encode(sha256(note), 'hex')`. Decimal results are exact strings in HTTP JSON.

### Grouping and time

The examples use a measurement named `trades`, with a `sym` tag, an integer `qty` field and the built-in `timestamp` column. WHERE filters rows before grouping. HAVING filters groups. Aggregates support forms such as `COUNT(*)`, `COUNT(DISTINCT sym)` and `SUM(qty) FILTER (WHERE qty > 1)`. When a projection mixes aggregates with nonconstant, nonaggregate expressions, Pulse can infer the latter as grouping keys. Use an explicit GROUP BY to make that choice visible. The implicit form requires a projection of expressions and no SELECT DISTINCT.

```sql
SELECT sym, COUNT(*) AS trades, SUM(qty) AS units
FROM trades
WHERE timestamp >= '2026-11-22' AND timestamp < '2026-11-23'
GROUP BY sym
HAVING SUM(qty) > 0
ORDER BY units DESC, sym
```

The stored `timestamp` is a signed 64-bit count of **nanoseconds since the Unix epoch**. For example, `timestamp + 1` advances by one nanosecond. Constant ISO dates and timestamps in comparisons with `timestamp` resolve to instants. The statement clock is read once for functions such as `now()`. Day boundaries use UTC. BETWEEN includes both endpoints and accepts reversed constant instant bounds. For consecutive reporting periods use a half-open interval as above.

```sql
SELECT timestamp_floor('1m', timestamp) AS minute, SUM(qty) AS units
FROM trades
GROUP BY 1
ORDER BY 1
```

GROUP BY ALL groups the nonaggregate select items. DISTINCT ON keeps the first row for each key according to ORDER BY. ROLLUP, CUBE and GROUPING SETS are rejected on single-table queries.

Only buckets containing rows appear. Supported interval forms include `INTERVAL '1 hour'`, `INTERVAL '3' DAY` and `INTERVAL '1 month 2 days'`. Calendar months and years use calendar arithmetic. For integer SUM, Pulse accumulates an exact wide total and checks the final value against the result type. An empty or all-NULL SUM returns NULL. Floating-point aggregates use approximate arithmetic.

### Joins and derived tables

To join two measurements, express **both inputs as aliased SELECTs**. Each inner query can filter and aggregate its own table before the coordinating node materializes the results. For example, this query joins each symbol’s volume to the largest trade for that symbol.

```sql
SELECT v.sym, v.units, p.largest
FROM (SELECT sym, SUM(qty) AS units FROM trades GROUP BY sym) AS v
JOIN (SELECT sym, MAX(qty) AS largest FROM trades GROUP BY sym) AS p
  ON v.sym = p.sym
ORDER BY v.sym
```

In the grammar, `derived_sources` consists of aliased derived inputs in FROM and JOIN positions. It accepts up to four comma-separated FROM entries and eight derived inputs in total. Every input needs a distinct alias. LATERAL and alias column lists are excluded. Direct base-table joins and mixed base/derived joins are rejected. Each input is a separate bounded read, so concurrent writes can produce different snapshots across the join. Paging the outer answer still requires the bounded join result to fit.

The coordinator reconstructs derived integer and timestamp columns as Int64, floating columns as Float64, booleans as Boolean, and decimal strings as text. A UInt64 cell above the signed range becomes NULL at this boundary. Cast large unsigned values to TEXT in the inner projection when their exact digits matter.

## Function catalog

The following names are admitted in ordinary single-table queries. Argument types and supported result types still apply. For example, a list-valued regex match may be tested with IS NOT NULL, while returning the list directly exceeds the scalar result contract.

| Family | Names |
| --- | --- |
| Clock and instant literals | `now`, `now_ns`, `systimestamp`, `systimestamp_ns`, `sysdate`, `current_timestamp`, `today`, `tomorrow`, `yesterday`, `to_timestamp`, `to_timestamp_ns`, `to_date`, `to_timestamp_nanos` |
| Calendar and formatting | `dateadd`, `datediff`, `date_bin`, `date_trunc`, `date_part`, `extract`, `timestamp_floor`, `timestamp_ceil`, `to_str`, `to_char`, `year`, `month`, `day`, `hour`, `minute`, `second`, `millis`, `micros`, `nanos`, `day_of_week`, `day_of_week_sunday_first`, `days_in_month`, `week_of_year`, `is_leap_year`, `is_end_of_month` |
| Math | `abs`, `ceil`, `ceiling`, `floor`, `round`, `trunc`, `round_down`, `round_up`, `round_half_even`, `sign`, `signum`, `sqrt`, `cbrt`, `exp`, `ln`, `log`, `log2`, `log10`, `power`, `pi`, `sin`, `cos`, `tan`, `cot`, `asin`, `acos`, `atan`, `atan2`, `sinh`, `cosh`, `tanh`, `degrees`, `radians`, `isnan`, `iszero`, `nanvl`, `gcd`, `lcm`, `factorial` |
| Selection and finance | `coalesce`, `nullif`, `nvl`, `greatest`, `least`, `switch`, `mid`, `spread`, `spread_bps`, `wmid` |
| Text | `concat`, `concat_ws`, `length`, `character_length`, `char_length`, `octet_length`, `length_bytes`, `bit_length`, `lower`, `upper`, `to_lowercase`, `to_uppercase`, `initcap`, `left`, `right`, `lpad`, `rpad`, `trim`, `btrim`, `ltrim`, `rtrim`, `replace`, `reverse`, `repeat`, `split_part`, `starts_with`, `ends_with`, `contains`, `strpos`, `position`, `substr`, `substring`, `substr_index`, `translate`, `ascii`, `chr`, `to_hex`, `levenshtein`, `find_in_set`, `overlay` |
| Regex and encoding | `regexp_like`, `regexp_match`, `regexp_replace`, `regexp_count`, `md5`, `sha224`, `sha256`, `sha384`, `sha512`, `digest`, `encode`, `decode` |
| Basic and ordered aggregates | `count`, `sum`, `min`, `max`, `avg`, `mean`, `count_distinct`, `approx_count_distinct`, `approx_distinct`, `first`, `last`, `first_not_null`, `last_not_null`, `first_value`, `last_value`, `arg_min`, `arg_max` |
| Statistical aggregates | `median`, `approx_median`, `approx_percentile`, `approx_percentile_cont`, `stddev`, `stddev_samp`, `stddev_pop`, `var`, `variance`, `var_samp`, `var_pop`, `var_sample`, `var_population`, `corr`, `covar`, `covar_samp`, `covar_pop`, `regr_slope`, `regr_intercept`, `regr_r2`, `regr_count`, `regr_avgx`, `regr_avgy`, `regr_sxx`, `regr_syy`, `regr_sxy` |
| Other aggregates | `bit_and`, `bit_or`, `bit_xor`, `bool_and`, `bool_or`, `string_agg`, `string_distinct_agg`, `weighted_avg`, `vwap`, `geomean`, `ksum`, `nsum` |

- `timestamp_floor('5m', timestamp)` returns a five-minute bucket. Calendar functions use case-sensitive unit codes, including `n` nanoseconds, `u` microseconds, `T` milliseconds, `s` seconds, `m` minutes, `h` hours, `d` days, `w` weeks, `M` months and `y` years. `datediff(unit, a, b)` returns a nonnegative whole-unit difference.
- `to_timestamp`, `to_timestamp_ns` and `to_date` accept constant text with an optional constant format. Use `to_timestamp_nanos` to convert a numeric nanosecond expression. `to_str` uses Java-style time patterns and `to_char` uses strftime-style patterns.
- LPAD, RPAD and REPEAT require a constant length or repeat count from 0 to 4096. Regexes use Rust regex syntax.
- `first(x)` and `last(x)` order by timestamp. Add an explicit tie-breaker inside FIRST_VALUE or LAST_VALUE if timestamps tie. `approx_count_distinct(x)` computes the exact distinct count in this release. KSUM and NSUM use ordinary SUM. The optional QuestDB precision argument to `approx_percentile(x, p, precision)` is ignored.

## Catalog and administrative statements

On a sharded cluster, `SHOW TABLES` returns one text column named `table_name`. The two ALTER TABLE forms below change retention. Use an admin credential when authentication is enabled.

```text
ALTER TABLE table SET TTL period
ALTER TABLE table DROP PARTITION WHERE timestamp ( "<" | "<=" ) constant_instant
```

A TTL accepts seconds, minutes, hours, days or weeks, including forms such as `36h` and `1.5 days`. A TTL of 0 disables the periodic policy. DROP PARTITION advances the table’s retention bound. Rows below that bound disappear from queries, and maintenance reclaims their storage later. Previously expired rows stay expired after the policy is cleared.

With database-managed identities enabled, an authenticated admin can use the following statements. Creating additional identities requires the `users` license feature. For direct HTTP, include `"service_account_admin": true` alongside `"sql"`, including for SHOW. The PostgreSQL listener supplies that flag for identity statements.

```text
SHOW USERS
CREATE USER name ROLE role PASSWORD VERIFIER 'verifier'
ALTER USER name SET ROLE role
ALTER USER name SET PASSWORD VERIFIER 'verifier'
DROP USER name

SHOW SERVICE ACCOUNTS
CREATE SERVICE ACCOUNT name ROLE role [ WITH token_spec ]
ALTER SERVICE ACCOUNT name SET ROLE role
ALTER SERVICE ACCOUNT name ADD token_spec
ALTER SERVICE ACCOUNT name DROP TOKEN token_id
DROP SERVICE ACCOUNT name

role       = reader | writer | admin
token_spec = TOKEN token_id SHA256 'hex_digest' EXPIRES AT unix_seconds
```

Use a Pulse PBKDF2-SHA256 password verifier for a person and a 64-hex-digit SHA-256 token digest for a workload. Token expiry is an absolute Unix time in **seconds**. Each successful edit commits independently.

## Limits and unsupported SQL

Pulse 0.2.4 excludes CTEs (WITH), set operations (UNION, INTERSECT, EXCEPT), scalar or correlated subqueries in predicates, OVER windows on base-table queries, table functions, external file or URL sources, and QuestDB SAMPLE BY and LATEST ON syntax. Use timestamp buckets with GROUP BY for observed samples. SQL ingestion and general schema DDL, including INSERT, UPDATE, DELETE and CREATE TABLE, are outside this dialect. Use the write and table administration APIs. PostgreSQL session commands such as BEGIN and COMMIT are acknowledged for client compatibility. Each read still captures its own snapshot.

An ordinary SELECT is limited to 256 projection items, 1,024 expression nodes and expression depth 32. SQL text is bounded at 64 KiB and the server can impose a lower limit. Row, response-byte, memory, scan-work and deadline limits apply separately. LIMIT caps the output and may still require scanning all matching input. A failed query returns an error instead of a partial result. A syntax or type error normally returns HTTP 400; a resource limit normally returns 429.

A successful HTTP SELECT returns `columns` and positional `rows`. A paged request adds `rows` and optionally `offset` **to the JSON request** and reads `more` in the response. Use a deterministic ORDER BY for paging. Every request captures a new read position, so concurrent writes can change the next page.
