Add Constraint
The ADD CONSTRAINT statement is used to define a new constraint on an existing table. It supports primary keys, foreign keys, unique constraints, checks, and defaults.
Synopsis
Parameters
Examples
Remarks
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
{ PRIMARY KEY (column_list)
| UNIQUE (column_list)
| FOREIGN KEY (column_list) REFERENCES ref_table (ref_column_list)
| CHECK (expression)
| DEFAULT default_value FOR column_name };
| Parameter | Description |
|---|---|
| table_name | Name of the table to modify. |
| constraint_name | Identifier for the new constraint. |
| column_list | Comma‑separated list of columns the constraint applies to. |
| ref_table | Referenced table for a foreign key. |
| ref_column_list | Columns in the referenced table. |
| expression | Boolean expression for a CHECK constraint. |
| default_value | Literal value for a DEFAULT constraint. |
Primary Key
ALTER TABLE Employees
ADD CONSTRAINT PK_Employees PRIMARY KEY (EmployeeID);
Foreign Key
ALTER TABLE Orders
ADD CONSTRAINT FK_Orders_Customers
FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID);
Check Constraint
ALTER TABLE Products
ADD CONSTRAINT CHK_Price CHECK (Price > 0);
Unique Constraint
ALTER TABLE Users
ADD CONSTRAINT UQ_Username UNIQUE (Username);
Default Constraint
ALTER TABLE Orders
ADD CONSTRAINT DF_OrderDate DEFAULT GETDATE() FOR OrderDate;
- Constraints enforce data integrity and cannot be added if existing data violates the rule.
- When adding a foreign key, ensure referenced columns have an appropriate primary or unique key.
- Use descriptive names for constraints to improve maintainability.
- SQL Server supports disabling constraints temporarily with
NOCHECK.