Set two or more unique keys in Prisma

July 22, 2024

Using the @@unique() attributes you can set a compound unique constraint.

model TableData {
  id       Int    @id @default(autoincrement())
  tableId  String
  metadata Json
  userId   Int

  @@unique([tableId, userId])
}

Prisma will enforce a unique constraint on the combination of tableId and userId. This means that while tableId and userId can each have duplicate values individually, but the same combination of both values cannot be repeated.

To query this, you need to use a specific structure, in this example tableId_userId. This can be customize using the name field.

const tableData = await prisma.tableData.findUnique({
  where: {
    tableId_userId: {
      tableId: id,
      userId: user.id
    }
  }
})

Read more about in the Prisma Documentation .