Prisma @@unique to SQL Composite UNIQUE Constraint
Convert Prisma @@unique model-level attributes to SQL composite UNIQUE constraints. Learn how multi-column uniqueness differs from single-column @unique.
Detailed Explanation
Composite Unique Constraints
Prisma's @@unique attribute at the model level creates a multi-column uniqueness constraint, ensuring that the combination of values across the specified columns is unique.
Example Prisma Schema
model TenantUser {
id Int @id @default(autoincrement())
tenantId Int @map("tenant_id")
email String
name String
role String @default("member")
@@unique([tenantId, email])
@@map("tenant_users")
}
Generated SQL
CREATE TABLE tenant_users (
id SERIAL PRIMARY KEY,
tenant_id INTEGER NOT NULL,
email VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
role VARCHAR(255) NOT NULL DEFAULT 'member',
UNIQUE (tenant_id, email)
);
How It Differs from @unique
| Attribute | Scope | Example |
|---|---|---|
@unique |
Single column | email String @unique — each email must be unique globally |
@@unique |
Multiple columns | @@unique([tenantId, email]) — the combination must be unique |
With @@unique([tenantId, email]), the same email can exist multiple times as long as each occurrence has a different tenantId. This is essential for multi-tenant applications.
Multiple Composite Uniques
You can have multiple @@unique constraints on the same model:
model Integration {
id Int @id @default(autoincrement())
provider String
externalId String @map("external_id")
tenantId Int @map("tenant_id")
apiKey String @map("api_key")
@@unique([provider, externalId])
@@unique([tenantId, provider])
@@map("integrations")
}
Each @@unique generates a separate UNIQUE (...) constraint in the SQL output. The database enforces all of them independently.
Composite Unique vs Composite Primary Key
While @@unique enforces uniqueness, @@id defines the primary key. A table can have only one primary key but multiple unique constraints. Use @@id when the combination of fields should serve as the row identifier, and @@unique when you just need to prevent duplicates.
Use Case
You are building a multi-tenant SaaS application where each tenant can have users with the same email address as users in other tenants, but within a single tenant, each email must be unique.