Create or refresh a record keyed by a unique identifier
Idempotent synchronization
Prisma · Function
upsert updates a record when its unique where selector matches; otherwise, it creates one. It accepts separate update and create branches and may use a native database upsert when the documented criteria are satisfied.
Call a model's upsert method with a unique where selector and separate update and create branches. Prisma updates the matching record when one exists; when none matches, it inserts the create data. Where the documented criteria are satisfied, Prisma can delegate the operation to the database as a native upsert.
await prisma.<model>.upsert({
where: <unique selector>,
update: <update data>,
create: <create data>,
})| Name | Type | Description |
|---|---|---|
where | WhereUniqueInput | A unique selector used to determine whether an existing record matches. |
update | UpdateInput | Data applied when the selected record already exists. |
create | CreateInput | Data inserted when no matching record exists. |
The created or updated record for the model.
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
const user = await prisma.user.upsert({
where: { email: 'alice@prisma.io' },
update: { name: 'Alice Updated' },
create: { email: 'alice@prisma.io', name: 'Alice' },
})
console.log(user)
}
main().finally(() => prisma.$disconnect())The unique email identifies the record. Prisma updates the matching user; otherwise it creates one using the create branch.
Idempotent synchronization
Initialization
Compound uniqueness
It combines an update and a create operation. If a record satisfies where, Prisma applies update; if not, Prisma creates a record from create.
Follow-up: When can Prisma use a database upsert? It can do so when there are no nested queries, no nested-read selection, only one modified model, and the documented unique-field criteria are met.
The where option identifies the candidate record, update describes changes to an existing record, and create describes the complete data for a new record.
Follow-up: Why must create repeat the unique selector in database-upsert cases? The database needs the inserted row's unique value to correspond to the conflict target used for matching.
Native database upserts are faster than upserts handled by Prisma Client because the database performs the operation directly. Prisma uses them with CockroachDB, PostgreSQL, or SQLite when the criteria are met.
Follow-up: What happens when the criteria are not met? Prisma Client handles the upsert instead of delegating it to the database.
createupdatefindUniqueWorking with compound IDs and unique constraints