Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 36 ยท Client Queries

Creating and Reading Records with Prisma Client

Learn the Prisma Client methods to create and read data: create, createMany, findUnique, findFirst, findMany, the OrThrow variants and count, with a runnable stand-in.

Chapters 1 and 2 built the foundation: a project and a schema. Now you will learn the query API, the methods on prisma.<model>. This lesson covers the two most basic jobs: putting rows in and getting rows out. We use this model throughout the chapter:

PRISMA
model Product {
  id        Int      @id @default(autoincrement())
  name      String
  category  String
  priceCents Int
  stock     Int      @default(0)
  sku       String   @unique
  createdAt DateTime @default(now())
}

The query methods at a glance

Method Returns When nothing matches
create the created row n/a
createMany { count } n/a
createManyAndReturn array of created rows (not on MySQL) n/a
findUnique one row or null null
findUniqueOrThrow one row throws P2025
findFirst the first matching row or null null
findFirstOrThrow the first matching row throws P2025
findMany an array []
count a number 0

Creating one record

TypeScript
const mug = await prisma.product.create({
  data: {
    name: "Blue mug",
    category: "kitchen",
    priceCents: 1200,
    sku: "MUG-001",
  },
});
// { id: 1, name: 'Blue mug', category: 'kitchen', priceCents: 1200, stock: 0, sku: 'MUG-001', createdAt: ... }

data must include every required field that has no default. id, stock and createdAt have defaults, so you may leave them out. create returns the full row, including values generated by the database (the id, the timestamp), which is why you rarely need a second query to read it back.

If a unique field collides, create throws a PrismaClientKnownRequestError with the code P2002.

Creating many records

TypeScript
const result = await prisma.product.createMany({
  data: [
    { name: "Desk lamp", category: "office", priceCents: 3500, sku: "LAMP-01" },
    { name: "Notebook", category: "office", priceCents: 450, sku: "NOTE-01" },
    { name: "Teapot", category: "kitchen", priceCents: 2800, sku: "TEA-01" },
  ],
  skipDuplicates: true,
});
console.log(result.count); // 3

createMany sends one bulk INSERT, so it is much faster than calling create in a loop. Its result is only a count. Use createManyAndReturn when you need the rows (PostgreSQL, CockroachDB and SQLite). skipDuplicates: true silently ignores rows that would violate a unique constraint (not supported on MongoDB). createMany cannot create related records in nested form; that needs separate calls or create (chapter 4).

Reading one record

TypeScript
const byId = await prisma.product.findUnique({ where: { id: 1 } });
const bySku = await prisma.product.findUnique({ where: { sku: "MUG-001" } });

findUnique only accepts fields that are @id or @unique (or a compound key). That is not a limitation to fight: it guarantees at most one result, and it makes TypeScript reject where: { name: "Blue mug" }. For any other criteria use findFirst:

TypeScript
const cheapest = await prisma.product.findFirst({
  where: { category: "office" },
  orderBy: { priceCents: "asc" },
});

Because the result may be null, TypeScript makes you handle it:

TypeScript
const product = await prisma.product.findUnique({ where: { id: 99 } });
if (!product) {
  return notFound();          // handle the missing case
}
console.log(product.name);    // safe here

When a missing row is a genuine error (for example a route /products/99 that must return 404), use the OrThrow variants and catch P2025, or keep the null check. Both styles are fine; pick one per codebase.

Reading many records

TypeScript
const all = await prisma.product.findMany();
const kitchen = await prisma.product.findMany({ where: { category: "kitchen" } });
const total = await prisma.product.count();

findMany() with no arguments returns every row. That is fine in a tutorial and a disaster on a table with a million rows, so get used to adding where and take (pagination is in a later lesson) before you ship anything.

Run it: a stand-in client

The stand-in below implements these methods over an array so you can see the return shapes: objects with defaults filled in, null for a miss, the OrThrow variants, createMany returning a count and unique errors. It supports only equality filters; the next lessons extend it.

Node.js Stand-in: create and read

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.

Passing user input safely

Never spread raw request bodies into data. A client could add role: "ADMIN" or an id you did not intend.

TypeScript
// Dangerous: whatever the client sends goes into the database.
await prisma.user.create({ data: req.body });

// Safe: pick the allowed fields (and validate their types).
const { email, name } = parseSignup(req.body);   // e.g. with Zod
await prisma.user.create({ data: { email, name } });

Validate input first, then hand Prisma only the fields you chose.

A look at the TypeScript types

The generated client gives helper types you can reuse, for example Prisma.ProductCreateInput for the shape of data and the model type Product for rows:

TypeScript
import type { Product, Prisma } from "../generated/prisma/client";

function toInput(form: { name: string; sku: string }): Prisma.ProductCreateInput {
  return { name: form.name, sku: form.sku, category: "general", priceCents: 0 };
}

async function loadProduct(id: number): Promise<Product | null> {
  return prisma.product.findUnique({ where: { id } });
}

Use these types for function parameters so your service layer stays in sync with the schema.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method should you use to find a product by a non-unique field such as category?

    findUnique accepts only unique fields. For other criteria use findFirst (one row) or findMany (many rows).
  2. 2. What does createMany return?

    createMany returns { count }. Use createManyAndReturn (where supported) to get the rows back.
  3. 3. What does findUnique return when no row matches?

    It returns null; findUniqueOrThrow throws instead (code P2025).
  4. 4. Why is prisma.product.findMany() with no arguments risky in production?

    Without where and take it returns the whole table, which can exhaust memory and slow the database.

Summary

  • create returns the stored row; createMany returns a count and is much faster than a loop.
  • findUnique needs @id or @unique fields and returns null on a miss; findFirst and findMany accept any filter.
  • OrThrow variants raise P2025 instead of returning null.
  • Validate user input and pass only chosen fields to data.

Next: Filtering with where