Prisma ORM and Migrations

Define your schema in Prisma, generate a type-safe client, run migrations and write efficient queries from TypeScript.

Intermediate · about 8 hours · difficulty 3/5

Learn first: Relational Data Modelling in PostgreSQL, TypeScript Fundamentals

Prisma is the most popular TypeScript ORM. You describe models in schema.prisma, and Prisma generates a fully typed client and SQL migrations from it.

The workflow

  • Define models, relations and constraints in schema.prisma.
  • Run prisma migrate dev to create and apply a migration file, and commit it.
  • In production and CI, run prisma migrate deploy to apply pending migrations.
  • Use Prisma Studio to browse data during development.

Querying

  • findMany, findUnique, create, update, delete with fully typed inputs and results.
  • select and include to fetch only the fields and relations you need.
  • Transactions with prisma.$transaction for multi-step writes.
  • Raw SQL with tagged templates when a query is easier to express directly.

Running it well

Create one PrismaClient instance and reuse it; in Next.js development, store it on globalThis to survive hot reloads. On serverless platforms, use a pooled connection string from your database provider.

Pitfalls

  • N+1 queries: fetching a list, then querying each item's relation in a loop. Use include or a single query.
  • Editing old migration files that have already run in production.
  • Returning whole user records (with passwordHash) to the client instead of selecting fields.

You are ready to move on when your placement portal uses Prisma with committed migrations, a seed script, and list queries that fetch related data in one round trip.

Key concepts

  • schema.prisma models and relations
  • migrate dev and migrate deploy
  • CRUD with the typed client
  • select and include
  • Transactions
  • Seeding data
  • Avoiding N+1 queries
  • Connection pooling for serverless

Other options for this step

  • Drizzle ORM and Migrations: Use Drizzle's SQL-like TypeScript API to define schemas, generate migrations and write type-safe queries with no heavy runtime.

Mini project

Model the placement portal in Prisma, create migrations, write a seed script with realistic Indian company and college data, and implement a service that lists openings with company details and applicant counts in a single query.

Check yourself

Your openings page makes 51 database queries for 50 openings. What is this problem called and how do you fix it with Prisma?

Free resources