Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

Your First Prisma Queries

Walk through a complete first Prisma script: connect, create records, read them back, update, delete and disconnect, with a runnable stand-in for the client.

You have a project, a schema and a generated client. Now comes the fun part: using the client. This lesson walks through one complete script from top to bottom. You will create rows, read them back, change one and delete one, which covers the four operations (create, read, update, delete, or CRUD) that make up most application code.

The schema we use is the one from the first lesson:

PRISMA
model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
}

After npx prisma migrate dev --name init (you will learn migrations in chapter 5) the table exists, and the script below can talk to it.

The script

TypeScript
// src/index.ts
import { prisma } from "./db";

async function main() {
  // CREATE
  const ada = await prisma.user.create({
    data: { email: "[email protected]", name: "Ada" },
  });
  console.log("created:", ada);

  // READ
  const all = await prisma.user.findMany();
  console.log("all users:", all);

  const one = await prisma.user.findUnique({ where: { email: "[email protected]" } });
  console.log("found:", one?.name);

  // UPDATE
  const renamed = await prisma.user.update({
    where: { id: ada.id },
    data: { name: "Ada Lovelace" },
  });
  console.log("updated:", renamed.name);

  // DELETE
  await prisma.user.delete({ where: { id: ada.id } });
  console.log("count after delete:", await prisma.user.count());
}

main()
  .catch((error) => {
    console.error(error);
    process.exitCode = 1;
  })
  .finally(async () => {
    await prisma.$disconnect();
  });

Run it with npx tsx src/index.ts. A few things to notice:

  • Everything is async. Each call returns a Promise, so you await it. Forgetting await is the most common beginner bug: you get a Promise object instead of data, and errors surface later as "unhandled rejection".
  • Calls are named after the model. The User model gives you prisma.user (the first letter becomes lowercase). The BlogPost model would give prisma.blogPost.
  • Arguments are plain objects. data is what to write, where selects rows. Each method accepts a small, predictable set of keys that you will meet in the next chapters.
  • Return values are typed. ada has the type { id: number; email: string; name: string | null }, and one is that type or null, so one?.name is required by the compiler.
  • $disconnect() closes the connection pool, which lets a short script exit. In a long-running server you usually do not disconnect, except when shutting down.

Run the same flow with a stand-in

Since we cannot install Prisma here, this stand-in implements the same method names on top of an array. It is intentionally tiny (equality filters only) and is reused in a more complete form in later lessons.

Node.js Stand-in: the first script, end to end

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.

What happens when something goes wrong

Database operations can fail. A unique email that already exists, a record that was deleted by someone else, a lost connection. Real Prisma throws errors with a code you can test, for example P2002 for a unique constraint violation and P2025 for "record not found". A later chapter covers them in depth; for now, see the idea:

Node.js Stand-in: catching a unique-constraint error

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.

Turning P2002 into a friendly message is exactly how sign-up forms should react to duplicate emails.

Habits to start with

  1. Always await, and handle errors at a sensible boundary (one try/catch in a route handler, not around every call).
  2. Never build SQL from user input yourself. The client sends parameterized queries, so user text cannot change the structure of the SQL.
  3. Select only what you need once you know how (next chapters).
  4. Keep one client instance and import it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which client property do you use to query a model named BlogPost?

    The accessor is the model name with a lowercase first letter: prisma.blogPost.
  2. 2. What type does findUnique return when no row matches?

    findUnique returns null when nothing matches (findUniqueOrThrow throws instead), so TypeScript forces you to handle null.
  3. 3. What goes wrong if you forget await before prisma.user.create(...)?

    Client methods return Promises. Without await you hold a Promise and errors may become unhandled rejections.
  4. 4. Which error code means a unique constraint was violated?

    P2002 is the unique constraint violation. P2025 means a record needed by the operation was not found.

Summary

  • CRUD maps to create, findMany / findUnique, update and delete.
  • Every method is async, takes a plain options object and returns typed results.
  • $disconnect() closes the pool when a script ends.
  • Catch known errors such as P2002 and turn them into helpful messages.

Next: The Prisma CLI and Prisma Studio