Skip to main content
Constraints offer additional data integrity by enforcing conditions on the data within a column. Whenever values are manipulated (inserted, deleted, or updated), constraints are checked and modifications that violate constraints are rejected. For example, the UNIQUE constraint requires that all values in a column be unique from one another (except NULL values). If you attempt to write a duplicate value, the constraint rejects the entire statement.

Supported constraints

Using constraints

Add constraints

How you add constraints depends on the number of columns you want to constrain, as well as whether or not the table is new.
  • One column of a new table has its constraints defined after the column’s data type. For example, this statement applies the PRIMARY KEY constraint to foo.a:
  • Multiple columns of a new table have their constraints defined after the table’s columns. For example, this statement applies the PRIMARY KEY constraint to foo’s columns a and b:
The DEFAULT and NOT NULL constraints cannot be applied to multiple columns.
  • Existing tables can have the following constraints added:
    • CHECK, FOREIGN KEY, and UNIQUE constraints can be added through ALTER TABLE...ADD CONSTRAINT. For example, this statement adds the UNIQUE constraint to baz.id:
    • DEFAULT values and NOT NULL constraints can be added through ALTER TABLE...ALTER COLUMN. For example, this statement adds the DEFAULT value constraint to baz.bool:
    • PRIMARY KEY constraints can be added with ADD CONSTRAINT/ADD PRIMARY KEY in the following circumstances:
      • A DROP CONSTRAINT statement precedes the ADD CONSTRAINT/ADD PRIMARY KEY statement in the same transaction. For examples, see Add constraints and Drop constraints.
      • The current primary key is on rowid, the default primary key created if none is explicitly defined at table creation.
      • The ADD CONSTRAINT/ADD PRIMARY KEY is in the same transaction as a CREATE TABLE statement with no primary key defined.

Order of constraints

The order in which you list constraints is not important because constraints are applied to every modification of their respective tables or columns.

Name constraints on new tables

You can name constraints applied to new tables using the CONSTRAINT clause before defining the constraint:

View constraints

To view a table’s constraints, use SHOW CONSTRAINTS or SHOW CREATE.

Remove constraints

The procedure for removing a constraint depends on its type:

Change constraints

The procedure for changing a constraint depends on its type:

See also