Reference Markdown

SQL

The SQL dialect SkimmerDB runs over namespaces' documents: statements, joins across namespaces, subqueries, window functions, types, NULLs, operators, functions, text predicates, answers and limits.

POST /v1/namespaces/{name}/sql with {"sql": "SELECT ..."} runs one query over the namespace's documents, the table docs (read scope; the MCP tool is sql_query). Your other namespaces are tables too, by name, so a query can join them; POST /v1/sql runs a query where every table is a namespace named. It reads the same copy of the data that search uses: each document is a row, its id and every top-level meta key are columns, and the text index works inside WHERE. SQL is in beta: the dialect will grow, and what's listed here works today.

For how to shape data for SQL and worked examples, see Analytics with SQL.

curl -s $B/namespaces/support/sql -H "Authorization: Bearer $KEY" \
  -d '{"sql": "SELECT status, COUNT(*) AS n FROM docs WHERE contains(text, '\''refund'\'') GROUP BY status ORDER BY n DESC"}'
from skimmerdb import SkimmerDB

ns = SkimmerDB().namespace("support")
r = ns.sql("SELECT status, COUNT(*) AS n FROM docs WHERE contains(text, 'refund') GROUP BY status ORDER BY n DESC")
print(r.columns, r.rows)
import { SkimmerDB } from "skimmerdb";

const ns = new SkimmerDB().namespace("support");
const r = await ns.sql("SELECT status, COUNT(*) AS n FROM docs WHERE contains(text, 'refund') GROUP BY status ORDER BY n DESC");
console.log(r.columns, r.rows);

Statement shape

One query a request: a SELECT, optionally with WITH before it and UNION / INTERSECT / EXCEPT between SELECTs.

sql
[WITH name [(columns)] AS (query), ...]
SELECT [DISTINCT] expr [AS name], ...  |  *  |  t.*
[FROM table [AS] alias, ... [JOIN ...]]
[WHERE predicate]
[GROUP BY expr | alias | position, ... | ROLLUP (...) | CUBE (...) | GROUPING SETS (...) | ALL]
[HAVING predicate]
[QUALIFY predicate]
[UNION | INTERSECT | EXCEPT [ALL] SELECT ...]
[ORDER BY expr | alias | position [ASC | DESC] [NULLS FIRST | NULLS LAST], ...]
[LIMIT n] [OFFSET m]
  • Tables are namespaces. In /v1/namespaces/{name}/sql, docs is that namespace. Any other namespace of the tenant is a table by its name; quote a name with - or . in it: "web-events". In /v1/sql every table is named. A key limited to some namespaces sees only those: any other name is no table, as if it didn't exist.
  • Aliases with or without AS. An unnamed column is named after its expression (count, sum, (amount * 2), ...).
  • GROUP BY and ORDER BY take a column, an alias, an expression or a 1-based position in the select list.
  • ORDER BY defaults to ascending and to NULLS LAST in both directions.
  • LIMIT and OFFSET take whole numbers (FETCH FIRST n ROWS ONLY works too).
  • SELECT * returns id and every column (of every table joined; t.* for one).
  • Identifiers may be double-quoted ("user plan"), and keywords aren't case-sensitive. Strings are single-quoted, with '' for a quote inside one. -- and /* */ are comments.

SHOW COLUMNS (or DESCRIBE) lists the namespace's columns: name, type, and how many segments hold each one.

Joins

sql
-- tickets by the plan of the user who opened them (two namespaces)
SELECT u.plan, COUNT(*) AS tickets
FROM docs t JOIN users u ON u.id = t.user_id
WHERE contains(t.text, 'refund')
GROUP BY u.plan ORDER BY tickets DESC
  • [INNER] JOIN, LEFT [OUTER] JOIN, RIGHT JOIN, FULL [OUTER] JOIN, CROSS JOIN, a comma list (FROM a, b WHERE a.x = b.y), USING (cols), NATURAL JOIN, and SEMI JOIN / ANTI JOIN.
  • LATERAL (SELECT ...) may name the columns of the tables before it: a comma, CROSS JOIN LATERAL, JOIN LATERAL ... ON or LEFT JOIN LATERAL ... ON true (rows with nothing on the right kept, as NULLs). Each row's top rows: FROM users u, LATERAL (SELECT id, total FROM orders o WHERE o.user_id = u.id ORDER BY total DESC LIMIT 3) t.
  • UNNEST(arr) [AS] t(col) in FROM: a row for each element of a JSON array (a metadata array, or one from ->), next to its document's row: FROM docs, UNNEST(tags) AS t(tag). Elements are int, float or text (objects and arrays inside as JSON); a value that isn't an array gives no rows.
  • Conditions on one table are applied in its own scan, through its zone maps and text index; equalities between tables are hash joins. When one side has few distinct keys (up to 4,096), they're sent to the other table's scan as a filter, so a big namespace joined to a small filtered one reads only the blocks that can match.
  • With several tables, say whose text a text predicate searches: contains(t.text, 'refund').
  • A join's result holds at most a share of the server's memory in rows (1M or more); past it, a 422 says to filter or aggregate first.

Subqueries and WITH

  • x IN (SELECT ...), x NOT IN (SELECT ...), EXISTS (SELECT ...), (SELECT ...) as a value, and (SELECT ...) AS t in FROM.
  • Correlated subqueries (ones that name the outer query's columns) work anywhere a value does: in WHERE, the select list and HAVING, with any condition on the outer columns (=, <, ...), aggregates, GROUP BY and ORDER BY ... LIMIT inside. Each runs once, over the distinct outer values it names, joined to them (not once a row), so a correlated subquery costs about what the equivalent join does:
sql
-- each user's order count (0 when none) and latest order
SELECT u.id,
       (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS orders,
       (SELECT o.id FROM orders o WHERE o.user_id = u.id ORDER BY o.placed_at DESC LIMIT 1) AS latest
FROM users u

-- orders above their customer's average
SELECT id FROM orders o WHERE total > (SELECT AVG(total) FROM orders o2 WHERE o2.user_id = o.user_id)

A subquery used as a value gives at most one row for each outer row (else a 422 says to add LIMIT 1 or an aggregate). NOT IN follows SQL: a NULL among the values makes it NULL, not true.

  • WITH name AS (...) is computed once, however often it's used.
  • WITH RECURSIVE name (cols) AS (first rows UNION [ALL] step): the step refers to name and runs over the rows the last round added, until a round adds none. With UNION (not ALL) rows already found aren't added again, so walks over cycles end. A recursion runs at most 10,000 rounds and holds at most the join row cap; past either, a 422.
sql
-- every manager above an employee (an org chart in one namespace)
WITH RECURSIVE up(id, manager, depth) AS (
  SELECT id, manager, 0 FROM people WHERE id = 'e-17'
  UNION ALL
  SELECT p.id, p.manager, up.depth + 1 FROM people p JOIN up ON p.id = up.manager)
SELECT id, depth FROM up ORDER BY depth

Window functions

sql
-- each user's latest event
SELECT id, user_id, ts FROM docs
QUALIFY ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY ts DESC) = 1

-- a running total and each day's share of its month
SELECT day, revenue,
       SUM(revenue) OVER (ORDER BY day) AS running,
       revenue / SUM(revenue) OVER (PARTITION BY DATE_TRUNC('month', day)) AS share
FROM daily
FunctionValue
ROW_NUMBER(), RANK(), DENSE_RANK(), NTILE(n), PERCENT_RANK(), CUME_DIST()Position in the partition's order
LAG(x [, k [, default]]), LEAD(...)x k rows before or after
FIRST_VALUE(x), LAST_VALUE(x), NTH_VALUE(x, n)A value of the frame
Any aggregate, OVER (...)Over the frame

OVER (PARTITION BY ... ORDER BY ... [ROWS | RANGE BETWEEN ... AND ...]): frames take UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING, UNBOUNDED FOLLOWING. With ORDER BY and no frame, an aggregate runs from the partition's start to the current row and its peers; without ORDER BY, over the whole partition. ROWS counts rows; RANGE offsets are values of the one ORDER BY key: a number (RANGE BETWEEN 10 PRECEDING AND CURRENT ROW over amounts; days over a date, seconds over a time) or an INTERVAL over a date or time (RANGE BETWEEN INTERVAL '7 days' PRECEDING AND CURRENT ROW: a rolling week, however many rows a day has). Rows whose key is NULL frame their NULL peers. Window functions work over a GROUP BY too (RANK() OVER (ORDER BY SUM(x) DESC)), and QUALIFY filters on them.

Columns and types

Each document is a row. The columns are:

ColumnWhat
idThe document id (text)
every top-level meta keyTyped from its values
every key inside a nested object, by its dotted pathuser.plan for {"user": {"plan": "pro"}}, four levels deep

text itself isn't a column: reach it with contains and grep.

Types come from the values written:

ValuesType
Integers, booleans (true is 1, false is 0)int
Other numbersfloat
Strings, arrays and nested objects (as their compact JSON; an object's keys are also columns)text
Imported CSV YYYY-MM-DDdate
Imported CSV YYYY-MM-DD HH:MM:SStime
Only nulls so farnull, until a value gives it a type
  • There's no schema to declare. The namespace's schema is the union of what its documents hold: a new key becomes a column with the next write, and documents without it read it as NULL.
  • A key whose values change type is read at the widest type seen: int < float < text. If priority is 3 in one document and "high" in another, it's text, and priority > 2 becomes an error. See Data model for keeping types consistent.
  • The 256 most frequent keys of each part of the namespace are columns, nested ones counted too. Keys named id (the document id wins) and keys starting with # aren't.
  • Nested metadata. {"user": {"plan": "pro", "addr": {"city": "Oslo"}}} gives the columns user (the object, as JSON text), "user.plan" and "user.addr.city". Write them user.plan (a table named user comes first), meta.user.plan, or quoted, "user.plan"; a top-level key spelled with a dot wins over a nested one. Search filters take the same dotted keys: {"user.plan": "pro"}. Arrays stay one text column of JSON: read them with UNNEST, list_contains and the JSON functions. Documents written before 2026-10-18 get these columns the next time their columns are made (as a namespace is written and compacted); meanwhile a part that keeps the object only as JSON answers a dotted column from it when another part has that column, and the JSON functions always work.
  • DECIMAL(p, s) comes from CAST (metadata numbers are int or float): exact, up to 18 digits.
  • TRUE and FALSE in SQL are the integers 1 and 0.

NULL

A missing key and a JSON null are both SQL NULL, distinct from 0 and ''.

  • Comparisons with NULL are unknown, and WHERE and HAVING keep only rows where the predicate is true. Use IS NULL and IS NOT NULL to test for it.
  • COUNT(*) counts rows; COUNT(x) and the other aggregates skip NULL. Over no rows (or only NULLs), COUNT(x) is 0 and SUM, AVG, MIN and MAX are NULL.
  • NULL grouping keys form one group.
  • A CASE with no matching branch and no ELSE is NULL.
  • Imported CSV treats empty fields as missing. NDJSON and Parquet keep NULL apart from empty strings.

Operators

OperatorMeaning
=, <>, !=, <, <=, >, >=Comparison
x IN (a, b, ...), x NOT IN (...)One of a list (or a subquery's values)
x BETWEEN a AND b, x NOT BETWEEN ...a <= x AND x <= b
x IS [NOT] DISTINCT FROM yEquality where NULL equals NULL
x ILIKE 'pattern'LIKE ignoring case
x LIKE 'pattern' [ESCAPE 'c'], x NOT LIKE ...Pattern match on text
x IS NULL, x IS NOT NULLMissing or null
AND, OR, NOT, ( )Logic, with SQL's three-valued results
a + b, a - b, a * bArithmetic on numbers (on DECIMALs, exact)
a / bDivision, always a float; NULL when b is 0
a // b, a % bInteger division (toward zero; of a float, as /) and remainder; NULL when b is 0
a || bText joined (NULL if either is)
j -> 'path', j ->> 'path'A JSON value's part: as JSON (->) or as text (->>); see JSON
date + INTERVAL '7 days', date - date, date + 3Dates and times: an interval (second to year, by the calendar for months), days between dates (seconds between times), days added
  • Like with like. Text compares with text and numbers with numbers; mixing them is an error, never an empty answer. Quote numbers that are stored as text: code = '42'.
  • Dates and times compare with strings that read as one: placed_at >= '2026-10-01', or with DATE '2026-10-01' / TIMESTAMP '2026-10-01 12:00:00'.
  • LIKE: % matches any sequence, _ exactly one character (newline included). Without ESCAPE, a backslash is an ordinary character; with ESCAPE '!', 'a!_b' matches the literal a_b.

Functions

Aggregates

FunctionReturns
COUNT(*)Rows
COUNT(x)Rows where x isn't NULL
COUNT(DISTINCT x)Distinct non-null values of x
SUM(x)Sum of a number column (int for int, DECIMAL for DECIMAL, exact; else float)
AVG(x)Average, as float (of a DECIMAL: its exact sum divided once)
MIN(x), MAX(x)Smallest and largest value, of x's type (numbers, text, dates)
COUNT_IF(p)Rows where p is true
STDDEV(x) / STDDEV_SAMP, STDDEV_POP, VARIANCE(x) / VAR_SAMP, VAR_POPSpread, as float
MEDIAN(x), QUANTILE(x, p) / QUANTILE_CONT, PERCENTILE_CONT(p) WITHIN GROUP (ORDER BY x)Interpolated percentile (_DISC: the nearest value)
MODE(x)The most frequent value
STRING_AGG(x, ',' [ORDER BY y]) (also GROUP_CONCAT, LISTAGG)Text joined
ARG_MAX(x, y), ARG_MIN(x, y) (also MAX_BY, MIN_BY)x where y is largest / smallest
BOOL_AND(p), BOOL_OR(p)Whether all / any are true
ANY_VALUE(x), FIRST(x), LAST(x)A value of the group
CORR(y, x), COVAR_POP, COVAR_SAMP, REGR_SLOPE, REGR_INTERCEPTCorrelation and regression
GROUPING(a, ...)With ROLLUP / CUBE / GROUPING SETS: a bit a key, 1 where it isn't grouped on

SUM(DISTINCT x) and AVG(DISTINCT x) work too, and any aggregate takes FILTER (WHERE p): SUM(amount) FILTER (WHERE status = 'paid'). An aggregate can't hold another, but expressions of aggregates can (SUM(a) / COUNT(*)).

sql
SELECT tool, COUNT(*) AS calls, COUNT(DISTINCT agent) AS agents, AVG(latency_ms) AS avg_ms, MAX(latency_ms) AS max_ms
FROM docs GROUP BY tool ORDER BY calls DESC

Scalar functions

FunctionReturns
CASE WHEN p THEN a [WHEN ...] [ELSE b] END, CASE x WHEN v THEN a ... ENDThe first branch whose predicate is true
COALESCE(a, b, ...) (also IFNULL), NULLIF(a, b), IF(p, a, b)NULL handling
CAST(x AS type), x::type, TRY_CAST(x AS type)x as BIGINT, DOUBLE, DECIMAL(p, s), VARCHAR, DATE or TIMESTAMP (TRY_CAST: NULL when it doesn't read as one)
LENGTH(x) (also STRLEN, OCTET_LENGTH)The length of a text in bytes (UTF-8)
CHAR_LENGTH(x)The length in characters
LOWER, UPPER, TRIM / LTRIM / RTRIM, REVERSE, REPEAT(x, n), LPAD / RPAD(x, n [, fill])Text
SUBSTRING(x, start [, len]) (also SUBSTRING(x FROM a FOR b)), LEFT(x, n), RIGHT(x, n)Part of a text, by characters from 1
CONCAT(a, ...) (skips NULLs), CONCAT_WS(sep, ...), REPLACE(x, from, to), SPLIT_PART(x, sep, n)Text
STRPOS(x, s) / POSITION(s IN x), STARTS_WITH(x, s), ENDS_WITH(x, s)Where or whether s is in x
REGEXP_MATCHES(x, 're'), REGEXP_EXTRACT(x, 're' [, group]), REGEXP_REPLACE(x, 're', 'rep' [, flags])RE2 patterns (REGEXP_REPLACE replaces every match; \1 is a group)
ABS, SIGN, ROUND(x [, d]), TRUNC, FLOOR, CEIL, SQRT, POWER(x, y), EXP, LN, LOG10, LOG2, GREATEST(...), LEAST(...)Numbers
EXTRACT(unit FROM x) (also DATE_PART('unit', x), YEAR(x), MONTH(x), ...)year, quarter, month, week, day, dow, doy, hour, minute, second, epoch of a date or time
DATE_TRUNC('unit', x)x rounded down to second ... year: a date stays a date; a time or integer seconds since 1970 gives a time
DATE_DIFF('unit', a, b)Whole units from a to b
DATE_ADD(x, INTERVAL ...), TO_TIMESTAMP(seconds), MAKE_DATE(y, m, d), STRFTIME(x, '%Y-%m-%d')Dates and times
CURRENT_DATE, CURRENT_TIMESTAMP / NOW()Today, now (UTC)
sql
-- an hourly series over integer-second timestamps
SELECT DATE_TRUNC('hour', ts) AS hour, COUNT(*) AS calls,
       SUM(CASE WHEN ok = 0 THEN 1 ELSE 0 END) AS errors
FROM docs WHERE ts >= 1760572800 GROUP BY hour ORDER BY hour

-- a URL's host, and a default for a missing key
SELECT REGEXP_REPLACE(url, '^https?://([^/]+).*$', '\1') AS host, COALESCE(plan, 'free') AS plan, COUNT(*)
FROM docs GROUP BY host, plan

JSON

Arrays and nested objects in meta are text columns of JSON (an object's keys are columns too); these read them, as DuckDB's JSON functions do. A path is '$.a.b[0]' ('$."a.b"' for a key with a dot), a plain key 'a', or an index.

FunctionReturns
json_extract(j, path), j -> pathThe value at path, as JSON text (NULL when there's none)
json_extract_string(j, path) (also json_value), j ->> path... as text: a string without its quotes, a number as written
json_array_length(j [, path])Elements of the array (0: not an array)
json_type(j [, path])OBJECT, ARRAY, VARCHAR, BIGINT, DOUBLE, BOOLEAN or NULL
json_valid(j)Whether j is JSON
list_contains(arr, v) (also array_contains, list_has)Whether the JSON array holds v
UNNEST(arr) in FROMA row an element (see Joins)
sql
SELECT tag, COUNT(*) FROM docs, UNNEST(tags) AS t(tag) GROUP BY tag ORDER BY 2 DESC
SELECT id FROM docs WHERE list_contains(tags, 'urgent') AND user.plan = 'pro'
SELECT payload ->> '$.items[0].sku' AS first_sku, COUNT(*) FROM docs GROUP BY 1

DECIMAL

CAST(x AS DECIMAL(p, s)) makes exact numbers (p digits, s after the point; DECIMAL alone is DECIMAL(18, 3)), rounded half away from zero. +, -, * and % are exact (+ and - keep the larger scale, * adds the scales); / gives a float; with an integer a decimal stays one, with a float it's a float. A literal written with a point next to a decimal is read exactly (price + 0.05). SUM is exact, MIN / MAX keep the type, AVG divides the exact sum once. At most 18 digits: a value or result past that is a 422, so CAST to DOUBLE for bigger numbers. Answers carry decimals as strings ("10.30"), so no digit is lost in JSON.

Note DATE_TRUNC refuses text: CAST it, or better, store times as integer seconds ("ts": 1760572800) in meta, or import a CSV column of YYYY-MM-DD HH:MM:SS, which becomes a time column.

Text predicates

Two functions reach a document's text from WHERE, through the same index search uses:

PredicateMatches
contains(text, 'words')Documents whose text contains the string: literal, ignoring case (as search's q)
grep(text, 'regex')Documents whose text matches an RE2 pattern: case-sensitive unless it starts with (?i) (as search with "regex": true)

They combine with anything else in WHERE (AND, OR, NOT) about the same table, up to 8 a table. Blocks of documents with no match are skipped before any column is read. In a query of several tables, name the table: contains(t.text, 'refund'); a text predicate can't be combined with OR across tables or used outside WHERE and ON.

sql
SELECT agent, COUNT(*) AS n FROM docs
WHERE grep(text, 'E5[0-9]{2}') AND ts >= 1760572800
GROUP BY agent ORDER BY n DESC

The answer

json
{"namespace": "support", "columns": ["status", "n"], "types": ["text", "int"], "rows": [["open", 2], ["closed", 1]],
 "chunks": 2, "scanned": 2, "partial": false, "truncated": false, "took_ms": 0.9,
 "temperature": "warm", "store_gets": 0, "store_bytes": 0, "cpu_ms": 0.4, "timed_out": false}
FieldWhat
columns, typesThe result's column names and types (int, float, text, date, time, decimal)
rowsThe rows, numbers as JSON numbers and SQL NULL as null
chunks, scannedColumn blocks in the namespaces read, and how many the query read
truncatedMore than 10,000 rows: these are the first 10,000
partialKept for compatibility: a query that can't read all its data fails instead
took_ms, temperature, store_gets, store_bytes, cpu_msWhat the query cost, as every query reports it

Replaced and deleted documents never count.

Views and partials

A query over one namespace whose aggregates merge from parts (COUNT, SUM, MIN, MAX, AVG, COUNT(DISTINCT ...), COUNT_IF, FILTER (WHERE ...); any WHERE; GROUP BY any expressions) runs as a part per segment and a merge, and the segments' parts are kept: asking it again computes only the segments written since. A view (POST /v1/namespaces/{name}/views) keeps such a query by name, readable as a table in any query: SELECT * FROM daily_signups, or a join. Queries repeated often on big namespaces become automatic views. Answers are always exact: a segment's part is used only while that segment's visible rows are the ones it was computed from. See Views. Integer sums, counts, minimums and maximums are the same as a query run whole; a SUM or AVG of floats adds the segments' compensated sums, so it can differ from the whole query's in the last digits.

Such an answer has a partials field:

FieldWhat
partials.viewThe named view read (several: comma-separated), or null
partials.kindnamed, auto (an automatic view) or none (parts kept in memory only)
partials.computed, partials.reusedSegments whose parts this query computed, and reused
partials.remoteOf those computed, how many other servers of the cluster computed

A view's query that can't run from parts is refused with 422 view_not_decomposable and the reason; a plan's views past its limit, 402 view_limit.

Streamed answers

A JSON answer stops at 10,000 rows. For more, ask for the rows streamed: ?format=ndjson or ?format=csv (or "format" in the body, or Accept: application/x-ndjson / text/csv). Rows go out as they're made, with no row cap, under the same time limit; the columns' types come in the X-Skimmerdb-Types header.

curl -sN "$B/sql?format=ndjson" -H "Authorization: Bearer $KEY" \
  -d '{"sql": "SELECT id, status, amount FROM orders WHERE amount > 100"}'
# {"id":"o-1","status":"paid","amount":120.5}
# {"id":"o-7","status":"open","amount":310.0}
for row in db.sql_rows("SELECT id, status, amount FROM orders WHERE amount > 100"):
    print(row["id"], row["amount"])
for await (const row of db.sqlRows("SELECT id, status, amount FROM orders WHERE amount > 100")) {
  console.log(row.id, row.amount);
}
  • NDJSON is one JSON object a row ({"column": value}, NULL as null). CSV is a header line, then a line a row (RFC 4180): NULL is an empty field, an empty text is "".
  • A plain scan of one namespace (SELECT columns or expressions FROM ns [WHERE ...]: no GROUP BY, aggregate, DISTINCT, ORDER BY, LIMIT, window or subquery) streams any number of rows, a block of the namespace at a time, so memory stays flat. Other shapes (joins, GROUP BY, ORDER BY, ...) are computed first and then streamed, up to a cap of rows held (at least 1,000,000); past it the stream ends with a too_many_rows error.
  • An error before the first row is the usual JSON error with its status. After it, NDJSON gets a last line {"error": "...", "code": "..."} and the transfer is broken off (CSV is only broken off), so a cut answer never looks whole.
  • Metering. One query, like the JSON answer; its bytes count as bytes returned as they're sent, and on the free plan a stream stops (out_budget) when they're used up.

For answers too big or too slow for one request, export them: see Exporting answers.

Writing with SQL

With a write key, the same endpoints (and the MCP tool sql_query) take statements that write:

sql
INSERT INTO ns [(column, ...)] VALUES (value, ...), ...
INSERT INTO ns [(column, ...)] SELECT ... | WITH ...
CREATE TABLE ns AS SELECT ...
DELETE FROM ns [[AS] alias] [WHERE predicate]
  • A row is a document. Its id column names it: an id that exists is replaced, as with every write (without an id column, ids are made). Its text column is its text (searchable; not a column afterwards). Every other column is metadata, stored as typed columns, as an import's.
  • INSERT into a namespace that doesn't exist makes it (text only), like a write. A column list renames the query's columns (as many); VALUES without one takes the namespace's columns in SHOW COLUMNS order. VALUES takes literals: numbers, 'text', NULL, TRUE / FALSE, DATE '2026-10-01', TIMESTAMP '2026-10-01 12:00:00'.
  • CREATE TABLE ns AS makes a new namespace (409 when one has the name) from a query's rows.
  • DELETE removes the documents its WHERE finds (any predicate: text, subqueries, other namespaces).
  • Atomic: each statement is one commit through the write log: all its rows become visible together, or none (a failure writes nothing). A DELETE deletes all it found in one write. Not atomic: reading and writing are two steps (a document written between them is neither seen nor kept out), and CREATE TABLE makes its namespace first (dropped again if the write fails).
  • The answer is a SQL answer with one row (inserted or deleted) and dml: {"statement", "namespace", "inserted", "deleted", "version", "created"}.
  • Scope and limits. A read key gets 403 (REST and MCP). Linked namespaces refuse writes (409); vector namespaces take their documents through writes, not SQL. A statement is metered as writes (each document inserted or deleted, and the bytes) plus one query when it reads; on the free plan a statement that would pass the writes left this month is refused whole (402).
curl
curl -s $B/sql -H "Authorization: Bearer $KEY" \
  -d '{"sql": "INSERT INTO big_orders SELECT id, customer, amount FROM orders WHERE amount > 1000"}'
# {"columns": ["inserted"], "rows": [[1832]], ..., "dml": {"statement": "insert", "namespace": "big_orders", "inserted": 1832, "deleted": 0, "version": 3, "created": true}}

Limits

FreePro
Time limit a query10 s30 s
SQL queries running at once, per tenant (per server)28
Rows in a JSON answer10,00010,000
Rows in a streamed answer: a plain scan / other shapesany / at least 1,000,000any / at least 1,000,000
Time limit of a SQL write (INSERT ... SELECT, CREATE TABLE AS, DELETE) and of an export60 s900 s
Rows a SQL write: INSERT / DELETE20,000,000 / 1,000,000 (and the plan's writes left)20,000,000 / 1,000,000
An INSERT ... VALUES statement8 MB8 MB
Text predicates a table88
Tables a query (namespaces and WITH uses)1616
Rounds of a WITH RECURSIVE10,00010,000
  • Memory. A query's groups, distinct values, rows in flight and reads from object storage are capped by a share of the server's memory. Past a cap the query stops with a 422 (or a 413 for reads, refused before anything is read). It never takes the server down.
  • Metering. A SQL query is one query, metered and rate-limited like a search, however many namespaces it reads; its store_gets and store_bytes are all of theirs. See Limits and plans.

Errors

StatusWhen
422 invalidThe SQL is wrong: the message says why (no column x, expected FROM, a text compared with a number, ...)
422 query_timeoutPast the plan's time limit
413 too_largeThe query would read more than its share of memory
429 rate_limitedThe tenant has its plan's SQL queries running already: retry shortly
403 forbiddenA write with a read key
409 conflictCREATE TABLE of a namespace that exists; a write to a linked namespace
402 payment_requiredA write past the free plan's writes left this month (nothing written)
503 unavailableThe query couldn't read its data: retry

Not supported yet

MissingInstead
A correlated subquery with UNION / INTERSECT / EXCEPT inside, or in a JOIN's ONPut the set operation in a WITH query; move the subquery to WHERE
DECIMAL past 18 digitsDOUBLE (float)
Typed arrays and maps ([1, 2], MAP), UNNEST in the select listJSON arrays in meta with UNNEST in FROM, list_contains and the JSON functions
UPDATE, MERGE, DROP TABLEINSERT ... SELECT the rows with the same ids (they're replaced), or PATCH .../docs; DELETE /v1/namespaces/{name}