Purpose

Adds a constraint to an existing table. It is optional.

This command adds a constraint using the same syntax as the Create Table command (see Constraint Definition for Local Tables).

Syntax

ADD [CONSTRAINT constraint_name] ...

Notes

  • You cannot add a Unique constraint if one is already assigned to the same column list. A Unique constraint works only if the values of the columns in the constraint columns list for the existing rows are unique or include a Null value.
  • Adding a foreign key constraint to the table fails if, for each existing row in the referring table, a matching row (with equal values for the column list) is not found in the referenced table.

Example

Assuming the current schema is PUBLIC, this example adds a foreign key constraint to the deptId column of the test table that references the rowId of the dept table.

ALTER TABLE test ADD CONSTRAINT test_fk FOREIGN KEY (deptId) REFERENCES dept(id)