Skip to main content
The InsertQueryBuilder is used to build and execute INSERT queries in Kysely. It provides a fluent API for inserting single or multiple rows with type safety.

Basic Usage

Insert a Single Row

Insert a single row into a table:
The generated SQL (MySQL):

Insert Multiple Rows

On dialects that support it (for example PostgreSQL) you can insert multiple rows by providing an array:
The generated SQL (PostgreSQL):

Returning Data

On supported dialects like PostgreSQL you need to chain returning to the query to get the inserted row’s columns:
The generated SQL (PostgreSQL):
You can return all columns:

Complex Values

Values can be arbitrary expressions including subqueries and raw SQL:
The generated SQL (PostgreSQL):

Insert from Subquery

You can create an INSERT INTO SELECT FROM query using the expression method:
The generated SQL (PostgreSQL):

Default Values

Insert default values:
The generated SQL (PostgreSQL):

Conflict Handling

On Conflict (PostgreSQL)

Handle conflicts using onConflict:

Insert Ignore (MySQL)

Use ignore() to ignore duplicate key errors:
The generated SQL (MySQL):

On Duplicate Key Update (MySQL)

Handle duplicates with update:

SQLite Conflict Actions

SQLite supports various conflict actions:

API Reference

Main Methods

  • insertInto(table) - Specify the table to insert into
  • values(values) - Set the values to insert
  • columns(columns) - Set the columns (used with expression)
  • expression(expression) - Insert from a subquery or expression
  • defaultValues() - Insert default values
  • returning(columns) - Return columns from inserted rows (PostgreSQL, SQLite)
  • returningAll() - Return all columns from inserted rows
  • onConflict(callback) - Handle conflicts (PostgreSQL)
  • onDuplicateKeyUpdate(updates) - Update on duplicate key (MySQL)
  • ignore() - Insert ignore (MySQL)
  • orIgnore(), orReplace(), orAbort(), orFail(), orRollback() - SQLite conflict actions
  • modifyEnd(modifier) - Add custom SQL to the end
  • execute() - Execute the query
  • executeTakeFirst() - Execute and return first result
  • executeTakeFirstOrThrow() - Execute and return first result or throw

Result Object

The return value is an instance of InsertResult: