MSDN Documentation

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 };
ParameterDescription
table_nameName of the table to modify.
constraint_nameIdentifier for the new constraint.
column_listComma‑separated list of columns the constraint applies to.
ref_tableReferenced table for a foreign key.
ref_column_listColumns in the referenced table.
expressionBoolean expression for a CHECK constraint.
default_valueLiteral 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;