Updating and Deleting Data: CRUD Operations Part 2
Let us explore modifying or removing existing database records using Prisma Client update, delete, and upsert query methods.
1. Modifying Records (Update)
Prisma provides three primary methods for modifying database rows:
A. Updating a Single Record
Modify a single row matching a unique column target. The update query requires a where block mapping to a unique field:
const updatedUser = await db.user.update({
where: {
email: "alice@example.com",
},
data: {
name: "Alice Smith",
},
});B. Bulk Modifying Records
Use updateMany to modify all records that match specific filter criteria:
const result = await db.user.updateMany({
where: {
email: {
contains: "@oldcompany.com",
},
},
data: {
name: "Archived Staff",
},
});C. Creating or Updating a Record (Upsert)
An upsert operation updates a record if it exists, or creates a new one if it does not:
const user = await db.user.upsert({
where: { email: "charlie@example.com" },
update: { name: "Charlie Senior" },
create: {
email: "charlie@example.com",
name: "Charlie Junior",
},
});2. Removing Records (Delete)
Prisma provides two primary methods for removing database rows:
A. Deleting a Single Record
Remove a single row matching a unique identifier. This query requires a unique filter:
const deletedUser = await db.user.delete({
where: {
email: "alice@example.com",
},
});B. Bulk Removing Records
Use deleteMany to clear multiple matching rows at once:
const deletedCount = await db.user.deleteMany({
where: {
email: {
contains: "@spam.com",
},
},
});To delete all rows in a table, call deleteMany without a filter argument:
// Clear the entire user table
await db.user.deleteMany();Published on Last updated: