Convert SQL UNIQUE Constraints to Prisma @unique and @@unique

Learn how single-column and multi-column SQL UNIQUE constraints map to Prisma @unique field attributes and @@unique model attributes.

Advanced Features

Detailed Explanation

Unique Constraints in Prisma

SQL UNIQUE constraints ensure no two rows share the same value (or combination of values). Prisma supports both single-field and multi-field unique constraints.

Single-Column Unique

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  email VARCHAR(320) NOT NULL UNIQUE,
  username VARCHAR(50) NOT NULL,
  CONSTRAINT uq_users_username UNIQUE (username)
);
model User {
  id       Int    @id @default(autoincrement())
  email    String @unique @db.VarChar(320)
  username String @unique @db.VarChar(50)

  @@map("users")
}

Both inline UNIQUE and named CONSTRAINT ... UNIQUE map to Prisma's @unique field attribute.

Multi-Column Unique

CREATE TABLE team_members (
  id SERIAL PRIMARY KEY,
  team_id INTEGER NOT NULL,
  user_id INTEGER NOT NULL,
  role VARCHAR(50) NOT NULL,
  CONSTRAINT uq_team_user UNIQUE (team_id, user_id)
);
model TeamMember {
  id     Int    @id @default(autoincrement())
  teamId Int    @map("team_id")
  userId Int    @map("user_id")
  role   String @db.VarChar(50)

  @@unique([teamId, userId])
  @@map("team_members")
}

Multi-column unique constraints use @@unique([...]) at the model level. This ensures the combination of values is unique across all rows.

Unique vs Index

Feature @@unique @@index
Enforces uniqueness Yes No
Improves query performance Yes Yes
Allows duplicate values No Yes
Used by Prisma for findUnique Yes No

Prisma's findUnique() and findUniqueOrThrow() methods work with both @id and @unique fields. Multi-field unique constraints enable compound findUnique queries:

const member = await prisma.teamMember.findUnique({
  where: {
    teamId_userId: { teamId: 1, userId: 42 }
  }
});

Named Constraints

Prisma allows custom constraint names via the map parameter:

@@unique([teamId, userId], map: "uq_team_user")

The converter preserves the original SQL constraint name using map.

Partial Unique (PostgreSQL)

PostgreSQL supports conditional unique indexes:

CREATE UNIQUE INDEX uq_users_active_email ON users (email) WHERE deleted_at IS NULL;

Prisma does not natively support partial unique constraints. The converter falls back to @default(dbgenerated(...)) or adds a comment noting the limitation.

Unique with Nullable Columns

In most databases, NULL values are exempt from unique constraints — multiple rows can have NULL in a unique column. This is important for optional unique fields like phone:

phone String? @unique

Use Case

Your database has single-column unique constraints on email and username fields, plus a composite unique constraint ensuring each user appears only once per team. The converter maps both patterns to the appropriate Prisma @unique and @@unique syntax.

Try It — SQL to Prisma Schema

Open full tool