You can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
Indexes & Constraints
Constraints
SQL constraints are the rules enforced on table columns. They are used to prevent invalid data from being entered into the database.
This ensures the accuracy and reliability of your data in the database.
Default
The DEFAULT clause specifies a default value to use for the column if no value provided by the user when doing an INSERT.
If there is no explicit DEFAULT clause attached to a column definition,
then the default value of the column is NULL.
An explicit DEFAULT clause may specify that the default value is NULL,
a string constant, a blob constant, a signed-number, or any constant expression enclosed in parentheses.
import { sql } from "drizzle-orm";
import { int, time, mysqlTable } from "drizzle-orm/mysql-core";
export const table = mysqlTable("table", {
int: int().default(42),
time: time().default(sql`cast("14:06:10" AS TIME)`),
});CREATE TABLE `table` (
`int` int DEFAULT 42,
`time` time DEFAULT (cast("14:06:10" AS TIME))
);Not null
By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.
import { int, mysqlTable } from "drizzle-orm/mysql-core";
export const table = mysqlTable('table', {
int: int().notNull(),
});CREATE TABLE `table` (
`int` int NOT NULL
);Unique
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
In MySQL, a unique constraint and a unique index are essentially the same thing.
Under the hood, MySQL implements a unique constraint as a unique index.
There is no separate constraint object like you might find in some other databases.
-- These three all produce the exact same result in MySQL:
ALTER TABLE users ADD CONSTRAINT uq_email UNIQUE (email);
ALTER TABLE users ADD UNIQUE INDEX uq_email (email);
CREATE UNIQUE INDEX uq_email ON users(email);To drop a unique constraint, the same syntax is used as dropping an index: ALTER TABLE users DROP INDEX uq_email;. There’s no separate DROP CONSTRAINT statement for it in MySQL.
That is why Drizzle always treats any .unique() as UNIQUE INDEX
import { int, varchar, unique, mysqlTable } from "drizzle-orm/mysql-core";
export const user = mysqlTable('user', {
id: int().unique(),
});
export const table = mysqlTable('table', {
id: int().unique('custom_name'),
});
export const composite = mysqlTable('composite_example', {
id: int(),
name: varchar(, { length: 256 }),
}, (t) => [
unique().on(t.id, t.name),
unique('custom_name').on(t.id, t.name)
]);CREATE TABLE `user` (
`id` int,
CONSTRAINT `id_unique` UNIQUE INDEX(`id`)
);
CREATE TABLE `table` (
`id` int,
CONSTRAINT `custom_name` UNIQUE INDEX(`id`)
);
CREATE TABLE `composite_example` (
`id` int,
`name` varchar(256),
CONSTRAINT `id_name_unique` UNIQUE INDEX(`id`,`name`),
CONSTRAINT `custom_name` UNIQUE INDEX(`id`,`name`)
);Check
The CHECK constraint is used to limit the value range that can be placed in a column.
If you define a CHECK constraint on a column it will allow only certain values for this column.
If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.
import { sql } from "drizzle-orm";
import { check, int, mysqlTable, text } from "drizzle-orm/mysql-core";
export const users = mysqlTable(
"users",
{
id: int().primaryKey(),
username: text().notNull(),
age: int(),
},
(table) => [
check("age_check1", sql`${table.age} > 21`)
]
);CREATE TABLE `users` (
`id` int PRIMARY KEY,
`username` text NOT NULL,
`age` int,
CONSTRAINT `age_check1` CHECK(`users`.`age` > 21)
);Primary Key
The PRIMARY KEY constraint uniquely identifies each record in a table.
Primary keys must contain UNIQUE values, and cannot contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).
import { int, text, mysqlTable } from "drizzle-orm/mysql-core";
export const user = mysqlTable("user", {
id: int().autoincrement().primaryKey(),
})
export const table = mysqlTable("table", {
cuid: text().primaryKey(),
})CREATE TABLE `user` (
`id` int AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE `table` (
`cuid` text PRIMARY KEY
);Composite Primary Key
Just like PRIMARY KEY, composite primary key uniquely identifies each record in a table using multiple fields.
Drizzle ORM provides a standalone primaryKey operator for that:
import { int, text, primaryKey, mysqlTable } from "drizzle-orm/mysql-core";
export const user = mysqlTable("user", {
id: int("id").autoincrement().primaryKey(),
name: text("name"),
});
export const book = mysqlTable("book", {
id: int().autoincrement().primaryKey(),
name: text(),
});
export const booksToAuthors = mysqlTable("books_to_authors", {
authorId: int(),
bookId: int(),
}, (table) => [
primaryKey({ columns: [table.bookId, table.authorId] }),
// Or PK with custom name
primaryKey({ name: 'custom_name', columns: [table.bookId, table.authorId] })
]);...
CREATE TABLE `books_to_authors` (
`author_id` int,
`book_id` int,
PRIMARY KEY(`book_id`,`author_id`)
);Foreign key
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.
Drizzle ORM provides several ways to declare foreign keys. You can declare them in a column declaration statement:
import { int, text, mysqlTable } from "drizzle-orm/mysql-core";
export const user = mysqlTable("user", {
id: int().primaryKey().autoincrement(),
name: text(),
});
export const book = mysqlTable("book", {
id: int().primaryKey().autoincrement(),
name: text(),
authorId: int("author_id").references(() => user.id)
});If you want to do a self reference, due to a TypeScript limitations you will have to either explicitly
set return type for reference callback or use a standalone foreignKey operator.
import { int, text, foreignKey, type AnyMySqlColumn, mysqlTable } from "drizzle-orm/mysql-core";
export const user = mysqlTable("user", {
id: int().primaryKey().autoincrement(),
name: text(),
parentId: int("parent_id").references((): AnyMySqlColumn => user.id),
});
// or
export const user = mysqlTable("user", {
id: int().primaryKey().autoincrement(),
name: text(),
parentId: int("parent_id")
}, (table) => [
foreignKey({
columns: [table.parentId],
foreignColumns: [table.id],
name: "custom_fk"
})
]);To declare multi-column foreign keys you can use a dedicated foreignKey operator:
import { int, text, primaryKey, foreignKey, mysqlTable, type AnyMySqlColumn } from "drizzle-orm/mysql-core";
export const user = mysqlTable("user", {
firstName: text("firstName"),
lastName: text("lastName"),
}, (table) => [
primaryKey({ columns: [table.firstName, table.lastName]})
]);
export const profile = mysqlTable("profile", {
id: int().autoincrement().primaryKey(),
userFirstName: text("user_first_name"),
userLastName: text("user_last_name"),
}, (table) => [
foreignKey({
columns: [table.userFirstName, table.userLastName],
foreignColumns: [user.firstName, user.lastName],
name: "custom_name"
})
]);Indexes
Drizzle ORM provides API for both index and unique index declaration:
import { int, text, index, uniqueIndex, mysqlTable } from "drizzle-orm/mysql-core";
export const user = mysqlTable("user", {
id: int("id").primaryKey().autoincrement(),
name: text("name"),
email: text("email"),
}, (table) => [
index("name_idx").on(table.name),
uniqueIndex("email_idx").on(table.email),
]);CREATE TABLE `user` (
...
);
CREATE INDEX `name_idx` ON `user` (`name`);
CREATE UNIQUE INDEX `email_idx` ON `user` (`email`);Drizzle ORM provides set of all params for index creation:
// Index declaration reference
index("name")
.on(table.name)
.algorithm("default") // "default" | "copy" | "inplace"
.using("btree") // "btree" | "hash"
.lock("default") // "none" | "default" | "exclusive" | "shared"