Query Builder
Introduction
The query builder is a fluent interface for building and running SQL without writing it by hand. You start from a connection with db.table('name'), chain constraints, and finish with a method that executes the query (get(), first(), count(), insert(), and so on). Values are always sent as bindings, never concatenated into the SQL, so the builder protects you from SQL injection.
Rows come back as plain objects keyed by column name. The examples on this page use an in-memory SQLite connection with these two tables:
import { sqliteConnection, raw } from '@plinthjs/database'
const db = sqliteConnection()
await db.statement(
`create table users (
id integer primary key, name text, email text, age integer,
role text, settings text, created_at text, votes integer default 0
)`,
)
await db.statement(
'create table posts (id integer primary key, user_id integer, title text, published integer default 0)',
)
await db.table('users').insert([
{ name: 'Ada', email: 'ada@x.com', age: 36, role: 'admin', created_at: '2024-03-05 10:00:00' },
{ name: 'Linus', email: 'linus@x.com', age: 54, role: 'user', created_at: '2023-12-25 08:30:00' },
{ name: 'Grace', email: null, age: 45, role: 'user', created_at: '2024-03-20 12:00:00' },
])Retrieving results
get() runs the query and returns every matching row as an array.
const users = await db.table('users').get()
// => [{ id: 1, name: 'Ada', ... }, { id: 2, name: 'Linus', ... }, { id: 3, name: 'Grace', ... }]A single row
first() returns the first matching row, or null when there is none. find() looks a row up by its id column (pass a second argument to use another column).
await db.table('users').where('name', 'Ada').first() // => { id: 1, name: 'Ada', ... }
await db.table('users').find(2) // => { id: 2, name: 'Linus', ... }
await db.table('users').find(99) // => null
await db.table('users').find('ada@x.com', 'email') // => { id: 1, ... }A single value or a column
value() returns one column of the first matching row (or undefined). pluck() returns one column from every row.
await db.table('users').where('name', 'Ada').value('age') // => 36
await db.table('users').where('name', 'Nobody').value('age') // => undefined
await db.table('users').pluck('name') // => ['Ada', 'Linus', 'Grace']Checking existence
await db.table('users').where('id', 1).exists() // => true
await db.table('users').where('id', 99).doesntExist() // => trueExactly one row
sole() returns the only matching row and throws if there are none or more than one. soleValue() does the same for a single column. Both errors are exported so you can catch them.
import { RecordsNotFoundError, MultipleRecordsFoundError } from '@plinthjs/database'
await db.table('users').where('name', 'Ada').sole() // => { id: 1, name: 'Ada', ... }
await db.table('users').where('name', 'Ada').soleValue('email') // => 'ada@x.com'
try {
await db.table('users').where('name', 'Nobody').sole()
} catch (error) {
error instanceof RecordsNotFoundError // => true, message 'No records found.'
}
try {
await db.table('users').sole()
} catch (error) {
error instanceof MultipleRecordsFoundError // => true, message '3 records were found.'
;(error as MultipleRecordsFoundError).count // => 3
}first() and find() return null rather than throwing, so reach for sole() when more than one match would be a bug.
Selecting columns
By default every column is selected. Name the columns you want with select(), and use distinct() to remove duplicates.
await db.table('users').select('name', 'age').get()
await db.table('users').select('role').distinct().get() // => [{ role: 'admin' }, { role: 'user' }]Where clauses
where(column, value) compares with =. Pass an operator as the second argument to use another comparison: =, !=, <>, <, <=, >, >=, like or not like. Chained wheres are joined with and; use orWhere() for or.
db.table('users').where('age', '>', 40).toSql()
// => { sql: 'select * from "users" where "age" > ?', bindings: [40] }
db.table('users').where('role', 'admin').orWhere('age', '>', 50).toSql()
// => select * from "users" where "role" = ? or "age" > ?Comparing with null is turned into is null or is not null for you:
db.table('users').where('email', '!=', null).toSql().sql
// => select * from "users" where "email" is not nullGrouped conditions
Pass a callback to wrap a set of conditions in parentheses.
db
.table('users')
.where((query) => query.where('role', 'admin').orWhere('age', '>', 50))
.where('email', '!=', null)
.toSql().sql
// => select * from "users" where ("role" = ? or "age" > ?) and "email" is not nullwhereNot() negates a condition or a whole group:
db.table('users').whereNot('role', 'admin').toSql().sql
// => select * from "users" where not ("role" = ?)Lists, nulls and ranges
db.table('users').whereIn('id', [1, 2]).toSql().sql
db.table('users').whereNotIn('role', ['banned']).toSql().sql
db.table('users').whereNull('email').toSql().sql
db.table('users').whereNotNull('email').toSql().sql
db.table('users').whereBetween('age', [30, 50]).toSql().sqlorWhereIn() is the or form of whereIn(). For very large id lists, whereIntegerInRaw() inlines validated integers instead of binding each one:
db.table('users').whereIntegerInRaw('id', [1, 2, 3]).toSql().sql
// => select * from "users" where "id" in (1, 2, 3)It throws a TypeError if any value is not an integer, which is what makes the inlining safe. whereIntegerNotInRaw() is the negation.
Comparing columns
whereColumn() compares two columns instead of a column and a value:
db.table('users').whereColumn('created_at', '<', 'updated_at').toSql().sql
// => select * from "users" where "created_at" < "updated_at"Pattern matching
whereLike() is case-insensitive by default. Pass true as the third argument to make it case-sensitive (on SQLite this compiles to glob).
db.table('users').whereLike('name', 'a%').orWhereLike('name', 'G%', true).toSql().sql
// => select * from "users" where "name" like ? or "name" glob ?whereNotLike() and orWhereNotLike() negate the match.
Several columns at once
whereAny() requires at least one of the columns to match, whereAll() requires all of them, and whereNone() requires none.
db.table('users').whereAny(['name', 'email'], 'like', '%x%').toSql().sql
// => select * from "users" where ("name" like ? or "email" like ?)
db.table('users').whereAll(['age', 'votes'], '>', 1).toSql().sql
// => select * from "users" where ("age" > ? and "votes" > ?)
db.table('users').whereNone(['name'], 'Bob').toSql().sql
// => select * from "users" where not ("name" = ?)Date constraints
The date helpers compare one part of a date column. They accept a string or a Date, and compile to the right function for each dialect.
await db.table('users').whereDate('created_at', '2024-03-05').pluck('name') // => ['Ada']
await db.table('users').whereMonth('created_at', 3).pluck('name') // => ['Ada', 'Grace']
db.table('users').whereYear('created_at', '>=', 2023)
db.table('users').whereDay('created_at', 5)
db.table('users').whereTime('created_at', '>', '09:00:00')Each has an or form (orWhereDate(), orWhereYear(), and so on).
JSON columns
whereJsonContains() checks whether a JSON column (or a path inside it, written column->path) contains a value. whereJsonLength() compares the length of a JSON array.
await db.table('users').where('id', '>', 0).update({ settings: '{"tags":["a","b"]}' })
await db.table('users').whereJsonContains('settings->tags', 'a').pluck('name') // => ['Ada', 'Linus', 'Grace']
db.table('users').whereJsonLength('settings->tags', '>', 1)
db.table('users').whereJsonDoesntContain('settings->tags', 'z')Exists and subqueries
whereExists() takes a callback (or another builder) that describes a subquery:
await db
.table('users')
.whereExists((query) =>
query.from('posts').whereColumn('posts.user_id', '=', 'users.id').where('published', 1),
)
.pluck('name')
// => ['Ada', 'Linus']whereNotExists(), orWhereExists() and orWhereNotExists() complete the set.
To select a subquery as a column use selectSub(). select() and selectSub() accumulate, in the order you call them, so either can come first:
db
.table('users')
.select('name')
.selectSub(
(query) =>
query.from('posts').select(raw('count(*)')).whereColumn('posts.user_id', '=', 'users.id'),
'posts_count',
)
.toSql().sql
// => select "name", (select count(*) from "posts" where "posts"."user_id" = "users"."id") as "posts_count" from "users"Raw where clauses
When the builder cannot express a condition, drop to SQL with whereRaw() and bind its values:
db.table('users').whereRaw('age > ? and role = ?', [18, 'admin']).toSql()
// => { sql: 'select * from "users" where age > ? and role = ?', bindings: [18, 'admin'] }Joins
join() (an inner join), leftJoin() and rightJoin() take the table, then the two columns being related with an operator. crossJoin() takes only a table.
await db
.table('users')
.join('posts', 'users.id', '=', 'posts.user_id')
.select('users.name', 'posts.title')
.get()
// => [{ name: 'Ada', title: 'Hello' }, { name: 'Ada', title: 'Draft' }, { name: 'Linus', title: 'Kernel' }]
await db
.table('users')
.leftJoin('posts', 'users.id', '=', 'posts.user_id')
.select('users.name', 'posts.title')
.get()
// Grace appears with title: nullTo join a subquery under an alias, use joinSub() or leftJoinSub(). To use a subquery as the table you select from, use fromSub().
db
.table('users')
.joinSub(
(query) => query.from('posts').select('user_id', raw('count(*) as c')).groupBy('user_id'),
'pc',
'pc.user_id',
'=',
'users.id',
)
.toSql().sql
db.table('users').fromSub((query) => query.from('users').where('age', '>', 1), 'u')Unions
union() appends another query's rows with duplicates removed; unionAll() keeps them. Both take another builder.
await db.table('users').select('name').union(db.table('posts').select('title')).get()
// => [{ name: 'Ada' }, { name: 'Draft' }, { name: 'Grace' }, ...]
db.table('users').select('name').unionAll(db.table('posts').select('title'))Grouping, ordering and limiting
groupBy() and having() work as in SQL. Selecting an aggregate expression needs raw() (see Raw expressions).
await db
.table('posts')
.select('user_id', raw('count(*) as total'))
.groupBy('user_id')
.having('total', '>', 1)
.get()
// => [{ user_id: 1, total: 2 }]Order with orderBy(column, direction) (direction defaults to 'asc'), orderByDesc(), or orderByRaw(). latest() and oldest() order by created_at descending or ascending, or by the column you name.
await db.table('users').orderBy('role').orderByDesc('age').pluck('name') // => ['Ada', 'Linus', 'Grace']
await db.table('users').latest('age').pluck('name')
await db.table('users').orderByRaw('length(name) desc').get()Use limit() and offset() (or their aliases take() and skip()) to window the results, and forPage(page, perPage) to compute both from a page number. Pages are 1-based and perPage defaults to 15.
await db.table('users').orderBy('id').limit(2).offset(1).pluck('name') // => ['Linus', 'Grace']
await db.table('users').orderBy('id').forPage(2, 2).pluck('name') // => ['Grace']For results with page metadata, see Pagination.
Aggregates
count(), sum(), avg(), min() and max() run the aggregate and return a number (0 when nothing matches).
await db.table('users').count() // => 3
await db.table('users').sum('age') // => 135
await db.table('users').avg('age') // => 45
await db.table('users').min('age') // => 36
await db.table('users').max('age') // => 54
await db.table('users').where('role', 'user').count('email') // => 1 (nulls are not counted)Inserting
insert() accepts one row or an array of rows and resolves to true. Inserting an empty array does nothing.
await db.table('posts').insert({ user_id: 1, title: 'Hello', published: 1 })
await db.table('posts').insert([
{ user_id: 1, title: 'Draft' },
{ user_id: 2, title: 'Kernel', published: 1 },
])insertGetId() inserts one row and returns the generated id:
const id = await db.table('users').insertGetId({ name: 'Dennis', age: 70, role: 'user' })
// => 4insertOrIgnore() skips rows that violate a unique constraint and returns how many were actually inserted. insertUsing() fills a table from a query.
await db.table('users').insertOrIgnore({ name: 'Dup', email: 'ada@x.com' }) // => 0 when email is unique
await db
.table('posts')
.insertUsing(['user_id', 'title'], (query) =>
query.from('users').select('id', 'name').where('id', 1),
)
// => 1 (rows inserted)Upserts
upsert() inserts rows and, where a row conflicts on the unique columns, updates the existing one instead. The second argument names the columns that identify a row; the optional third lists which columns to update (by default, every inserted column that is not in the unique set). The unique columns must be covered by a unique index.
await db.statement('create unique index users_email on users (email)')
await db.table('users').upsert(
[{ name: 'Ada Lovelace', email: 'ada@x.com', age: 37 }],
'email', // or ['email'] for several columns
['name', 'age'],
)
// => 1updateOrInsert() updates the first row matching the attributes, or inserts a new row built from the attributes and values:
await db.table('users').updateOrInsert({ email: 'z@x.com' }, { name: 'Z' }) // => true (inserted)
await db.table('users').updateOrInsert({ email: 'z@x.com' }, { name: 'Zed' }) // => true (updated)Updating
update() applies to every row matched by the query and returns the number of rows changed. Use raw() to compute a value from the current one.
await db.table('users').where('name', 'Ada').update({ age: 37 }) // => 1
await db
.table('users')
.where('name', 'Ada')
.update({ votes: raw('votes + 1') }) // => 1incrementEach() and decrementEach() adjust several columns at once, and take a second object of columns to set verbatim:
await db.table('users').where('name', 'Ada').incrementEach({ votes: 5, age: 1 }, { role: 'editor' })WARNING
update() and delete() without a where affect every row in the table.
Deleting
await db.table('users').where('email', 'z@x.com').delete() // => 1 (rows deleted)
await db.table('users').where('age', '>', 1000).delete() // => 0Processing large result sets
Loading a huge table into memory with get() is wasteful. These methods read in pieces.
chunk() hands you pages of rows. The query must have an orderBy, otherwise paging would not be deterministic, and a missing order throws. Return false from the callback to stop early.
await db
.table('users')
.orderBy('id')
.chunk(2, async (rows, page) => {
console.log(
page,
rows.map((row) => row.name),
)
})
// 1 ['Ada', 'Linus']
// 2 ['Grace']chunkById() pages by comparing the id column instead of using offsets, which stays correct while you update or delete the rows you are iterating. each() runs a callback for one row at a time (the row index is global), and also stops on false.
await db.table('users').chunkById(100, (rows) => {
// process rows
})
await db
.table('users')
.orderBy('id')
.each((row, index) => {
console.log(index, row.name)
})lazy() and lazyById() return an async generator that fetches a page at a time but yields single rows, so you can use for await:
for await (const user of db.table('users').orderBy('id').lazy(500)) {
console.log(user.name)
}cursor() is an async generator over a single query. The driver interface has no row streaming, so the whole result is loaded first and then handed to you row by row.
for await (const user of db.table('users').cursor()) {
console.log(user.name)
}Locking
Inside a transaction you can lock the selected rows. lockForUpdate() adds for update and sharedLock() adds for share. The SQL is emitted as written, so use these against databases that support row locks (MySQL and Postgres).
db.table('users').lockForUpdate().toSql().sql // => select * from "users" for update
db.table('users').sharedLock().toSql().sql // => select * from "users" for share
await db.transaction(async (tx) => {
const account = await tx.table('accounts').where('id', 1).lockForUpdate().first()
// ...
})Conditional clauses
when() applies a callback only if the first argument is truthy, with an optional callback for the falsy case. unless() is the inverse. They keep a chain readable when filters are optional.
const search = { role: 'admin', minAge: 0 }
const query = db
.table('users')
.when(search.role, (q, role) => q.where('role', role))
.when(search.minAge, (q, age) => q.where('age', '>=', age))
query.toSql()
// => { sql: 'select * from "users" where "role" = ?', bindings: ['admin'] }tap() passes the builder to a callback and returns it, which is handy for reusing a block of constraints:
import type { QueryBuilder } from '@plinthjs/database'
const published = (query: QueryBuilder) => query.where('published', 1)
await db.table('posts').tap(published).count()Branching a query
A builder is mutable. Call clone() to get an independent copy, so you can add constraints to one branch without affecting the other.
const base = db.table('users').where('role', 'user')
const older = base.clone().where('age', '>', 50)
await base.count() // => 2
await older.count() // => 1Terminal methods such as count(), first() and exists() clone internally, so calling them does not change the builder.
Raw expressions
raw() wraps a SQL fragment that is emitted exactly as written, never quoted. Use it for functions and expressions in selects, wheres, orders and updates.
db.table('users').select(raw('lower(name) as lname')).toSql().sql
// => select lower(name) as lname from "users"
db.table('users').where(raw('lower(email)'), '=', 'ada@x.com')WARNING
Raw fragments are not escaped. Never build one from user input. Pass user-supplied values as bindings (whereRaw('age > ?', [age])) instead.
Inspecting the SQL
toSql() returns the SQL with its bindings, and toRawSql() returns a single string with the bindings substituted as quoted literals. Use toRawSql() for debugging only; always execute with bindings.
db.table('users').where('id', 1).toSql()
// => { sql: 'select * from "users" where "id" = ?', bindings: [1] }
db.table('users').where('id', 1).toRawSql()
// => select * from "users" where "id" = 1Both only describe a select. To see every statement that actually runs, including writes, use db.listen() or db.pretend() from Getting Started.
Gotchas
select()andselectSub()add to the column list. Callselect()with no arguments to clear it.where()supports closures and column values, but there is no subquery form ofwhereIn()orwhere(). UsewhereExists(),joinSub()orfromSub()for subqueries.- Calling an aggregate such as
count()orsum()inside a subquery callback throws an error that tells you to select the aggregate withselect(raw('count(*) as total'))or to usewhereExists(): those methods run a query immediately instead of describing one. chunk()andlazy()need anorderBy.chunkById()andlazyById()order by the id column for you.