Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 36 ยท Client Queries

Updating, Deleting and Upserting Records

Change and remove data with Prisma Client: update, updateMany, atomic increment, delete, deleteMany and upsert, plus the P2025 not-found error and soft deletes.

Reading is safe; writing is where mistakes hurt. This lesson covers changing and removing rows: update, updateMany, delete, deleteMany and upsert. You will also learn atomic number updates (which avoid lost updates) and how to handle the not-found case.

update: change one record

TypeScript
const updated = await prisma.product.update({
  where: { sku: "MUG-001" },
  data: { priceCents: 1350, stock: 20 },
});
  • where must identify exactly one row, with @id or @unique fields (like findUnique). Since Prisma 5 you may add extra non-unique conditions next to the unique field, which is a handy safety check: where: { id: 1, stock: { gt: 0 } }.
  • data holds only the fields to change; other fields stay as they are.
  • The return value is the updated row (use select to trim it).
  • If no row matches, update throws PrismaClientKnownRequestError with code P2025 ("Record to update not found").

Fields marked @updatedAt are refreshed automatically.

Atomic number operations

Never read a number, add one in JavaScript and write it back:

TypeScript
// BAD: two requests can both read 10 and both write 11
const p = await prisma.product.findUniqueOrThrow({ where: { id: 1 } });
await prisma.product.update({ where: { id: 1 }, data: { stock: p.stock - 1 } });

// GOOD: the database does the arithmetic atomically
await prisma.product.update({
  where: { id: 1 },
  data: { stock: { decrement: 1 } },
});

The operators are increment, decrement, multiply, divide and set. Each becomes stock = stock - 1 inside the database, so concurrent requests cannot overwrite each other. For text fields, assign a new string; for scalar lists use set and push.

updateMany: change many records

TypeScript
const result = await prisma.product.updateMany({
  where: { category: "kitchen", stock: 0 },
  data: { category: "discontinued" },
});
console.log(result.count); // how many rows changed

updateMany accepts any where (not only unique fields) and returns { count }, not the rows. It never throws a not-found error: zero matches simply gives count: 0. Use updateManyAndReturn on databases that support it when you need the changed rows.

An empty where: {} on updateMany or deleteMany affects every row. When the filter comes from user input or a variable that might be undefined, check it before the call.

delete and deleteMany

TypeScript
const gone = await prisma.product.delete({ where: { id: 5 } });   // returns the deleted row
const result = await prisma.product.deleteMany({ where: { stock: 0 } });  // { count }
await prisma.product.deleteMany();                                // empties the table!

delete follows the same rules as update: unique where, P2025 when nothing matches. A delete can also fail with P2003 (foreign key constraint) when other rows still reference the record; chapter 4 covers referential actions such as onDelete: Cascade.

upsert: update or create

TypeScript
const sku = "NOTE-01";
const item = await prisma.product.upsert({
  where: { sku },
  update: { stock: { increment: 10 } },
  create: { sku, name: "Notebook", category: "office", priceCents: 450, stock: 10 },
});

upsert looks for the row by a unique where. If it exists, update is applied; otherwise create. It is ideal for "import this record", counters and idempotent webhooks. Note that it is atomic only in the sense Prisma implements it: on PostgreSQL, SQLite, CockroachDB and MongoDB with a single unique field and equal values in where and create, Prisma uses a native INSERT ... ON CONFLICT; otherwise it runs a read then a write, where two simultaneous upserts can collide on the unique constraint, so be ready to retry on P2002.

Soft deletes

Often you do not want to destroy data. Add a timestamp and filter on it:

PRISMA
model Product {
  id        Int       @id @default(autoincrement())
  name      String
  deletedAt DateTime?
}
TypeScript
await prisma.product.update({ where: { id: 5 }, data: { deletedAt: new Date() } });
const visible = await prisma.product.findMany({ where: { deletedAt: null } });

Every read must remember deletedAt: null; chapter 7 shows how client extensions can add that filter automatically.

Try it: updates, atomic changes and upsert

The stand-in implements these write methods over arrays, including the P2025 error, atomic operators and upsert.

Node.js Stand-in: update, delete, upsert

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The lost-update problem, demonstrated

To see why atomic operators matter, simulate two requests that each read the stock, wait a moment and write back stock - 1. The final stock is wrong, while two real decrements are right.

Node.js Lost updates with read-modify-write

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which error code does update throw when no record matches the where?

    P2025 means a record required by the operation was not found.
  2. 2. Why is data: { stock: { decrement: 1 } } safer than reading the stock and writing stock - 1?

    Atomic operators become 'stock = stock - 1' in SQL, avoiding lost updates.
  3. 3. What does updateMany return?

    updateMany returns { count }. It does not throw when nothing matches.
  4. 4. What does upsert do?

    upsert looks up by a unique where and runs update when found or create when not.
  5. 5. What happens with prisma.product.deleteMany() and no arguments?

    An empty filter matches all rows. Guard filters that may be empty.

Summary

  • update and delete target one row by a unique where and throw P2025 if it is missing; updateMany and deleteMany take any filter and return a count.
  • Use atomic operators (increment, decrement, multiply, set) instead of read-modify-write.
  • upsert updates or creates by a unique key; be ready to retry on P2002 under heavy concurrency.
  • Consider soft deletes (deletedAt) when data must be recoverable, and guard empty filters.

Next: Counting, Aggregating and Grouping