Enforce unique email addresses
User accounts
Prisma · Const
@unique defines a single-field unique constraint in a Prisma model. It can identify records through a scalar field and automatically corresponds to a unique database index.
Apply @unique to a scalar field to require distinct stored values and create a unique database constraint. It may be optional or required; however, when it is the sole unique identifier of a model without @id or @@id, the field must be required. Use @@unique for a constraint spanning multiple fields.
@unique(map: String?, length: number?, sort: String?, clustered: Boolean?, where: raw(String) | { field: value }?)| Name | Type | Description |
|---|---|---|
map | String? | Optional database constraint and index name override. |
length | number? | Optional index length configuration. |
sort | String? | Optional index sort direction. |
clustered | Boolean? | Optional clustered-index setting. |
where | raw(String) | { field: value }? | Optional filtered or partial-index predicate. |
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}The required email field can uniquely identify each User record.
User accounts
External identifiers
One-to-one relations
@unique defines a unique constraint for one scalar field, so values in that column must be distinct. It may be optional or required, but it must be required when it is the only unique constraint on a model without an ID.
Follow-up: How would you enforce uniqueness across several fields? Use the model-level @@unique attribute with the participating scalar fields.
A model can have any number of unique constraints, and @unique can be applied to any scalar field. Each application represents a single-field constraint rather than a compound constraint.
Follow-up: What is the corresponding syntax for a compound constraint? Use @@unique([fieldA, fieldB]) at model level.
Adding @unique automatically adds a corresponding unique index to the specified column. The database therefore receives both the uniqueness enforcement and its associated index through the schema definition.
Follow-up: How can the underlying constraint or index name be customized? Supply the optional map argument to @unique.
@@unique@id@@id@map@relation