How to Create if it Does Not Exist using Prisma


How can we simulate a “create if not exists” query in Prisma?

Ideally, we’d like to avoid manually running a SELECT/findUnique() query and placing our INSERT/create() inside a conditional.

Prisma provides us with upsert() (similar to findOrCreate() with updates) to create a record only if it does not exist. If it does exist, we can update the fields if we’d like to.

Create if not exists using upsert()

Suppose we want to update the name of all User records whose email is you@example.com.

const upsertUser = await prisma.user.upsert({
  where: {
    email: 'you@example.com',
  },
  update: {
    name: 'Bob',
  },
  create: {
    email: 'you@example.com',
    name: 'Bob',
  },
});

First, we’ll specify the WHERE clause using where.

Then, we’ll specify what field to update if the record already exists using update.

Finally, if the record does not exist, we’ll create the record using create.

Do not update if not exists using upsert()

We can also use upsert() to create but not update if a record does not exist.

We can simply leave the update property empty.

const upsertUser = await prisma.user.upsert({
  where: {
    email: 'you@example.com',
  },
  update: {},
  create: {
    email: 'you@example.com',
    name: 'Bob',
  },
});

Read more on upsert() in the Prisma documentation.