Reference›SQL Reference

SQL Reference

Hotdata's native SQL is HotSQL: standard SQL with extensions for analytics, time-series, and complex types. If you know Postgres, you already know most of it.

You can also write queries in PostgreSQL, DuckDB, Snowflake, or ClickHouse syntax (see SQL dialects).

SQL dialects

Hotdata accepts queries in five SQL dialects:

  • HotSQL (the native dialect)
  • PostgreSQL
  • DuckDB
  • Snowflake
  • ClickHouse

Set the dialect field on the query request to use another dialect. Hotdata translates it to HotSQL before running, so queries written for another engine run without a rewrite.

Write statements follow the same rules in every dialect (see Writing data with SQL). An unrecognized dialect is rejected.

dialectDialect
hotsql (default)HotSQL
postgresPostgreSQL
duckdbDuckDB
snowflakeSnowflake
clickhouseClickHouse
{
  "sql": "SELECT IFF(amount > 100, 'big', 'small') AS bucket FROM orders",
  "dialect": "snowflake"
}

SELECT syntax

Standard SELECT is supported:

  • WITH (CTEs)
  • INNER, LEFT, RIGHT, FULL and CROSS joins
  • GROUP BY and HAVING
  • ORDER BY, LIMIT and OFFSET
  • UNION and UNION ALL
  • Subqueries in SELECT, FROM, WHERE and HAVING

Reference tables as catalog.schema.table or schema.table:

SELECT o.id, c.name
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.created_at >= '2025-01-01';

Data types

Standard SQL types are supported:

CategoryTypes
NumericTINYINT, SMALLINT, INT, INTEGER, BIGINT, DECIMAL, FLOAT, DOUBLE, REAL
CharacterCHAR, VARCHAR, STRING
Date/TimeDATE, TIME, TIMESTAMP, INTERVAL
BooleanBOOLEAN
BinaryBYTEA
ComplexARRAY, STRUCT, MAP

BINARY, VARBINARY, and BLOB are not accepted as cast targets. For binary data use BYTEA, or arrow_cast(x, 'Binary') and decode(x, 'hex').

Operators

The standard comparison, logical and arithmetic operators are supported, with % for modulo and || for string concatenation.

Bitwise operators are &, |, ^ (XOR), << and >>. There is no bitwise-NOT operator: ~ is not supported, and there is no bit_not function to stand in for it.

Functions

HotSQL includes a comprehensive function library. Each category has a dedicated reference with signatures, arguments, and runnable examples:

Aggregates: FILTER and WITHIN GROUP

Aggregates accept a FILTER (WHERE ...) clause, and ordered-set aggregates (percentile_cont, approx_percentile_cont) accept WITHIN GROUP (ORDER BY ...):

SELECT
  sum(amount) FILTER (WHERE status = 'completed')       AS completed_revenue,
  percentile_cont(0.5) WITHIN GROUP (ORDER BY latency)  AS median_latency
FROM orders;

Window functions

Any aggregate or window function runs over a frame with OVER (PARTITION BY ... ORDER BY ...):

SELECT id, amount,
  sum(amount) OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS running_total,
  rank()      OVER (ORDER BY amount DESC)                                          AS amount_rank
FROM transactions;

Expanding arrays

unnest(array) expands an array into rows:

SELECT id, unnest(tags) AS tag FROM articles;

Geospatial functions

Hotdata's spatial functions follow PostGIS-style ST_ naming.

  • Geometries are planar (Cartesian). There is no geography type, and x is always easting/longitude.
  • Buffering and overlay operations are available: ST_Buffer, ST_Union, ST_Intersection, ST_Difference, ST_MakeValid, and others.
  • ST_Transform reprojects coordinates.
  • For geodesic measurements in metres on lon/lat data, use the _Spheroid family (ST_Area_Spheroid, ST_Distance_Spheroid, ST_DWithin_Spheroid, ...) or ST_DistanceSphere.

Spatial relationships

Test how geometries relate to each other:

-- Find stores within 10 km of a point (ST_DistanceSphere returns metres)
SELECT id, name
FROM stores
WHERE ST_DistanceSphere(
  ST_GeomFromText('POINT(-122.4194 37.7749)'),
  location
) < 10000;

-- Points contained in a polygon (e.g. delivery zones)
SELECT order_id, ST_AsText(destination)
FROM orders
WHERE ST_Within(destination, delivery_zone);

-- Intersecting geometries (e.g. overlapping regions)
SELECT a.id, b.id
FROM regions a
JOIN regions b ON ST_Intersects(a.geom, b.geom) AND a.id < b.id;

ST_Distance and ST_DWithin are planar—distances in the coordinates' own units (degrees for lon/lat data). For metres on lon/lat data use ST_DistanceSphere (great-circle) or ST_Distance_Spheroid / ST_DWithin_Spheroid (WGS84 geodesic).

Coordinate reprojection

ST_Transform reprojects between coordinate reference systems. The CRS travels in the call (there is no per-geometry SRID); coordinates are always x = easting/longitude:

-- lon/lat (EPSG:4326) to Web Mercator metres (EPSG:3857)
SELECT ST_Transform(location, 'EPSG:4326', 'EPSG:3857') AS mercator
FROM stores;

Alternate spellings from other SQL dialects are accepted as aliases, for example ST_Distance_Sphere for ST_DistanceSphere.

See the Spatial functions reference for all 117 functions, and the PostGIS documentation for the semantics of each.

Hotdata provides two kinds of vector search:

  • Semantic search on text columns, using an embedding provider.
  • Direct vector search on pre-computed embedding columns.

The search table functions always use the column's HNSW index: vector_search for text and vector_search_vector for a query vector. They do not read an IVF index.

See the Vector functions reference for every vector function on one page, including the vec_sum and vec_avg aggregates.

Semantic search with vector_distance

vector_distance(column, 'search text') is the simplest way to run a semantic search. It takes a text column and a search string, then:

  1. Generates an embedding with the column's embedding provider.
  2. Computes the distance with the metric defined in the vector index.
SELECT id, title, vector_distance(description, 'machine learning frameworks') AS dist
FROM conn.public.articles
ORDER BY dist ASC
LIMIT 10;

Requirements:

  • A vector index on the column with an embedding provider configured
  • The column must be a text column (VARCHAR / TEXT)

You don't need to know which distance metric or embedding column is used—the index configuration handles it.

vector_distance behaves like an ordinary distance function, so whether the index is used depends on the conditions under distance functions. Use vector_search for a semantic search that always uses the index.

Distance functions

For direct control over vector search—when you already have embedding vectors or want to specify the exact distance metric—use the distance functions directly on vector columns. All are lower-is-closer; use ORDER BY ... ASC:

SQL functionMetricUse case
l2_distance(column, query)L2 squared (L2sq)General-purpose distance
cosine_distance(column, query)CosineAngle between vectors (normalized embeddings)
negative_dot_product(column, query)Inner productMaximum inner product search

l2_distance returns the squared Euclidean distance, matching the metric the index is built on. Ranking is unaffected, but a threshold is: WHERE l2_distance(a, b) < 0.5 is a radius of 0.707. For the unsquared distance use array_distance.

All three return Float32, so compare against a tolerance rather than an exact value.

These functions accept a vector column and a literal query vector (ARRAY[...]):

SELECT id, title, cosine_distance(embedding, ARRAY[0.1, -0.2, 0.5, ...]) AS dist
FROM documents
ORDER BY dist ASC
LIMIT 10;

These functions scan every row by default. With a vector index, HNSW or IVF, ORDER BY distance_fn(col, ARRAY[...]) ASC LIMIT k uses the index. These shapes run as an exact scan instead, without a warning:

  • The query vector is not a literal ARRAY[...], for example a column, a parameter, a subquery, or a CTE.
  • A cast literal is in another position. ARRAY[1, 2, 3]::FLOAT[] uses the index only when the distance call is the ORDER BY key, or a SELECT item with an alias that the ORDER BY names.
  • The indexed vector column is in the output, by name or through SELECT *. Select the distance and the other columns you need instead.
  • ORDER BY ... DESC. An index answers nearest-first, so only ascending order is a match.
  • The distance function does not match the index's metric, for example cosine_distance against an l2 index.

Missing the rewrite makes a query slower, never wrong. Check with EXPLAIN when it matters.

For a guaranteed HNSW index lookup, use vector_search_vector, or vector_search for text.

The table functions read HNSW indexes only. To search a column with an IVF index, use the distance functions.

vector_search table function

vector_search is a table function for semantic search that returns full rows. Like vector_distance, it auto-embeds your search text using the configured embedding provider — but returns results as a table you can query directly.

vector_search('catalog.schema.table', 'column', 'search text', k)
ParameterTypeDescription
tablestring literalFully-qualified table name: 'catalog.schema.table'
columnstring literalText column with a vector index and embedding provider
querystring literalSearch text to embed and search for
kintegerNumber of nearest neighbors to return

Returns the table's columns plus a _distance column (Float32). Lower distance means more similar.

Two details of the returned shape are worth knowing before you write SELECT * against it:

  • The result carries an internal rowid column ahead of the table's own columns. List the columns you want instead of using SELECT *.
  • The indexed embedding column cannot be selected. SELECT description_embedding FROM vector_search(...) fails with an unknown-field error. Select the source text column instead.

Requirements: A vector index on the column with an embedding provider configured.

-- Semantic search returning full rows
SELECT id, title, _distance
FROM vector_search('mydb.public.articles', 'description', 'machine learning', 10)
ORDER BY _distance ASC;
-- With filtering and aggregation
SELECT category, COUNT(*) AS cnt, AVG(_distance) AS avg_dist
FROM vector_search('mydb.public.articles', 'description', 'data science', 50)
WHERE category IN ('ml', 'statistics')
GROUP BY category
ORDER BY avg_dist;

vector_search_vector table function

vector_search_vector is the direct ANN search table function — you provide the query vector yourself. It requires a vector index but no embedding provider.

vector_search_vector('catalog.schema.table', 'column', ARRAY[...], k)
ParameterTypeDescription
tablestring literalFully-qualified table name: 'catalog.schema.table'
columnstring literalVector column with a HNSW index
queryARRAY[...] literalQuery vector
kintegerNumber of nearest neighbors to return

Returns all table columns plus a _distance column (Float32).

Requirements: A vector index on the column.

SELECT id, title, _distance
FROM vector_search_vector('mydb.public.documents', 'embedding', ARRAY[0.1, -0.2, 0.5, ...], 10)
ORDER BY _distance ASC;

Choosing between vector search methods

MethodInputRequires embedding providerRequires indexUses the indexReturns
vector_search('table', 'col', 'text', k)textyesyes (HNSW)alwaystable (see returned shape)
vector_search_vector('table', 'col', ARRAY, k)vectornoyes (HNSW)alwaystable (see returned shape)
vector_distance(col, 'text')textyesyes (for the provider and metric)only if rewrittenscalar (Float32) — use in SELECT/ORDER BY
l2_distance / cosine_distance / negative_dot_productvectornonoonly if rewrittenscalar (Float32) — use in SELECT/ORDER BY
  • Table functions guarantee an index scan, on an HNSW index only. Prefer one on a large table.
  • Scalar distance functions reach the index only when the query meets every condition under Distance functions. Prefer one when you want a distance in the output, the table is small, or there is no index.

WHERE clause filtering

This applies to queries that run through an HNSW index: the two search table functions, and a distance-function query that uses the index. For IVF, see IVF indexes.

  • Scalar WHERE conditions are applied during the search, so the query still returns k results.
  • A filter that matches few rows runs as an exact search over the matching rows instead.
SELECT id, title, cosine_distance(embedding, ARRAY[...]) AS dist
FROM documents
WHERE category = 'technical'
ORDER BY dist ASC
LIMIT 10;

Behavior and limitations

  • SELECT * with distance functions: when the table has generated embedding columns, SELECT * expands to include them, so the query falls back to brute force (see distance functions for the shapes that are never rewritten).
  • Rewriting is an optimization, not a guarantee: a query that misses a rewrite condition is slow, not wrong. Use vector_search / vector_search_vector when the index lookup is what you need.

Hotdata provides BM25 full-text search via the bm25_search table function. It performs ranked text retrieval against a column with a BM25 index.

bm25_search('catalog.schema.table', 'column', 'query text' [, limit])
ParameterTypeDescription
tablestring literalFully-qualified table name: 'catalog.schema.table'
columnstring literalText column to search
querystring literalSearch query text
limitinteger (optional)Maximum results to return. Default: 1000

Returns all columns from the base table plus a score column (Float32) containing the BM25 relevance score. Higher scores indicate stronger relevance. Rows are not returned in score order—add an explicit ORDER BY score DESC to rank them.

Requirements: A BM25 index on the target column.

-- Search articles for "machine learning", return top 20 by relevance
SELECT id, title, body, score
FROM bm25_search('mydb.public.articles', 'body', 'machine learning', 20)
ORDER BY score DESC;
-- Combine full-text search with additional filters
SELECT id, title, score
FROM bm25_search('conn.public.docs', 'content', 'kubernetes deployment', 100)
WHERE category = 'infrastructure'
ORDER BY score DESC
LIMIT 10;

How text is analyzed

A BM25 index stores tokens, and a document is findable only by a token it produced.

  • Text is split on every non-alphanumeric character.
  • Tokens are lowercased.
  • Any token over 40 bytes is dropped.

Queries are analyzed the same way, so the two always agree.

Nothing else is applied: no stemming (run misses running), no accent folding (cafe misses café), and no camel-case splitting (mixed misses MixedCaseWord).

Chinese, Japanese, Korean and Thai are not usable today. They have no spaces or punctuation to split on, so a whole run of text becomes one token and only the exact full string matches.

To search these scripts, insert word boundaries yourself before loading and index that column.

Managed table layout

Instant database tables can declare a storage layout: how their rows are partitioned and sorted on disk.

  • It is set when the table is created, through the managed table API.
  • It cannot be changed afterward.
  • It is not set from SQL.

A layout has two parts:

  • Partitioning — one or more partition keys, each a column plus a transform: identity, year, month, day, or hour.
    • Transforms compose: partitioning by year(ts) and month(ts) places each calendar month in its own partition.
    • A WHERE filter on a partition column lets the planner skip whole partitions.
  • Sort order — one or more sort keys (a column plus optional asc / desc and null ordering). Rows are written in this order, so range filters on the sort keys can prune row groups.

The layout also organizes data for key-based mutations (upsert, update, delete) on partitioned tables.

It complements sorted indexes: a sorted index is a secondary, pre-sorted copy of cached data, and the layout governs the table's primary storage.

Indexes

Hotdata supports three index types to accelerate different query patterns. Indexes are created via the API or CLI—not SQL. Indexes are built over instant-database tables, so load the data first (upload parquet or run an ingest).

CLI (instant-database tables): hotdata search create --type text|vector|sorted --from <catalog>.<schema>.<table> --column <col>

Indexes are stored in the catalog and used automatically when the query planner finds a beneficial match. Use GET .../indexes to list indexes and DELETE .../indexes/{index_name} to drop one.

Sorted indexes

Pre-sorted Parquet copies of cached data, ordered by the columns you specify. Accelerate range queries, ordering, and point lookups.

{
  "index_name": "idx_created_at",
  "columns": ["created_at"],
  "index_type": "sorted"
}

A sorted index is used for one thing: a WHERE filter on the index's leading sort column, where sorted Parquet lets the planner prune row groups. Range and equality filters both benefit.

-- Index on created_at: row-group pruning for the range filter
SELECT * FROM events
WHERE created_at >= '2025-01-01' AND created_at < '2025-02-01';

-- Index on created_at: also pruned, an equality filter is a degenerate range
SELECT * FROM events WHERE created_at = '2025-01-15';

An ORDER BY on its own does not select the index, so SELECT * FROM products ORDER BY sku LIMIT 100 still sorts.

Vector indexes

HNSW indexes for approximate nearest-neighbor search on vector columns, or IVF indexes with "algorithm": "ivf" (see IVF indexes). Require exactly one column.

On a pre-computed embedding column (float array):

{
  "index_name": "docs_embedding_idx",
  "columns": ["embedding"],
  "index_type": "vector",
  "metric": "cosine"
}

On a text column with auto-embedding: when the source column is text, Hotdata automatically generates embeddings using an embedding provider. This enables vector_distance() for semantic search.

If you omit embedding_provider_id, the system embedding provider is used automatically. If no system provider is configured, you must pass one explicitly. The metric also defaults to the provider's configured metric when not specified.

{
  "index_name": "docs_description_idx",
  "columns": ["description"],
  "index_type": "vector"
}

Or with explicit provider and metric:

{
  "index_name": "docs_description_idx",
  "columns": ["description"],
  "index_type": "vector",
  "metric": "cosine",
  "embedding_provider_id": "embp_abc123",
  "dimensions": 1536
}

The embedding provider generates a new column (default: {column}_embedding) containing the vector embeddings. Configure embedding providers via the Embedding Providers API.

An auto-embedding vector index must be the only index on its table.

  • Creating one is rejected if the table already has an index.
  • Once it exists, no other index can be added.

To combine full-text and vector search over the same content, keep them on separate tables.

This restriction applies only to auto-embedding indexes. A vector index over a pre-computed embedding column generates nothing, so it coexists with full-text and sorted indexes as normal.

FieldRequiredDescription
algorithmnohnsw (default) or ivf. See IVF indexes
metricnoDistance metric: l2, cosine, or dot. Defaults to l2 for float array columns, or the provider's metric for text columns with auto-embedding
embedding_provider_idnoEmbedding provider ID. Defaults to the system provider for text columns
output_columnnoName for the generated embedding column. Default: {column}_embedding
dimensionsnoEmbedding dimensions (model-dependent)

CLI example:

hotdata search create --type vector --from mydb.public.documents \
  --column embedding --metric cosine

IVF indexes

Set "algorithm": "ivf" to build the index with IVF instead of HNSW. Choose ivf for a table too large to index with hnsw:

  • An hnsw search needs memory that grows with the table.
  • An ivf search reads only the clusters of vectors nearest the query.
  • An ivf index uses extra storage.
{
  "index_name": "docs_embedding_ivf",
  "columns": ["embedding"],
  "index_type": "vector",
  "algorithm": "ivf",
  "metric": "cosine",
  "async": true
}
hotdata search create --type vector --algorithm ivf --from mydb.public.documents \
  --column embedding --metric cosine --async

Every field is described under Create an index on a table. Query it the same way as HNSW: the distance functions in an ORDER BY ... LIMIT k, with or without a WHERE.

Columns

  • On a column that already holds vectors, ivf indexes it directly.
  • On a text column with an embedding provider, hotdata generates the embeddings into a new column and indexes that. Search it with vector_distance and the query text.

Options

  • metric: l2 or cosine. dot is rejected. An embedding provider's metric must also be l2 or cosine.
  • nlist: the number of clusters, from 1 to 65536. When omitted, it is chosen from the table's size.
  • probe_fraction: the share of clusters a search starts by reading, greater than 0 and at most 1. When omitted, hotdata chooses it.
  • vector_precision: int8 (the default for ivf) or float32.
    • float32 takes four times the space.
    • With int8, distances differ slightly from the exact distance, so two rows at nearly the same distance can come back in swapped order.

Accuracy

ivf searches are approximate, and the rarer a filter, the more a result can miss. Reading more clusters finds more of the true nearest neighbors, at higher latency. Measure on your own data.

A WHERE is applied during the search, so a filtered query returns k rows when at least k indexed rows match.

Set the search width on the index with probe_fraction, or per query with SET hotdata.ivf_probe_clusters = N; in front of the query, in the same SQL text:

SET hotdata.ivf_probe_clusters = 64;
SELECT id, cosine_distance(embedding, ARRAY[0.1, -0.2, 0.5, ...]) AS dist
FROM mydb.public.documents
ORDER BY dist
LIMIT 10;

N is a number of clusters, at least 1, capped at the index's cluster count. It applies to that query only.

When the index is not used

These queries run as an exact scan. In EXPLAIN, a query the index serves shows an IvfSearchExec node.

  • The query shapes that also skip an HNSW index.
  • A filter that fewer than k indexed rows match, or that cannot be evaluated inside the index. This scan also returns rows whose vector is NULL.
  • OFFSET after the LIMIT.

Limits

  • vector_search and vector_search_vector read hnsw indexes only. On a column with an ivf index they fail with an error that suggests the ORDER BY form.
  • A table can have only one vector index, whichever algorithm it uses.
  • An ivf index is not carried over to a forked database. Create it again on the fork.

Keeping the index current

Every load updates the index, but clusters are not rebalanced automatically. Rebuild the index when the table has grown far past its size at build time, or when new data is distributed differently from the data it was built on.

To rebuild, drop the index and create it again. Queries on the column run as an exact scan until the new index is ready.

BM25 indexes

Full-text search indexes using BM25 scoring. Required for bm25_search(). The index stores analyzed tokens — see how text is analyzed for what is and is not matchable.

{
  "index_name": "articles_body_idx",
  "columns": ["body"],
  "index_type": "bm25"
}

CLI example:

hotdata search create --type text --from mydb.public.articles \
  --column body

Point lookups

Queries that fetch a single row by equality (WHERE col = value with LIMIT 1) are classified as point lookups. Parquet bloom filter reads skip row groups that cannot contain the value, reducing I/O.

SELECT * FROM users WHERE id = 12345;

Index lifecycle

Every load into a table keeps its indexes current, in every load mode. If an index cannot be updated, drop it and create it again.

Writing data with SQL

The query endpoint runs a small set of write statements against the database's own tables. Each one runs once, inline, and answers with a one-row result holding a single rows_affected column.

StatementWhat it does
INSERT INTO t [(cols)] VALUES … / INSERT INTO t [(cols)] SELECT …Appends rows. Columns left out of the list are NULL; every value is cast to its column's type.
CREATE TABLE t (col TYPE, …)Declares an empty table. IF NOT EXISTS is accepted.
CREATE TABLE t AS SELECT …Declares a table and loads it with the query's rows.
DROP TABLE [IF EXISTS] tRemoves the table and its indexes.
CREATE TABLE events (id BIGINT, kind TEXT, at TIMESTAMP);
INSERT INTO events (id, kind, at) VALUES (1, 'signup', '2026-01-01T00:00:00');
INSERT INTO events SELECT id, 'import', now() FROM staging.rows;
DROP TABLE IF EXISTS staging.rows;

Rules that apply to every write:

  • Who can write. The API key must hold both the read and write permissions. A saved query never runs a write, whoever executes it.
  • Where you can write. Only the database's own default catalog. Attached catalogs are other databases' data and stay read-only.
  • Each INSERT is a publish, like an append load. Batch rows into one statement instead of inserting them one at a time. For large volumes, use the load endpoint.
  • Append only. INSERT OVERWRITE, INSERT OR REPLACE, ON CONFLICT and RETURNING are refused. A table with an embedding index must be inserted into with an explicit column list that leaves the generated vector column out.
  • Every column is nullable. NOT NULL, DEFAULT, PRIMARY KEY, UNIQUE and OR REPLACE on CREATE TABLE are refused rather than silently ignored. Table layout (partition_by, sorted_by, a key) is declared through the tables API, not in SQL.
  • UPDATE and DELETE are not supported yet. They are refused by name. Use the load endpoint's keyed update, delete and upsert modes instead.
  • Everything else that mutates is refused: ALTER, views, COPY, transaction control, and EXPLAIN or EXPLAIN ANALYZE of a write.

Information schema

Introspect the catalog by querying the information_schema views:

  • information_schema.tables — tables in scope
  • information_schema.columns — columns and their types
  • information_schema.schemata — schemas
  • information_schema.catalogs — catalogs
SELECT table_schema, table_name
FROM information_schema.tables
ORDER BY table_schema, table_name;

DESCRIBE table returns a single table's schema:

DESCRIBE conn.public.orders;
  • information_schema.views, routines, and parameters exist for tool compatibility but are empty.
  • SHOW TABLES and SHOW COLUMNS return rows.
  • SHOW FUNCTIONS is accepted but returns no rows. Use information_schema or DESCRIBE to inspect a table.

You can also list tables and schemas via the API or MCP.

EXPLAIN

Use EXPLAIN to inspect the query plan:

EXPLAIN SELECT * FROM orders WHERE created_at > '2025-01-01';

EXPLAIN ANALYZE runs the query and returns execution metrics (timing, rows, etc.). Because it executes the plan, a write wrapped in EXPLAIN or EXPLAIN ANALYZE is inspected and rejected rather than run.