SQL ADD CONSTRAINT Keyword
The ADD CONSTRAINT
command is used to add a constraint to an existing table after it has been created. Constraints help enforce rules for the data in a table.
SQL ADD CONSTRAINT Common Constraint Types
PRIMARY KEY
FOREIGN KEY
UNIQUE
CHECK
DEFAULT
SQL ADD CONSTRAINT Syntax
SQL
x
1
ALTER TABLE table_name
2
ADD CONSTRAINT constraint_name constraint_type (column1, column2, ...);
SQL ADD CONSTRAINT Example
This query adds a primary key constraint named PK_Patient
on the patient_id
and last_name
columns of the Patients
table:
SQL
1
1
ALTER TABLE Patients
2
ADD CONSTRAINT PK_Patient PRIMARY KEY (patient_id, last_name);
Note: This syntax may not be supported in our playground. If you receive a syntax error near
"CONSTRAINT"
, it means our playground does not support adding named constraints usingADD CONSTRAINT
.As a workaround, constraints like primary keys should be defined at the time of table creation, or use simplified constraint syntax if available.