Idempotent writes
Create a record only when its unique identifier is not already present; otherwise modify the existing record.
Prisma · Module
Prisma Client upsert updates a record when its unique where condition matches; otherwise, it creates one. It accepts separate update and create branches and may use a native database upsert when the query qualifies.
Prisma Client's upsert combines update and create behavior. It checks the unique where condition, applies update when a matching record exists, and otherwise creates a record from create; eligible queries can be delegated to the database.
prisma.<model>.upsert({ where, update, create })| Name | Type | Description |
|---|---|---|
where | UserWhereUniqueInput | Unique selector used to find the existing record. |
update | UserUpdateInput | Data applied when the record already exists. |
create | UserCreateInput | Data used when no matching record exists. |
The created or updated model record.
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 determines which user is matched; Prisma updates that user when found or creates it with the create data otherwise.
Create a record only when its unique identifier is not already present; otherwise modify the existing record.
Use a composite identifier or unique constraint to select the record for the operation.
Apply an atomic create-or-update workflow while allowing Prisma to delegate eligible operations to the database.
upsert accepts where, update, and create. If where matches an existing record, Prisma applies update; if not, it creates a record using create.
Follow-up: When can Prisma use a database upsert? It can do so when the query has no nested writes or nested reads, modifies one model, uses one unique where field, and keeps the where and create unique values equal.
A database upsert is usually faster because Prisma sends the operation to the database rather than handling the decision itself. Prisma uses this strategy automatically only when the documented criteria are satisfied.
Follow-up: Which providers support this optimization? The documentation lists CockroachDB, PostgreSQL, and SQLite data sources.
The where property identifies the candidate record, update contains changes for the match branch, and create contains data for the no-match branch. The three inputs correspond to the two possible outcomes of the operation.
Follow-up: How would a composite identifier be used? Supply the composite identifier object under its generated unique selector in where.
createupdatedeletefindUniquecompound IDs and unique constraints