Constraints in DBMS
What is Constraint in DBMS?
Constraints are the rules or restrictions applied on columns of a table in a database. They ensure that data is
valid and consistent.
Types of Constraints in DBMS (with examples)
1. NOT NULL Constraint
This rule says that NULL value is not allowed in this column.
Example:
CREATE TABLE Students (
Roll_No INT NOT NULL,
Name VARCHAR(50) NOT NULL
);
Now Roll_No and Name cannot be left empty.
2. UNIQUE Constraint
It ensures all values in the column are unique.
Example:
CREATE TABLE Students (
Email VARCHAR(50) UNIQUE
);
No two students can have the same Email ID.
3. PRIMARY KEY Constraint
It uniquely identifies each record in a table.
Example:
CREATE TABLE Students (
Roll_No INT PRIMARY KEY,
Name VARCHAR(50)
);
Roll_No will now be unique and not null.
4. FOREIGN KEY Constraint
It links one table to another.
Example:
CREATE TABLE Marks (
Page 1
Constraints in DBMS
Roll_No INT,
FOREIGN KEY (Roll_No) REFERENCES Students(Roll_No)
);
Only Roll_No present in Students table can be entered here.
5. CHECK Constraint
It sets a condition for a column.
Example:
CREATE TABLE Students (
Age INT CHECK (Age >= 18)
);
Now Age must be 18 or above.
6. DEFAULT Constraint
It provides a default value if user does not enter any value.
Example:
CREATE TABLE Students (
City VARCHAR(50) DEFAULT 'Delhi'
);
If user does not specify city, 'Delhi' will be used.
Summary Table of Constraints
| Constraint | Description |
|----------------|----------------------------------------------|
| NOT NULL | Does not allow null values |
| UNIQUE | Does not allow duplicate values |
| PRIMARY KEY | Unique + Not Null |
| FOREIGN KEY | Links to primary key of another table |
| CHECK | Puts a condition on the column |
| DEFAULT | Provides a default value |
Page 2