ADD CONSTRAINT is used with ALTER TABLE to attach a new integrity rule to a table after it has been created. By naming the constraint you can later reference it to modify or drop it. Supported constraint types include PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and DEFAULT. The database immediately validates the rule against existing data unless you specify options such as NOT VALID (PostgreSQL) or WITH NOCHECK (SQL Server). If existing rows violate the rule, the statement fails unless the dialect supports and you choose deferred validation. Adding constraints can implicitly create supporting indexes (for example, most systems build an index for a new primary key or unique constraint). Be mindful of lock levels: some engines require a table rewrite or blocking lock while the constraint is validated.
table_name
(identifier) - Name of the table being alteredconstraint_name
(identifier) - User-defined name for the constraintconstraint_type
(keyword) - PRIMARY KEY|||FOREIGN KEY|||UNIQUE|||CHECK|||DEFAULTconstraint_body
(varies) - Column list or expression defining the ruleALTER TABLE, DROP CONSTRAINT, PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, DEFAULT, NOT NULL
SQL-92 standard
You can add PRIMARY KEY, FOREIGN KEY, UNIQUE, CHECK, and DEFAULT constraints. Support for DEFAULT with ADD CONSTRAINT varies by dialect (native in SQL Server).
Use ALTER TABLE table_name DROP CONSTRAINT constraint_name; Always record the name when you create the constraint so dropping it is straightforward.
Validating the constraint can be costly on large tables, and supporting indexes increase storage. However, query performance often improves for joins and lookups on the constrained columns.
Some databases (PostgreSQL, Oracle) allow DEFERRABLE constraints that are checked at COMMIT. Specify DEFERRABLE INITIALLY DEFERRED when creating or altering the constraint.