Skip to content

Query files and annotations ​

A query file is any .sql file your code imports. In the simplest case, a file contains a single statement, and its filename becomes the exported function name—for example, src/book-by-isbn.sql exports bookByIsbn along with the types BookByIsbnParams and BookByIsbnRow:

sql
-- @one
SELECT isbn, title, price_cents FROM books WHERE isbn = :isbn

Every linked example on this page is a complete mini-project you can inspect, edit, and run in the browser playground. Try this one in one-statement.

How a .sql file becomes a typed TypeScript modulesrc/book-by-isbn.sql combined with sql.lock through hyper-sql's content mapper generates the function bookByIsbn plus flat BookByIsbnParams and BookByIsbnRow interfaces.src/book-by-isbn.sql-- @oneSELECT isbn, title, price_centsFROM booksWHERE isbn = :isbn@one → Row | undefined:isbn → ParamsSELECT → Rowhyper-sqlcontent mapper+ sql.lockImported TypeScript module (virtual)export interface BookByIsbnParams {isbn: string}export interface BookByIsbnRow {isbn: string; title: string;price_cents: number}export function bookByIsbn(db, p): BookByIsbnRow | undefined
A .sql file compiles into an importable TypeScript module with flat Params and Row interfaces.

Single vs. multiple statements ​

A single .sql file can also hold multiple statements. Start each one with -- @name x, which exports a function named x. Any annotations belong to the -- @name directly above them; putting SQL or an annotation before the first -- @name is an error. See named-statements.

Annotations ​

Annotations are SQL comments of the form -- @tag .... Every annotation must have a real effect—hyper-sql reports an error on unused or redundant annotations rather than silently ignoring them.

AnnotationMeaning
-- @oneReturns Row | undefined and throws if a second row is returned. Not allowed on INSERT, UPDATE, or DELETE (even single-row writes): for INSERT ... RETURNING, destructure the array with const [row] = f(db, {...}). Safe on a SELECT filtering by a unique key.
-- @manyReturns Row[] (the default for SELECT and RETURNING statements).
-- @execReturns { changes, lastInsertRowid } on SQLite or { changes } on Postgres (the default for write statements without RETURNING).
-- @param name: TSets the TypeScript type of a parameter that can't be inferred from a column.
-- @col name: TSets the TypeScript type of an output column that the database can't infer, or narrows away null (which the generated code then verifies at runtime on every row).
-- @import { A } from './x.ts'Imports a TypeScript type used by annotations in this file.

See one-and-many and annotations. For column-level -- @type annotations in schema.sql, see Types.

Annotation usage examples ​

Result and naming annotations (src/books.sql) — put multiple statements in one file with -- @name, and mark each statement's result shape explicitly:

sql
-- @name listBooks
-- @many
SELECT isbn, title, price_cents
FROM books
ORDER BY title

-- @name bookByIsbn
-- @one
SELECT isbn, title, price_cents
FROM books
WHERE isbn = :isbn

-- @name deleteBook
-- @exec
DELETE FROM books WHERE isbn = :isbn

Expression and parameter typing (src/shelf-values.sql) — add -- @col for computed expressions SQLite can't infer, and -- @param for parameters compared against an expression instead of a plain column:

sql
-- @col shelf_value: number
-- @param minValue: number
SELECT isbn, binding, price_cents * stock AS shelf_value
FROM books
WHERE price_cents * stock >= :minValue
ORDER BY isbn
LIMIT :limit

Importing custom or branded types (src/find-book.sql) — use -- @import when a -- @param or -- @col annotation references a type defined in a TypeScript file (if the column already has -- @type in schema.sql, queries inherit it without needing @import or @col):

sql
-- @import { Isbn } from './ids.ts'
-- @one
-- @param isbn: Isbn
-- @col isbn: Isbn
SELECT isbn, title
FROM books
WHERE isbn = :isbn

To apply a custom type, literal union, boolean, bigint, or JSON guard to a column across every query at once, use -- @type in schema.sql—see Overriding a single column.

Parameters ​

Write query parameters as :name (positional ? placeholders aren't allowed). Callers pass all parameters as a single object with matching keys. See parameters.

Postgres infers every parameter type on its own. On SQLite, a parameter usually inherits the type of the column it's compared against (such as col = :p), plus a few common patterns:

PatternInferred parameter type
LIMIT :n, OFFSET :nnumber
col BETWEEN :a AND :btype of col
col LIKE '%' || :p || '%'string
CAST(:p AS INTEGER)target type of the CAST
count(*) > :nnumber
(a, b) > (:c, :d)type of the corresponding column

If a parameter doesn't fit one of these patterns—or gets compared against two columns of different types—add a -- @param annotation. Common cases include:

  • OFFSET (:page - 1) * :size
  • x * 2 = :p

In INSERT ... SELECT, a parameter that stands alone as a select item inherits the type of the target column in that position. For instance, on SQLite, INSERT INTO post_tags (post_id, tag_id) SELECT :postId, value FROM json_each(:tagIds) types postId as number and tagIds as number[]. Because an INSERT's SELECT doesn't return rows, duplicate column names like SELECT p.id, t.id don't need aliases. See insert-select.

The optional-filter idiom (:p IS NULL OR col = :p) is typed automatically on SQLite, but Postgres can't determine the type of :p from :p IS NULL. When hyper-sql pull hits that error on Postgres, it suggests two alternatives: use an optional block (/*if :p*/ AND col = :p /*end*/) or add an explicit cast (:p::type).

To match against a list of values, use col = ANY(:list) on Postgres (any-list) or col IN (SELECT value FROM json_each(:list)) on SQLite (in-list). The same prepared statement works for a list of any length. Postgres array parameters—such as text[] columns, tags && :tags, or unnest(:ids::int8[])—are also typed automatically without annotations (array-params).

Inserting multiple rows ​

For a fixed number of rows, write multiple VALUES tuples with distinct parameters:

sql
INSERT INTO items (name, qty) VALUES (:firstName, :firstQty), (:secondName, :secondQty)

Each parameter picks up the type of its target column.

For a dynamic list of rows, turn an array parameter into rows inside INSERT ... SELECT:

  • SQLite: INSERT INTO items (name) SELECT value FROM json_each(:names) types names as string[].
  • Postgres: INSERT INTO items (name) SELECT unnest(:names::text[]) does the same. To insert multiple columns at once, pass parallel arrays: SELECT * FROM unnest(:names::text[], :qtys::int4[]).

Add RETURNING to get back a typed array of the inserted rows. See insert-many (SQLite) and insert-many (Postgres).

Nested rows with JSON ​

To fetch parent rows with nested child lists in a single query, build the child array as JSON directly in SQL. This query returns every user, including users with no posts:

sql
SELECT u.id,
       (SELECT json_group_array(json_object('id', p.id, 'title', p.title))
        FROM posts p WHERE p.user_id = u.id) AS posts
FROM users u

posts is automatically typed as { id: number; title: string }[] with no annotation required. On Postgres, use json_agg(json_build_object(...)) instead. You can also use these aggregates directly in a SELECT list with GROUP BY u.id instead of a correlated subquery. Every field is validated at runtime when rows are decoded.

Object keys must be string literals. Values that come directly from a column or literal inherit their schema type and nullability; arbitrary expressions (such as p.id + 1) are typed as unknown. ORDER BY inside the aggregate is supported.

When is the nested list nullable?

FormType
json_group_array(...) (SQLite)T[] (never NULL)
json_agg(...) (Postgres)T[] | null (NULL when no rows match)
coalesce(json_agg(...), '[]')T[]
json_agg(...) with GROUP BY and no FILTERT[] (unless GROUP BY uses ROLLUP, CUBE, GROUPING SETS, or ())
Subquery with GROUP BY, HAVING, LIMIT, or OFFSETT[] | null (may produce zero rows)

Subqueries that use UNION, WITH, NATURAL JOIN, or JOIN ... USING aren't inferred: they fall back to unknown | null on Postgres and require a -- @col annotation on SQLite.

Type differences inside JSON. Because JSON has no native bigint or arbitrary-precision decimal type, a few database types map differently inside JSON objects and arrays:

Database typeType inside JSON
Postgres int8, SQLite INTEGERnumber (throws if outside JavaScript's safe integer range, ±2⁵³)
timestamp, timestamptzstring (even when "timestamp": "Date" is set)
SQLite INTEGER with -- @type boolean0 | 1
SQLite REAL, FLOAT, DOUBLEnumber
Postgres numeric; SQLite NUMERIC, DECIMAL, DATE, BLOB, ANYunknown

numeric stays unknown because parsing it as a JSON number would silently round large or high-precision values. To give an unknown JSON value a concrete type, cast it in SQL—for example p.price::text (exact string) or p.price::float8 (number) on Postgres, or CAST(p.price AS TEXT) on either dialect (using Postgres type names like text, int4, and float8 on Postgres, or SQLite declared types on SQLite)—or select it as a regular top-level column. See nested-rows (SQLite) and nested-rows (Postgres).

MERGE (Postgres) ​

Postgres 15+ MERGE INTO target USING source ON condition statements—with WHEN [NOT] MATCHED [BY SOURCE | BY TARGET] clauses—are fully typed (SQLite doesn't support MERGE). The source can be a table or a (subquery). Parameters used as standalone SET or INSERT values inherit their target column's type and schema annotations.

Without RETURNING, a MERGE returns { changes }. With RETURNING (Postgres 17+), it returns typed rows: target columns keep their table nullability, source columns become nullable if there's a WHEN NOT MATCHED BY SOURCE clause, and merge_action() is typed as 'INSERT' | 'UPDATE' | 'DELETE'. Optional SQL blocks (/*if*/, /*on*/, /*sort*/) aren't allowed inside MERGE; write the statement in full, or define one named MERGE per variant. See merge.

Optional SQL blocks ​

You can make parts of a query conditional using special SQL block comments such as /*if :p*/ ... /*end*/ (referred to as marks or parts in error messages). Because they're standard SQL comments, the file remains valid SQL with every block active. Blocks cannot be nested. During hyper-sql pull, the database prepares every valid combination, so every generated variant is verified up front.

How optional SQL blocks stay type-safeA query with /*if*/, /*on*/, and /*sort*/ comment blocks stays valid plain SQL, gets every variant verified by hyper-sql pull, and caches each rendered SQL variant at runtime with dense parameter numbering.One valid .sql file (no string building)SELECT isbn, title/*on :withPrice*/, price_cents /*end*/FROM books WHERE 1 = 1/*if :max*/ AND price_cents <= :max /*end*/ORDER BY /*sort :by title = title | price = price_cents*/ title /*end*/Every comment block on = standard runnable SQLCall: { by: 'title' }→ { isbn; title }[]SELECT isbn, title FROM booksWHERE 1 = 1 ORDER BY title // params: []Call: { withPrice: true, max: 1500, by: 'price' }SELECT isbn, title, price_cents FROM booksWHERE 1 = 1 AND price_cents <= ?1 ORDER BY price_cents
One valid .sql file generates cached SQL variants with dense parameter numbering (?1 / $1) and typed overloads when flags change the returned columns.
SyntaxBehavior
/*if :p*/ AND ... /*end*/Optional AND condition in WHERE or HAVING, included when p isn't undefined (p? can't be null). Start with WHERE 1 = 1 when there's no fixed condition before it.
/*on :f*/ ... /*end*/, /*off :f*/ ... /*end*/Arbitrary SQL toggled by a boolean flag f?: boolean (on when true, off when not true). Flags that add output columns generate typed overloads for each combination. Up to 3 flags per statement.
/*sort :p a = x | b = y*/ x /*end*/Type-safe ORDER BY from a fixed set of choices. p becomes a union of the choice names, and the SQL inside the block must match the first choice.
SET /*if :p*/ c = :p, /*end*/ updated = now()Optional UPDATE ... SET assignment, included when p isn't undefined (passing null sets the column to NULL). Keep at least one always-on assignment outside optional blocks.
(a /*if :c*/, c /*end*/) VALUES (:a /*if :c*/, :c /*end*/)Optional single-row INSERT column and matching value. When omitted, the column falls back to its default, so it must be nullable or have a DEFAULT.

Explore each form in the playground:

search-page combines filters, flags, and sort choices in one query. Postgres versions of each example are listed on the Examples page.

What hyper-sql infers ​

Most nullability and expression types follow directly from SQL semantics, so annotations are rarely needed. In addition to columns declared nullable in your schema, hyper-sql marks an output column nullable when:

  • It comes from the nullable side of a LEFT, RIGHT, or FULL join.
  • It's an aggregate like max(x) without GROUP BY (which returns NULL on an empty table).
  • It can be NULL in a subtotal row from ROLLUP, CUBE, or GROUPING SETS.
  • It's a scalar subquery (which may return no rows).
  • It comes from a view—or on Postgres, from LATERAL, a table-returning function, unnest, or VALUES.

See these inference rules in action:

Whenever hyper-sql can't infer a type safely, it reports a TypeScript error right at that spot in the .sql file and tells you which annotation or rewrite will fix it. Every message is documented in Errors.

Dynamic SQL at runtime ​

Occasionally your app has to choose a table name, column list, or entire SQL string dynamically at runtime. Static analysis can't type arbitrary runtime SQL, so hyper-sql provides unchecked<Row>(db, text, params, decode) as an explicit escape hatch. You supply the row type and a row decoder, and hyper-sql still runs your decoder to validate every row at runtime.

If you're only choosing between a small, fixed set of tables, prefer writing one named statement per table so you keep full compile-time checking. See examples/host/unchecked-sqlite/ and examples/host/unchecked-postgres/ in the repository for complete examples.