Drizzle ORM provides you the most SQL-like way to insert rows into the database tables.
Insert one row
Inserting data with Drizzle is extremely straightfoward and sql-like. See for yourself:
If you need insert type for a particular table you can use typeof usersTable.$inferInsert syntax.
Insert returning
PostgreSQL
SQLite
MySQL
You can insert a row and get it back in PostgreSQL and SQLite like such:
Insert $returningId
PostgreSQL
SQLite
MySQL
MySQL itself doesn’t have native support for RETURNING after using INSERT. There is only one way to do it for primary keys with autoincrement (or serial) types, where you can access insertId and affectedRows fields. We’ve prepared an automatic way for you to handle such cases with Drizzle and automatically receive all inserted IDs as separate objects
Also with Drizzle, you can specify a primary key with $default function that will generate custom primary keys at runtime. We will also return those generated keys for you in the $returningId() call
If there is no primary keys -> type will be {}[] for such queries
Insert multiple rows
Upserts and conflicts
Drizzle ORM provides simple interfaces for handling upserts and conflicts.
On conflict do nothing
PostgreSQL
SQLite
MySQL
onConflictDoNothing will cancel the insert if there’s a conflict:
On conflict do update
PostgreSQL
SQLite
MySQL
onConflictDoUpdate will update the row if there’s a conflict:
where clauses
on conflict do update can have a where clause in two different places -
as part of the conflict target (i.e. for partial indexes) or as part of the update clause:
To specify these conditions in Drizzle, you can use setWhere and targetWhere clauses:
Upsert with composite indexes, or composite primary keys for onConflictDoUpdate:
On duplicate key update
PostgreSQL
SQLite
MySQL
MySQL supports ON DUPLICATE KEY UPDATE instead of ON CONFLICT clauses. MySQL will automatically determine the conflict target based on the primary key and unique indexes, and will update the row if any unique index conflicts.
Drizzle supports this through the onDuplicateKeyUpdate method:
While MySQL does not directly support doing nothing on conflict, you can perform a no-op by setting any column’s value to itself and achieve the same effect: