How to Create Prisma Migrations

Migrations are needed to update your database as your application evolves.

Prisma offers a simple way to manage migrations.

Here's a concise article with an example to show you how:

Example Changes

Suppose you're adding a UserProfile table to your database. You would start by defining this new model in your Prisma schema file (prisma/schema.prisma):

model UserProfile {
  id        Int      @id @default(autoincrement())
  bio       String?
  userId    Int      @unique
  user      User     @relation(fields: [userId], references: [id])

Applying Changes with Migrations

After updating your schema, you apply these changes with the following command:

npx prisma migrate dev --name add_user_profile

This command does two main things:

  • It creates a new migration file in prisma/migrations that records your schema changes.
  • Then updates your database schema according to the changes in your Prisma schema file.

Some notes

  • Naming Your Migration: Replace add_user_profile with a descriptive name. This helps track and understand the purpose of each migration.
  • Review and Apply: Prisma prompts you to review your migration. Ensure everything is correct before applying the changes to your database.
  • Rolling Back: Use prisma migrate reset to revert your database to an initial state if necessary. Be cautious, as this deletes all data.

Always back up your data before executing significant schema changes.

Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.


Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.