SQL ADD CONSTRAINT Keyword

The ADD CONSTRAINT keyword in SQL is used to add a constraint to an existing table. Constraints are rules that help ensure data integrity by enforcing restrictions on the data that can be stored in a table.



ADD CONSTRAINT: Definition and Usage

Adding constraints after table creation is useful when you need to add additional rules or validation to your data. You might do this, for example, if you initially missed a constraint or if your data requirements change.

Syntax

Syntax

ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type (column1, column2, ...);
      

Replace constraint_type with the type of constraint you want to add (e.g., PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK).

Example: Adding a Primary Key Constraint

This example adds a primary key constraint named 'PK_Person' to the 'Persons' table, using 'ID' and 'LastName' as the composite key. This means that the combination of 'ID' and 'LastName' must be unique for each row in the table.

Syntax

ALTER TABLE Persons
ADD CONSTRAINT PK_Person PRIMARY KEY (ID, LastName);
      
Output

A primary key constraint named 'PK_Person' is added to the 'Persons' table. The combination of the 'ID' and 'LastName' columns is now a primary key, enforcing uniqueness.