Constraints in SQL are rules applied to data in a database to maintain the accuracy, integrity, and reliability of data. When you define constraints on a table, you ensure that certain criteria are met for data values, which helps prevent invalid data entry and enforces business rules.
Constraints are rules applied to columns in tables to ensure the correctness of data. When you define constraints, you set standards for data integrity that the database system enforces every time data is entered, updated, or deleted. Constraints help ensure that data conforms to certain rules, such as:
Defining constraints correctly can make your database more efficient and reduce the risk of data errors.
There are several types of constraints in SQL. Each constraint serves a specific purpose, and together they help maintain data integrity.
The Primary Key constraint uniquely identifies each record in a table. A primary key must contain unique values and cannot contain NULL
values.
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
Explanation: In the Employees
table, EmployeeID
is set as the primary key, meaning each EmployeeID
must be unique.
If you try to insert a duplicate value in EmployeeID
, you will get an error
INSERT INTO Employees (EmployeeID, FirstName, LastName) VALUES (1, 'John', 'Doe');
INSERT INTO Employees (EmployeeID, FirstName, LastName) VALUES (1, 'Jane', 'Doe');
-- Error: Duplicate entry '1' for key 'PRIMARY'
The Foreign Key constraint is used to maintain referential integrity between two tables. A foreign key in one table points to a primary key in another table, linking the two tables.
CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50)
);
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);
Explanation: Here, DepartmentID
in the Employees
table is a foreign key that references the DepartmentID
in the Departments
table, establishing a link between the tables.
If you try to insert a DepartmentID
in the Employees
table that does not exist in Departments
, you will get an error:
INSERT INTO Employees (EmployeeID, FirstName, LastName, DepartmentID) VALUES (1, 'John', 'Doe', 999);
-- Error: Cannot add or update a child row: a foreign key constraint fails
The Unique constraint ensures that all values in a column are different. Unlike the primary key, a unique constraint allows a single NULL
value.
CREATE TABLE Products (
ProductID INT PRIMARY KEY,
ProductCode VARCHAR(10) UNIQUE,
ProductName VARCHAR(50)
);
Explanation: In the Products
table, ProductCode
is unique, ensuring no two products can have the same code.
If you try to insert a duplicate ProductCode
, you’ll get an error:
INSERT INTO Products (ProductID, ProductCode, ProductName) VALUES (1, 'P001', 'Widget');
INSERT INTO Products (ProductID, ProductCode, ProductName) VALUES (2, 'P001', 'Gadget');
-- Error: Duplicate entry 'P001' for key 'ProductCode'
The Not Null constraint ensures that a column cannot have a NULL
value. It is commonly used for columns where a value is always required.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT NOT NULL,
OrderDate DATE NOT NULL
);
Explanation: In the Orders
table, both CustomerID
and OrderDate
are marked as NOT NULL
, meaning they must have a value for every record.
If you try to insert a record without providing a CustomerID
or OrderDate
, you’ll get an error:
INSERT INTO Orders (OrderID, CustomerID) VALUES (1, 123);
-- Error: Column 'OrderDate' cannot be null
The Check constraint ensures that all values in a column satisfy a specific condition.
CREATE TABLE Accounts (
AccountID INT PRIMARY KEY,
Balance DECIMAL(10, 2) CHECK (Balance >= 0)
);
Explanation: In the Accounts
table, the Balance
column must always be zero or positive, ensuring that negative balances aren’t allowed.
If you try to insert a negative balance, you’ll get an error:
INSERT INTO Accounts (AccountID, Balance) VALUES (1, -100);
-- Error: Check constraint 'Accounts_chk_1' is violated
The Default constraint sets a default value for a column when no value is provided.
CREATE TABLE Users (
UserID INT PRIMARY KEY,
Username VARCHAR(50),
CreatedDate DATE DEFAULT CURRENT_DATE
);
Explanation: In the Users
table, CreatedDate
defaults to the current date if no value is specified during insertion.
When you insert a new user without a CreatedDate
, it will automatically be set to today’s date:
INSERT INTO Users (UserID, Username) VALUES (1, 'Alice');
SELECT * FROM Users;
-- Output:
-- | UserID | Username | CreatedDate |
-- |--------|----------|-------------|
-- | 1 | Alice | 2024-11-12 |
Constraints can be defined when creating a table or added to an existing table. Here’s how:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT NOT NULL,
ProductID INT UNIQUE,
OrderDate DATE DEFAULT CURRENT_DATE,
Quantity INT CHECK (Quantity > 0)
);
ALTER TABLE Orders
ADD CONSTRAINT chk_Quantity CHECK (Quantity > 0);
To modify or remove constraints, use ALTER TABLE
statements.
ALTER TABLE Orders
DROP CONSTRAINT chk_Quantity;
SQL doesn’t allow direct modification of constraints, so you’ll need to drop the constraint and add a new one.
Composite Primary Key: A primary key that consists of multiple columns.
CREATE TABLE Enrollment (
StudentID INT,
CourseID INT,
PRIMARY KEY (StudentID, CourseID)
);
ON DELETE CASCADE: Automatically deletes records in the child table when the parent record is deleted.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ON DELETE CASCADE
);
chk_Age
, fk_CustomerID
, etc.Constraints are vital in maintaining data integrity and enforcing rules within your SQL database. By understanding and applying constraints such as primary keys, foreign keys, unique constraints, not null, check, and default constraints, you can prevent data inconsistencies, enforce business logic, and secure the quality of your data. Proper constraint usage simplifies database management, making your applications more robust and reliable. Happy Coding!❤️