The constraints you listed are Integrity Constraints in DBMS/RDBMS. They help maintain the accuracy and consistency of data.
1. NOT NULL Constraint
Ensures that a column cannot have a NULL (empty) value.
Example:
CREATE TABLE Student (
StudentID INT,
Name VARCHAR(50) NOT NULL
);
Here, the Name column must contain a value.
2. UNIQUE Constraint
Ensures that all values in a column are unique.
Example:
CREATE TABLE Student (
StudentID INT,
Email VARCHAR(100) UNIQUE
);
No two students can have the same email address.
3. PRIMARY KEY Constraint
Uniquely identifies each record in a table.
Properties:
- Must be unique
- Cannot be NULL
- Only one primary key per table
Example:
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
Name VARCHAR(50)
);
StudentID uniquely identifies each student.
4. FOREIGN KEY Constraint
Establishes a relationship between two tables.
Example:
Student Table
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
Name VARCHAR(50)
);
Course Table
CREATE TABLE Course (
CourseID INT PRIMARY KEY,
StudentID INT,
FOREIGN KEY (StudentID)
REFERENCES Student(StudentID)
);
Here, StudentID in the Course table refers to StudentID in the Student table.
Summary Table
| Constraint | Purpose |
|---|---|
| NOT NULL | Prevents NULL values in a column |
| UNIQUE | Ensures all values are different |
| PRIMARY KEY | Uniquely identifies each row |
| FOREIGN KEY | Maintains relationship between tables |
Example Combined
CREATE TABLE Student (
StudentID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE
);
CREATE TABLE Result (
ResultID INT PRIMARY KEY,
StudentID INT,
Marks INT,
FOREIGN KEY (StudentID)
REFERENCES Student(StudentID)
);
In this example:
StudentID→ PRIMARY KEYName→ NOT NULLEmail→ UNIQUEStudentIDinResult→ FOREIGN KEY