A query starts with from, fromQuery, or fromUnion and is refined by chaining. Every
method returns a new query — nothing mutates.
const base = CH.from(Events)
.select(($) => ({ name: $.Name }))
.where(($) => [$.OrgId.eq("org_123")])
const limited = base.limit(10) // `base` still has no LIMITThat makes shared base queries safe to hand around and specialise per caller.
The SQL in these guides is shown with its whitespace collapsed. Every column reference is
qualified with its source, on every dialect: events.Name on ClickHouse, "events"."Name" on
Postgres and SQLite, `events`.`Name` on MySQL. Short fragments in comments sometimes leave the
qualifier out.
(Backed by docs/queries.md > Queries are immutable.)
Three forms.
Every column — select() with no arguments reads every column of the FROM table, under
its key, as drizzle's bare select() does:
CH.from(Events).select()
// SELECT events.Name AS Name, events.DurationMs AS DurationMs, ... FROM eventsBy column name — output keys match the column names:
CH.from(Events).select("Name", "DurationMs")
// SELECT events.Name AS Name, events.DurationMs AS DurationMs FROM eventsBy callback — for computed expressions, aliases, and aggregates:
CH.from(Events).select(($) => ({
name: $.Name,
p95: CH.quantile(0.95)($.DurationMs),
count: CH.count(),
}))The object keys become the SQL aliases and the keys of the output row type. Spreading $
gives every column of the FROM table under its key, so select(($) => ({ ...$, lowered: CH.lower($.Name) })) reads them all plus one more; returning takes the same. select is
required: compiling without one raises QueryBuilderDefect, which stays a defect — no request
value can remove a select().
Calling select again replaces the previous projection rather than adding to it.
(Backed by docs/queries.md > select by column name.)
A select key is written as a SQL alias, so any string works as one, including a key built from
input. Postgres, SQLite and MySQL quote every alias. ClickHouse writes a plain name (letters,
digits, _) bare, as before, and puts any other in backticks:
import * as CH from "@maple-dev/effect-orm/clickhouse"
const Events = CH.table("events", {
columns: { Name: CH.string, DurationMs: CH.uint64 },
engine: CH.engine.mergeTree(),
orderBy: ["Name"],
})
export const compiled = CH.compileUnsafe(
CH.from(Events)
.select(($) => ({ "by service": $.Name, "p-95": CH.quantile(0.95)($.DurationMs), null: CH.count() }))
.groupBy("by service")
.orderBy(["p-95", "desc"]),
)
// SELECT events.Name AS `by service`, quantile(0.95)(events.DurationMs) AS `p-95`, count() AS `null`
// FROM events GROUP BY `by service` ORDER BY `p-95` DESCimport * as PG from "@maple-dev/effect-orm/postgres"
const Events = PG.table("events", { columns: { name: PG.text, duration_ms: PG.int8 } })
export const compiled = PG.compileUnsafe(
PG.from(Events)
.select(($) => ({ "by service": $.name, "max ms": PG.max($.duration_ms) }))
.groupBy("by service")
.orderBy(["max ms", "desc"]),
)
// SELECT "events"."name" AS "by service", max("events"."duration_ms") AS "max ms"
// FROM "events" GROUP BY 1 ORDER BY "max ms" DESCSQLite quotes the same way; MySQL uses backticks. Postgres, SQLite and MySQL write a GROUP BY key by its position in the select list.
The row comes back under the same keys. On ClickHouse a key with a dot, and a few words that
ClickHouse reads as something else (null, true, all, select and others), are quoted
too; Names has the full list. A key that contains
__PARAM_, the text the builder marks params with, is escaped on ClickHouse and fails the
compile with InvalidLiteral on the other dialects.
where takes a callback returning an array of conditions, AND-joined together:
.where(($) => [
$.OrgId.eq("org_123"),
$.DurationMs.gt(1000),
])Entries may be undefined, which drops them — that is what makes optional filters clean. See
when / whenTrue.
Calling where again adds conditions, ANDed with the earlier ones, as in Kysely. A shared
base that filters by tenant keeps that filter however many .where(...) calls follow. Both flat
conditions and .and() preserve tenant scoping; .or() does not.
having accumulates the same way.
select, groupBy, orderBy, limit, offset, and format replace the previous value. Joins
and CTEs accumulate.
Takes output keys (the aliases from select), not raw column names:
.select(($) => ({ name: $.Name, count: CH.count() }))
.groupBy("name")Once a query groups or aggregates, every column it reads outside an aggregate must be a
groupBy key, as both databases require. Compiling one that breaks the rule is a
QueryBuilderDefect naming the alias and column, instead of a server error:
select(($) => ({ name: $.Name, n: CH.count() }))with nogroupBy("name");- an aggregate in
whereor a join'son(filter on it inhaving); groupBynaming an aggregate alias.
An expression over a grouped column (CH.lower($.Name) with Name grouped) and a repeat of a
grouped expression are fine. Only SQL the builder writes is checked: a window (CH.over), a
CH.sql template, rawExpr and functions declared with defineFn / makeExpr are not looked
inside, so they can hide a mistake from this check but never trigger a false one.
Filter groups after aggregation. The callback has the input-column accessor, so either repeat
an aggregate expression or reference an output alias with CH.dynamicColumn("alias", type):
const query = CH.from(Events)
.select(($) => ({ name: $.Name, count: CH.count() }))
.where(($) => [$.OrgId.eq(CH.param.string("orgId"))])
.groupBy("name")
.having(() => [CH.dynamicColumn("count", CH.uint64).gte(CH.param.int("minimumCount"))])Compile with { orgId: "org_123", minimumCount: 10 } to emit HAVING count >= 10.
Use WHERE for row filters and HAVING for aggregate filters. A tenant predicate in HAVING
does not establish tenant scope.
The complete HAVING recipe is checked directly from Markdown.
Takes [column, direction] tuples, one per sort key:
.orderBy(["count", "desc"], ["name", "asc"])
// ORDER BY count DESC, name ASCTo sort by something not selected, pass a callback returning [expression, direction] pairs;
it reads the source's columns as where does:
.orderBy(($) => [[$.Timestamp, "desc"], [CH.lower($.Name), "asc"]])Passing two bare strings, .orderBy("count", "desc"), is a type error.
Untyped callers receive QueryBuilderDefect; use a tuple for each sort key.
(Backed by docs/queries.md > orderBy takes tuples and > orderBy rejects a bare string.)
.select("ServiceName").distinct()
// SELECT DISTINCT ServiceName …
.select(($) => ({ org: $.OrgId, id: $.Id })).distinctOn("org").orderBy(["org", "asc"], ["id", "desc"])
// SELECT DISTINCT ON (org) … — the newest row per orgdistinctOn takes selected aliases and keeps the first row of each group in ORDER BY order;
Postgres wants those keys to lead the ORDER BY. ClickHouse and Postgres support it; SQLite and
MySQL have no DISTINCT ON, and compiling it for them is a QueryBuilderDefect.
.limit(50).offset(100)Both take non-negative integers, not param.* expressions. A negative or fractional literal is
a type error; a value that arrives at runtime (NaN, -1, 1.5) fails compilation with a
QueryBuilderError instead of being rounded. Still enforce an application maximum at your
request boundary. Use a stable orderBy when paging;
Recipes shows where an offset is appropriate.
.format("JSON") // appends `FORMAT JSON`ClickHouse only. Accepts "JSON" or "JSONEachRow". Most clients set the format themselves;
use this only when you are sending raw SQL somewhere that does not. On another dialect a query
with format is a QueryBuilderDefect.
On Postgres, forUpdate, forNoKeyUpdate, forShare and forKeyShare add a locking clause
after LIMIT; MySQL and MariaDB have forUpdate and forShare (MySQL). Each takes { skipLocked?, noWait?, of? }. The usual job-queue claim:
PG.from(Jobs)
.select("id")
.where(($) => [$.state.eq("queued")])
.orderBy(["id", "asc"])
.limit(1)
.forUpdate({ skipLocked: true })
// … LIMIT 1 FOR UPDATE SKIP LOCKEDA lock lasts until the transaction ends, so run the query inside Database.transaction. These
are a QueryBuilderDefect, refused before anything is sent: skipLocked and noWait together;
a qualified name in of (use the alias or jobs, not public.jobs); a lock on a query with
DISTINCT, GROUP BY or HAVING, or on a unionAll branch, which Postgres refuses; and any lock on
ClickHouse, SQLite or D1, which have no row locks.
selectNoFrom(() => ({ … })) is a SELECT of values with no FROM. Its where takes conditions
that read no source, such as exists(…):
PG.selectNoFrom(() => ({ found: PG.lit(1) })).where(() => [PG.exists(PG.from(Users).select("id"))])
// SELECT 1 AS "found" WHERE EXISTS (SELECT "users"."id" AS "id" FROM "users")MySQL writes FROM DUAL. The usual use is as an insert's source, to insert a row only when a
condition holds; see Insert ... select.
See Unions and CTEs.
.route("ingest") and .crossTenant() attach metadata to the compiled result rather than
changing the SQL. Both are covered in Tenant scoping.
A query is Pipeable, and Query has a data-last form of each builder method, as Effect,
Stream and Schema do. Each Query function is a dual that calls the fluent method, so
both styles write the same SQL:
CH.Query.from(Events).pipe(
CH.Query.select(($) => ({ name: $.Name, ms: $.DurationMs })),
CH.Query.where(($) => [$.OrgId.eq("org_123")]),
CH.Query.orderBy(["ms", "desc"]),
CH.Query.limit(10),
)
// the same SQL as CH.from(Events).select(…).where(…).orderBy(…).limit(10)$ in a data-last callback is typed from the query that pipe carries, and a wrong column or
an unselected orderBy key is a type error at that step. Each function also has a data-first
form: CH.Query.where(query, ($) => […]).
Query has from, fromQuery and fromUnion to start, and a function for every CHQuery
method: select, where, groupBy, having, orderBy, limit, offset, format,
distinct, distinctOn, the row locks (forUpdate, forNoKeyUpdate, forShare,
forKeyShare), route, crossTenant, the joins (innerJoin, leftJoin, crossJoin and
their …Query forms) and withCTE. A form a dialect lacks (a row lock on ClickHouse or SQLite,
format outside ClickHouse, distinctOn on SQLite) is refused at compile, as the fluent method
is. Unions (CHUnionQuery) and writes (insertInto, update, deleteFrom) are not pipeable
yet; use their fluent methods.
A reusable part is a plain function. Type its $ with the table's columns and the name the
query reads it under (the alias, else the table name), so the query keeps its source:
const byOrg = (orgId: string) => CH.Query.where(($: CH.ColumnAccessor<typeof Events.columns, "events">) => [$.OrgId.eq(orgId)])
CH.Query.from(Events).pipe(byOrg("org_123"), CH.Query.select("Name"))(Backed by docs/queries.md > Pipeable, data-last queries.)
const compiled = CH.compileUnsafe(query, params)compile writes its entry's dialect: ClickHouse from /clickhouse, Postgres from /postgres,
SQLite from /sqlite, MySQL from /mysql (pass { dialect: mariadbDialect } for MariaDB).
Unions compile with compileUnion.
See Params and compilation.