Skip to main content

InsertQueryBuilder

Builder for constructing INSERT queries with type-safe value insertion.

Type Parameters

  • DB - The database schema type
  • TB - The table name being inserted into
  • O - The output type (InsertResult or custom with returning)

Methods

values

Sets the values to insert. Takes an object whose keys are column names and values are values to insert. You must provide all fields you haven’t explicitly marked as nullable or optional using Generated or ColumnType. Examples: Insert a single row:
Insert multiple rows (PostgreSQL):
Complex values with expressions:

columns

Sets the columns to insert. The values method sets both columns and values. Use this method when using expression to insert from a select query. Example:

expression

Insert an arbitrary expression, such as the result of a select query. Example:

defaultValues

Creates an insert into "person" default values query. Example:

returning

Adds a RETURNING clause to the query (supported on PostgreSQL, SQLite, MS SQL Server). Example:

returningAll

Adds a returning * clause to the query. Example:

onConflict

Adds an ON CONFLICT clause (PostgreSQL, SQLite). Examples: Update on conflict:
Do nothing on conflict:
Use constraint name:

onDuplicateKeyUpdate

Adds ON DUPLICATE KEY UPDATE (MySQL). Example:

ignore

Changes an insert into query to an insert ignore into query (MySQL) or insert or ignore into (SQLite). Example:

orIgnore

Changes an insert into query to an insert or ignore into query (SQLite).

orReplace

Changes an insert into query to an insert or replace into query (SQLite).

orAbort

Changes an insert into query to an insert or abort into query (SQLite).

orFail

Changes an insert into query to an insert or fail into query (SQLite).

orRollback

Changes an insert into query to an insert or rollback into query (SQLite).

top

Changes an insert into query to an insert top into query (MS SQL Server). Example:

output

Adds an OUTPUT clause (MS SQL Server).

outputAll

Adds an output inserted.* clause (MS SQL Server).

$call

Simply calls the provided function passing this as the only argument. Example:

$if

Call func(this) if condition is true. Especially handy with optional returning or returningAll calls. Example:

$castTo

Change the output type of the query.

$narrowType

Narrows (parts of) the output type of the query.

execute

Executes the query and returns an array of rows.

executeTakeFirst

Executes the query and returns the first result or undefined.

executeTakeFirstOrThrow

Executes the query and returns the first result or throws.

compile

Compiles the query to SQL without executing it.

stream

Streams the query results.

explain

Executes an EXPLAIN query.