Single-column uniqueness
Prevent duplicate email addresses in a users table.
Drizzle ORM · Function
Drizzle’s unique declaration adds a database constraint that rejects duplicate values in one column or a combination of columns. It can be named and is commonly used in a table callback for composite uniqueness.
Drizzle’s unique declaration creates a database-level uniqueness constraint for one or more columns. Use it in a table callback for composite constraints, optionally give the constraint a name, and use the PostgreSQL-specific modifier when the documentation’s NULL handling option is required.
unique(name?).on(...columns)| Name | Type | Description |
|---|---|---|
name | string | undefined | Optional constraint name; omit it for an automatically named constraint. |
columns | AnyColumn[] | One or more table columns covered by the constraint. |
A table constraint declaration used in the table schema definition.
NULLS NOT DISTINCT option when defining a MySQL unique constraint.import { pgTable, text, unique } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: text("id").notNull(),
email: text("email").notNull(),
}, (table) => ({
emailNameUnique: unique("users_email_unique").on(table.email),
}));Defines a PostgreSQL table whose email column must be unique, using a named table-level constraint.
Prevent duplicate email addresses in a users table.
Require each pair of values, such as tenant and slug, to be unique.
Give a migration-visible constraint a predictable identifier.
unique declaration do?The unique declaration adds a database uniqueness constraint over one or more columns. A named constraint can be created with unique("name").on(table.column).
Follow-up: How would you enforce uniqueness across two columns? Use unique("name").on(table.first, table.second) in the table callback.
A column-level .unique() is suitable for a single column. The table callback form, unique().on(...), supports multi-column uniqueness and can also assign a custom constraint name.
Follow-up: Why use a named constraint? A stable name makes generated schema and migration output easier to identify and manage.
PostgreSQL supports the NULLS NOT DISTINCT behavior through the unique-constraint API. This restricts a table from having more than one null value for the constrained columns.
Follow-up: Is this portable to MySQL? No; the documentation states that MySQL does not support this option.
unique indexprimary keypgTablemysqlTablesqliteTable