· SQL · 6 min read
SQL Server Constraints: Primary Key, Foreign Key, Unique, Check, Default
Primary Key Constraint
A Primary Key Constraint is a data integrity rule that enforces a single, unique identifier for each record in a table. The values in the primary key column have to be unique, and the SQL server automatically generates a clustered index on this column to speed up data retrieval. The primary key constraint is used to uniquely identify a record in a table and is essential when working with large tables.
To create a primary key constraint, you can use the CREATE TABLE statement or the ALTER TABLE statement. For instance, to create a table with a primary key constraint:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT,
Gender VARCHAR(10)
);
Here, the StudentID column is the primary key, and we have explicitly defined the constraint using the PRIMARY KEY keyword. You can also create a primary key constraint on an existing table using the ALTER TABLE statement:
ALTER TABLE Students
ADD CONSTRAINT PK_StudentID PRIMARY KEY (StudentID);
This command creates a primary key constraint named “PK_StudentID” on the “StudentID” column of the “Students” table. Note that the primary key constraint consists of one or more columns in the table.
In summary, the primary key constraint ensures that a column or set of columns contain unique values, and by enforcing data integrity, it helps to maintain the accuracy, consistency, and reliability of a database.
Foreign Key Constraint
A foreign key constraint is a rule that ensures data consistency between two tables. It establishes a link between a primary key of one table and a foreign key of another table. This constraint is used to maintain the referential integrity of the data, which means that data cannot be entered into the foreign key column unless it corresponds to a primary key in the referenced table.
For example, let’s say there are two tables: “Orders” and “Customers”. The “Orders” table has a foreign key referencing the “CustomerID” column of the “Customers” table. The foreign key constraint ensures that every order in the “Orders” table must belong to a valid customer in the “Customers” table.
Here’s how you can create a foreign key constraint on an existing table using the ALTER TABLE statement:
ALTER TABLE Orders
ADD CONSTRAINT FK_CustomerID
FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID);
This code creates a foreign key constraint named “FK_CustomerID” on the “CustomerID” column of the “Orders” table. The constraint references the “CustomerID” column of the “Customers” table. If a user tries to insert a value into the “CustomerID” field of the “Orders” table that does not exist in the “Customers” table, the database engine will throw an error.
Foreign key constraints are essential when dealing with complex databases with multiple tables. They help maintain data integrity and consistency, which is especially important in applications involving financial transactions, healthcare, or other sensitive data.
In summary, the foreign key constraint ensures that data in the foreign key column of a table corresponds to the primary key of another table, ensuring referential integrity and preventing data inconsistencies.
Unique Constraint
A unique constraint is a database constraint that ensures that the data in a column or set of columns is unique, which means that the same value cannot appear more than once in the column or set of columns. It is similar to the primary key constraint, but it does not enforce the requirement that the column or set of columns contains a unique identifier for each row in the table.
Let’s look at an example. Suppose you have a table called “Employees” with a column named “EmployeeID”. You want to make sure that no two employees have the same identification number. You can enforce this constraint using a unique constraint:
CREATE TABLE Employees (
EmployeeID INT UNIQUE,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT,
Gender VARCHAR(10)
);
This code creates a table with a unique constraint on the “EmployeeID” column. If you try to insert a row with a duplicate employee ID, the database engine will throw an error.
Alternatively, you can add a unique constraint to an existing table using the ALTER TABLE statement:
ALTER TABLE Employees
ADD CONSTRAINT UC_EmployeeID UNIQUE (EmployeeID);
This code creates a unique constraint named “UC_EmployeeID” on the “EmployeeID” column of the “Employees” table.
Unique constraints are useful in situations where you want to make sure that the data in a column or set of columns is unique, but you don’t necessarily need that column or set of columns to serve as the primary key. They can help maintain data integrity by preventing duplicate data from being entered into the table.
In summary, the unique constraint ensures that the data in a column or set of columns is unique, helping to prevent data inconsistencies and maintaining data integrity.
Check Constraint
A check constraint is a database constraint that ensures that the data in a column meets a specified condition or set of conditions. It allows you to specify a logical expression that must evaluate to TRUE for the data to be entered or updated in the table. Check constraints can apply to a single column or multiple columns in a table.
For example, let’s say you have a table called “Products” with a column named “Price”. You want to make sure that the price of a product is always greater than zero. You can enforce this constraint using a check constraint:
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(50),
Price DECIMAL(10, 2),
CONSTRAINT CHK_Price CHECK (Price > 0)
);
This code creates a table with a check constraint on the “Price” column. The check constraint named “CHK_Price” ensures that the “Price” column contains values greater than zero. If you try to enter a value less than or equal to zero, the database engine will throw an error.
You can also add a check constraint to an existing table using the ALTER TABLE statement:
ALTER TABLE Products
ADD CONSTRAINT CHK_Price CHECK (Price > 0);
This code adds a check constraint named “CHK_Price” to the “Price” column of the “Products” table.
Check constraints can be used to enforce a wide range of conditions, such as range checks, comparison checks, and pattern matching. They help to ensure data accuracy and consistency by preventing invalid data from being entered into the table.
In summary, the check constraint allows you to specify a condition or set of conditions that must be met for the data to be entered or updated in a table, enforcing data accuracy and consistency.
Summary
SQL Server constraints play a critical role in maintaining the accuracy, consistency, and reliability of a database. In this article, we have covered five types of constraints: Primary Key, Foreign Key, Unique, Check, and Default. Developers can use these constraints to enforce rules that ensure data integrity and prevent inconsistencies. By implementing these constraints, developers can build robust databases that better meet the needs of their applications.