SQL
elements man database/sqlRunning queries with db.query, building a query from parts with sql, the
sync-style async transform, and camelCase column mapping.
Signaturedb.query<T>`...`: SqlResult<T> db.query<T>(query: Sql): SqlResult<T> sql`...`: Sql sql.join(parts: Sql[], separator?: Sql): Sql sql.ident(name: string): Sql
db.query runs a query and returns its rows. Write the SQL as a template
directly after db.query, with no parentheses, and interpolate any runtime
value with ${value}.
Examplelet user = db.query<User>` select * from users where id = ${id} `.first(); let active = db.query<User>` select * from users where active = ${true} and orgId = ${orgId} `;
db.query is a tagged template: JavaScript passes it the text of the template
and the ${value} values as two separate lists. Each value is sent to Postgres
as a positional parameter ($1, $2), apart from the query text, so an
interpolated value is never part of the SQL text and cannot inject SQL.
db.query does not take a string. db.query("select ...") and
db.query(text) are type errors, so SQL text is always written in a template
in your source code.
db.query runs on the server, and the compiler enforces it. Browser code,
including event handlers and template expressions, reads and writes the
database only by calling an @rpc function; a db.query call in browser code
outside an @rpc function is a compile error at the call site. The code that calls
db.query exists only on the server and is never sent to the browser, so
neither are your queries or your schema. sql, sql.join and sql.ident are
server-only in the same way.
The return value is a SqlResult<T>: an iterable wrapper over the rows. Each
row is a plain object: no class wraps a row, and nothing is loaded lazily. The generic renames
the result type for the type checker and does not change runtime behavior.
Iterating resultslet users = db.query<User>` select id, name, email from users `; for (let u of users) { console.log(u.name); } users.all().map(u => u.name);
The result exposes:
.first(): the first row, orundefined..last(): the last row, orundefined..all(): every row as a plain array..length/.size: the row count..empty():truewhen there are no rows..firstOrThrow(error?)/.lastOrThrow(error?)/.allOrThrow(error?): same as the above, but throwsNotFoundError(a safe 404) if empty. A string is the message for theNotFoundError; an Error instance is thrown as given.
Result methodsdb.query<User>` select * from users where id = ${id} `.first(); db.query<Event>` select * from events order by createdAt desc `.last(); db.query<User>`select * from users`.all(); // throws NotFoundError to the client if the row is missing let user = db.query<User>` select * from users where id = ${id} `.firstOrThrow(); // your own message, or your own error when a 404 is the wrong answer db.query<Job>` select * from jobs where id = ${id} `.firstOrThrow("No such job."); db.query<Invite>` select * from invites where token = ${token} and expiresAt > now() `.firstOrThrow(new ValidationError("That invite has expired."));
Sync-Style and the Async Transform
db.query is written sync-style. At build time the compiler rewrites each call
to await db.queryAsync and propagates async up the call stack. Every
function that transitively calls db.query becomes async without you typing
anything. The code reads as a sequence of statements and runs async.
To run queries at the same time with Promise.all, call db.queryAsync or
db.txAsync. Each returns a promise that you await yourself. Awaiting another
library's promise does not need db.queryAsync: mark the function async,
await that call, and keep writing db.query as usual.
Concurrent readsimport { db } from "@elements/app"; let [users, posts] = await Promise.all([ db.queryAsync<User>`select * from users`, db.queryAsync<Post>`select * from posts`, ]);
camelCase
By convention, write camelCase identifiers in your SQL. Elements converts to snake_case when the query is sent to Postgres and back to camelCase on results, so the SQL reads like the TypeScript that surrounds it. You write one casing throughout the codebase.
In the interactive psql shell, write the stored snake_case names
(created_at). The interactive shell does not convert the SQL
you type.
camelCaselet user = db.query<User>` insert into users ( firstName, createdAt ) values ( ${name}, ${now} ) returning * `.firstOrThrow(); user.firstName; user.createdAt; // On the wire to Postgres: // INSERT INTO users (first_name, created_at) VALUES ($1, $2) RETURNING *
The same convention applies in LiveTable config, in migrations, and anywhere
else you write SQL. Elements does the conversion in each.
elements db -sql and a sql file piped into elements db are converted too.
The one place it does not apply is the interactive psql shell, where you write
the snake_case names stored in the database. See elements man database/cli.
Names passed as strings
A few Postgres functions take a relation or column name as a string rather than as an identifier. Those strings are names, and they convert like names, so one spelling works everywhere:
Names as stringsdb.query`create sequence orderNumberSeq start with 1`; // stored as order_number_seq db.query`select nextval('orderNumberSeq') as n`; // 1 db.query`select nextval('order_number_seq') as n`; // 2, the stored spelling also works db.query`select 'orderNumberSeq'::regclass`; // resolves
This applies to nextval, currval, setval, to_regclass, to_regtype,
pg_get_serial_sequence, and a ::regclass or ::regtype cast. Only the name
argument of those calls converts, and only at that call's own nesting level.
Every other string is a value and is passed through exactly as you wrote it:
Values// 'myKind' stays 'myKind' db.query` select * from items where kind = ${kind} `; db.query`select concat('aB', 'cD')`; // untouched
Column Types
Each column of a row arrives as the JavaScript value for its Postgres type, so
the type you declare in db.query<T> matches what the row holds:
| Postgres type | Value in the row |
|---|---|
text, varchar, uuid, time |
string |
integer, smallint, bigint, real, double precision |
number |
numeric, decimal |
string, with every digit kept |
boolean |
boolean |
timestamptz, timestamp |
Date |
date |
Date, at midnight local time |
json, jsonb |
the parsed value |
an array, such as text[] |
an array of the element's value |
bytea |
Buffer |
| a null in any column | null |
count(*) is a bigint, so it is a number.
For a calendar day with no time, such as a birthday or a due date, select the
date column as text. The row then holds the string "2026-03-14", the same
format a date input and DatePicker use for their value:
app/pages/home/index.tsinterface Book { id: string; title: string; finishedOn: string; } const books = db.query<Book>` select id, title, finishedOn::text as finishedOn from books order by finishedOn desc `;
A LiveTable row holds the same values: its date column is a Date at
midnight local time. Format it for display with the Date methods, such as
toLocaleDateString().
Building a Query From Parts
Every ${value} in a db.query template is a parameter. Postgres does not
accept SQL text as a parameter, so a parameter cannot hold an optional WHERE
condition, an ORDER BY list, or a column name. Write that text with sql.
sql is a tagged template like db.query, but it does not run the query. It
returns a Sql: SQL text and its values. Interpolate a Sql into db.query,
or into another sql, and its text is placed in the query at that position.
The ${value} values inside it are still parameters.
Optional conditionimport { db, sql } from "@elements/app"; let olderThan = cursor ? sql`and createdAt < ${cursor}` : sql``; let order = sql`createdAt desc, id desc`; let posts = db.query<Post>` select * from posts where authorId = ${authorId} ${olderThan} order by ${order} `;
A function can build a query and return it. Pass the Sql to db.query in
parentheses to run it:
Run a built queryfunction postsBy(authorId: string): Sql { return sql` select * from posts where authorId = ${authorId} `; } let posts = db.query<Post>(postsBy(authorId));
sql.join(parts, separator) joins an array of Sql values into one Sql. Use
it when the number of parts is known only when the code runs. The separator is
a Sql, and is a comma when you leave it out.
sql.joinlet filters = [sql`orgId = ${orgId}`]; if (role) { filters.push(sql`role = ${role}`); } let users = db.query<User>` select * from users where ${sql.join(filters, sql` and `)} `;
sql.ident(name) returns a Sql whose text is the column or table name in
the string name. It accepts a name made of letters, digits and underscores that does
not start with a digit, with a dot between a table and its column, and throws on any other text, so a string from
a request cannot add SQL to the query.
sql.identlet column = sortBy === "title" ? "title" : "createdAt"; let posts = db.query<Post>` select * from posts order by ${sql.ident(column)} desc `;
A Sql is made only by sql, sql.join and sql.ident. A string in ${} is
always a parameter. Only sql.ident places a string as SQL text, and it
accepts only a name. A camelCase name inside a Sql is
converted to snake_case, the same as a name in the rest of the query. A LiveTable custom select
returns a Sql; see livetable/options.