Prisma with PostgreSQL: Schema Design, Migrations and Avoiding N+1 Queries
By Muhammad Osama Khan, Software Engineer. Database, Sep 22, 2026, 4 min read.
Model relations, ship migrations without surprises, replace query loops with include and wrap multi-step writes in a transaction.
Prisma gives a Node project a typed client on top of PostgreSQL, with the schema described in one file. It removes a lot of boilerplate, but it does not remove the need to think about queries. This guide covers the parts that matter in a real app: the schema, migrations, N+1 queries and transactions.
Describe the data in schema.prisma
prisma/schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id Int @id @default(autoincrement())
title String
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
createdAt DateTime @default(now())
@@index([authorId, createdAt])
}PostgreSQL does not index foreign keys for you, so add an @@index on the column you filter and sort by (here the author and the date).
Migrations: dev versus production
- Change
schema.prisma. - Run
npx prisma migrate dev --name add_postson your machine. Prisma writes a SQL file intoprisma/migrations, applies it to your local database and regenerates the client. - Read the generated SQL, then commit the migration folder together with the code that needs it.
- In CI or on the server, run
npx prisma migrate deploy. It only applies migrations that already exist and never creates or resets anything.
terminal
# local development
npx prisma migrate dev --name add_posts
# production / CI (applies committed migrations only)
npx prisma migrate deployNever run migrate dev or migrate reset against a production database: both can drop data. Take a backup before a migration that removes or renames columns.
The N+1 query problem
An N+1 happens when you load a list with one query and then run one more query per row. With 100 users that is 101 round trips to the database.
slow.js
const users = await prisma.user.findMany();
for (const user of users) {
// one extra query for every user
user.posts = await prisma.post.findMany({ where: { authorId: user.id } });
}Ask for the relation in the same call. Prisma loads the related rows in a fixed number of queries, however many users there are.
fast.js
const users = await prisma.user.findMany({
select: {
id: true,
name: true,
posts: {
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 5,
select: { id: true, title: true }
}
}
});select also keeps the response small: only the fields the screen needs leave the database. To see what Prisma runs, create the client with new PrismaClient({ log: ['query'] }) while debugging.
Transactions for multi-step writes
When several writes must succeed or fail together, use an interactive transaction. If the callback throws, everything inside it is rolled back.
orders.js
export async function placeOrder(productId, quantity) {
return prisma.$transaction(async (tx) => {
const product = await tx.product.update({
where: { id: productId },
data: { stock: { decrement: quantity } }
});
if (product.stock < 0) throw new Error('Out of stock'); // rolls everything back
return tx.order.create({ data: { productId, quantity } });
});
}One client per process
Every PrismaClient opens its own connection pool. In development, hot reloading can create a new client on each change and exhaust your connections, so keep a single instance.
lib/prisma.js
import { PrismaClient } from '@prisma/client';
const globalForPrisma = globalThis;
export const prisma = globalForPrisma.prisma ?? new PrismaClient();
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;Frequently asked questions
What is the difference between prisma migrate dev and migrate deploy?
migrate dev is for development: it creates a new migration from your schema changes, applies it and may reset the database. migrate deploy is for CI and production: it only applies migrations that already exist and never creates or resets anything.
How do I avoid N+1 queries in Prisma?
Load related rows in the same call with include or a nested select, instead of looping over results and querying for each one. Prisma then fetches them in a fixed number of queries, however many rows there are.
Should I create a new PrismaClient for every request?
No. Each client opens its own connection pool. Create one instance per process, and in development keep it on globalThis so hot reloading does not create a new one on every change.
Does Prisma add indexes on foreign keys in PostgreSQL?
No. PostgreSQL does not index foreign key columns automatically, so add an @@index for the columns you filter or sort by, such as [authorId, createdAt].