Constraints in SQL are rules applied to table columns to maintain data accuracy, integrity, and consistency in the database. They ensure that only valid data gets inserted or updated, which helps prevent logical and data-entry errors at the database level โ rather than relying only on application logic.
Some of the most common constraints include:
- PRIMARY KEY โ Ensures each record is unique and not null.
Example:
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Department VARCHAR(30)
);
Here, EmpID uniquely identifies each employee.
FOREIGN KEY โ Maintains referential integrity between two tables.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
EmpID INT,
FOREIGN KEY (EmpID) REFERENCES Employees(EmpID)
);
This ensures an order canโt exist for an employee who isnโt present in the Employees table.
UNIQUE โ Ensures all values in a column are distinct.
For instance, Iโve used a UNIQUE constraint on Email in a Customers table to avoid duplicate registrations.
CHECK โ Restricts the values allowed in a column.
CHECK (Salary > 0)
Iโve used this to validate that numeric fields like salary or quantity are positive.
DEFAULT โ Assigns a default value when no value is provided.
DEFAULT 'Active'
- This ensures consistency when users omit optional fields.
- NOT NULL โ Ensures a column cannot store null values.
I apply this for essential fields likeNameorDateOfBirth.
In practice, I used constraints heavily in a payroll system to prevent invalid data entry โ for example, ensuring that every salary record was linked to a valid employee (FOREIGN KEY) and that deductions never exceeded the gross salary (CHECK constraint).
A challenge Iโve faced was when inserting data into multiple related tables โ foreign key constraints would fail if the parent record wasnโt inserted first. To handle this, I ensured proper insertion order and sometimes temporarily disabled constraints during bulk imports (with caution).
One limitation is that overly restrictive constraints can block valid data scenarios if not well-planned, so designing them requires a balance between data protection and flexibility.
In short, constraints act as database-level guards, ensuring data reliability โ by enforcing uniqueness, valid relationships, and correct values โ before the data ever reaches your application logic.
