SQL Constraints

What are Constraints?

Constraints enforce rules at the table level to guarantee data integrity and consistency. They are defined when creating or altering a table and can be:

Common Constraint Syntax

CREATE TABLE dbo.Employee (
    EmployeeID INT PRIMARY KEY,
    DepartmentID INT,
    Salary MONEY CHECK (Salary >= 0),
    Email NVARCHAR(255) UNIQUE,
    CONSTRAINT FK_Employee_Department
        FOREIGN KEY (DepartmentID) REFERENCES dbo.Department(DepartmentID)
);

Constraint Types

ConstraintPurposeTypical Syntax
PRIMARY KEY Unique identifier for each row; cannot be NULL PRIMARY KEY (column1 [, column2])
FOREIGN KEY Ensures a value exists in the referenced table FOREIGN KEY (col) REFERENCES OtherTable(OtherCol)
UNIQUE All values must be distinct UNIQUE (col1 [, col2])
CHECK Validates column value against an expression CHECK (col > 0)
DEFAULT Provides a fallback value DEFAULT (value)

Related Topics