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:Insert Multiple Rows
On dialects that support it (for example PostgreSQL) you can insert multiple rows by providing an array:Returning Data
On supported dialects like PostgreSQL you need to chainreturning to the query to get the inserted row’s columns:
Complex Values
Values can be arbitrary expressions including subqueries and raw SQL:Insert from Subquery
You can create anINSERT INTO SELECT FROM query using the expression method:
Default Values
Insert default values:Conflict Handling
On Conflict (PostgreSQL)
Handle conflicts usingonConflict:
Insert Ignore (MySQL)
Useignore() to ignore duplicate key errors:
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 intovalues(values)- Set the values to insertcolumns(columns)- Set the columns (used withexpression)expression(expression)- Insert from a subquery or expressiondefaultValues()- Insert default valuesreturning(columns)- Return columns from inserted rows (PostgreSQL, SQLite)returningAll()- Return all columns from inserted rowsonConflict(callback)- Handle conflicts (PostgreSQL)onDuplicateKeyUpdate(updates)- Update on duplicate key (MySQL)ignore()- Insert ignore (MySQL)orIgnore(),orReplace(),orAbort(),orFail(),orRollback()- SQLite conflict actionsmodifyEnd(modifier)- Add custom SQL to the endexecute()- Execute the queryexecuteTakeFirst()- Execute and return first resultexecuteTakeFirstOrThrow()- Execute and return first result or throw
Result Object
The return value is an instance ofInsertResult: