Skip to the content

Lesson 230 of 296

Prisma

What you will learn

  • What an ORM is and what Prisma does
  • The Prisma schema
  • Prisma 7 setup with a driver adapter
  • Migrations with Prisma Migrate
  • CRUD queries, relations and avoiding N+1
  • Transactions, raw SQL and multi-tenant filters
  • ORM trade-offs
On this page

What is an ORM?

An ORM (Object-Relational Mapper) lets you work with database rows as objects in your programming language, writing method calls instead of SQL strings. Prisma is the most popular ORM for TypeScript: you describe your data in a schema file, and Prisma generates a fully typed client, so prisma.customer.findMany() returns correctly typed objects and TypeScript catches typos in field names. Alternatives: Drizzle (SQL-like, lightweight), TypeORM, MikroORM, Kysely (a typed query builder).

At the time of writing, Prisma 7 is the current stable major version (Prisma 8 is in release-candidate testing). Prisma 7 changed several things from version 6, noted below. The schema, configuration and queries in this lesson were run with Prisma 7.10.1 against a real PostgreSQL database: the migration was generated and applied, and every query below executed successfully.

The schema

prisma/schema.prisma describes models (tables), fields (columns) and relations:

generator client {
  provider = "prisma-client"
  output   = "../src/generated/prisma"
}

datasource db {
  provider = "postgresql"
}

model Customer {
  id        Int      @id @default(autoincrement())
  name      String
  email     String   @unique
  city      String?
  createdAt DateTime @default(now()) @map("created_at")
  orders    Order[]

  @@map("customers")
}

model Order {
  id         Int         @id @default(autoincrement())
  customerId Int         @map("customer_id")
  customer   Customer    @relation(fields: [customerId], references: [id])
  status     OrderStatus @default(PENDING)
  version    Int         @default(1)
  orderedAt  DateTime    @default(now()) @map("ordered_at")
  items      OrderItem[]

  @@index([customerId, orderedAt(sort: Desc)])
  @@map("orders")
}

model Product {
  id         Int         @id @default(autoincrement())
  name       String
  pricePence Int         @map("price_pence")
  items      OrderItem[]

  @@map("products")
}

model OrderItem {
  orderId        Int     @map("order_id")
  productId      Int     @map("product_id")
  quantity       Int
  unitPricePence Int     @map("unit_price_pence")
  order          Order   @relation(fields: [orderId], references: [id], onDelete: Cascade)
  product        Product @relation(fields: [productId], references: [id])

  @@id([orderId, productId])
  @@map("order_items")
}

enum OrderStatus {
  PENDING
  PAID
  CANCELLED
}
  • ? makes a field optional (nullable).
  • @id, @unique, @default, @relation, @@index, @@id (composite key) map to the constraints and indexes of the previous lessons.
  • @map and @@map keep camelCase in TypeScript and snake_case in the database.
  • Relation fields (customer, orders) exist only in Prisma; the real column is customerId.

Prisma 7 setup

Changes in Prisma 7 (from the official upgrade guide):

  • The generator is prisma-client (the old prisma-client-js is being removed), and an output path is required: the client is generated into your source folder, not node_modules.
  • The new client is Rust-free and needs a driver adapter for every database: @prisma/adapter-pg for PostgreSQL.
  • Connection settings move to prisma.config.ts at the project root; .env files are not loaded automatically any more (use dotenv or node --env-file).
  • Prisma ships as an ES module.
import "dotenv/config";
import { defineConfig, env } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: { path: "prisma/migrations" },
  datasource: { url: env("DATABASE_URL") }
});

Creating the client:

import { PrismaClient } from "./generated/prisma/client.js";
import { PrismaPg } from "@prisma/adapter-pg";

const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
export const prisma = new PrismaClient({ adapter });

Create one PrismaClient for the whole application and reuse it: each one holds a connection pool.

Migrations

  • npx prisma migrate dev --name add_orders: compares the schema with the database, writes a SQL migration file, applies it, and regenerates the client. For development.
  • npx prisma migrate deploy: applies pending migrations, never creates new ones. For CI and production (Lesson 228).
  • npx prisma generate: regenerates the typed client after schema changes.
  • The generated migration is plain SQL you can edit before applying (for example to add CONCURRENTLY or a backfill step).

Queries

const customer = await prisma.customer.create({
  data: { name: "Aisha Khan", email: "aisha@example.com", city: "London" }
});

const londoners = await prisma.customer.findMany({
  where: { city: "London", email: { endsWith: "@example.com" } },
  orderBy: { name: "asc" },
  select: { id: true, name: true }
});

const one = await prisma.customer.findUnique({ where: { email: "aisha@example.com" } });

await prisma.customer.update({ where: { id: customer.id }, data: { city: "Leeds" } });

await prisma.customer.upsert({
  where: { email: "ben@example.com" },
  create: { name: "Ben Smith", email: "ben@example.com" },
  update: { name: "Ben Smith" }
});

select returns only the chosen fields, and TypeScript knows the exact shape of the result.

Relations and N+1

const orders = await prisma.order.findMany({
  where: { status: "PAID" },
  include: { customer: { select: { name: true } }, items: { include: { product: true } } },
  orderBy: { orderedAt: "desc" },
  take: 20
});

include loads the related data in a fixed number of queries (or one query with joins, depending on the relation load strategy), not one per order. The N+1 trap (Lesson 221) appears when you loop over results and call prisma.customer.findUnique for each: use include, or collect the IDs and use findMany({ where: { id: { in: ids } } }).

Aggregates:

const totals = await prisma.order.groupBy({
  by: ["status"],
  _count: { _all: true }
});

Transactions

await prisma.$transaction(async (tx) => {
  const order = await tx.order.create({ data: { customerId: 1, status: "PENDING" } });
  await tx.orderItem.create({ data: { orderId: order.id, productId: 2, quantity: 1, unitPricePence: 450 } });
});

If the function throws, everything is rolled back. Use the tx client inside, not the global prisma. Options include isolationLevel: "Serializable". Atomic increments avoid lost updates: data: { stock: { decrement: 1 } }.

Optimistic locking (Lesson 225):

const result = await prisma.order.updateMany({
  where: { id: 101, version: 3 },
  data: { status: "PAID", version: { increment: 1 } }
});
if (result.count === 0) throw new Error("Conflict: order was changed by someone else");

Raw SQL when needed

For complex reports, window functions or performance-critical queries, write SQL, safely parameterised:

const rows = await prisma.$queryRaw<{ name: string; spent: bigint }[]>`
  SELECT c.name, SUM(oi.quantity * oi.unit_price_pence) AS spent
  FROM customers c
  JOIN orders o ON o.customer_id = c.id
  JOIN order_items oi ON oi.order_id = o.id
  GROUP BY c.id, c.name
  HAVING SUM(oi.quantity * oi.unit_price_pence) > ${4000}
`;

The tagged template turns ${...} into parameters, not string concatenation, so it is safe from SQL injection. Never use $queryRawUnsafe with user input. Note: PostgreSQL SUM of integers returns a bigint, which Prisma gives you as a JavaScript BigInt.

Multi-tenant filters with client extensions

A Prisma client extension can add the tenant filter to every query automatically (Lesson 203). This example assumes an Invoice model with a tenantId field, which is not in the schema above:

function forTenant(tenantId: number) {
  return prisma.$extends({
    query: {
      invoice: {
        async findMany({ args, query }) {
          args.where = { ...args.where, tenantId };
          return query(args);
        }
      }
    }
  });
}

In practice you extend every operation and model that is tenant-owned (or set app.tenant_id for row-level security in a transaction), and test that cross-tenant access fails.

ORM trade-offs

ProsCons
Type-safe queries and resultsCan hide inefficient SQL; check generated queries and N+1
Faster development for CRUDComplex reports are easier in SQL
Migrations and schema in one placeAnother abstraction to learn and upgrade
Safe parameterisation by defaultVendor-specific features (exclusion constraints, RLS, partial indexes) may need raw SQL in migrations

The professional position: use the ORM for most work, read the SQL it generates (enable query logging), and drop to raw SQL when it is clearer or faster.

How to say it in an interview

"Prisma is a TypeScript ORM where a schema file defines models, relations, constraints and indexes, and a generated client gives fully typed queries. In Prisma 7 the generator is prisma-client with a required output path, every database needs a driver adapter such as adapter-pg, and configuration lives in prisma.config.ts. I use migrate dev locally and migrate deploy in CI, review the generated SQL, use select and include to load exactly what I need and avoid N+1, interactive transactions with the tx client, atomic increments and version checks against lost updates, and tagged-template queryRaw for complex SQL, never the unsafe variant with user input. I enable query logging to check what the ORM generates."

Key words

WordMeaning
ORMMaps database rows to objects in code
Prisma schemaThe file defining models, fields and relations
Prisma ClientThe generated, typed query API
Driver adapterConnects Prisma 7's client to a database driver
prisma migrate dev / deployCreate-and-apply migrations / apply only
include / selectLoad relations / choose fields
$transactionRun queries in one transaction
$queryRawSafe parameterised raw SQL
Client extensionAdds behaviour to every query (e.g. tenant filters)

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.