SQL Constraints

SQL Constraints are rules applied to table columns to control what data can be stored in the database.
They help maintain data accuracy, integrity, and reliability.

In simple words:
Constraints restrict the type of data that can be inserted into a table.

Why Constraints Are Important
Constraints ensure:
   • Data is valid
   • No duplicate values
   • Required fields are not empty
   • Tables maintain proper relationships

Example:
A student table should not allow two students with the same Student_ID.

Types of SQL Constraints
The most common SQL constraints are:
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT

Simple Example (All Constraints Together)

CREATE TABLE Employees (
    Employee_ID INT PRIMARY KEY,
    Name VARCHAR(50) NOT NULL,
    Email VARCHAR(100) UNIQUE,
    Age INT CHECK (Age >= 18),
    Country VARCHAR(50) DEFAULT 'India'
);	

Summary Table

Constraint    |	    Purpose
--------------|----------------------
NOT NULL --------- Prevents empty values
UNIQUE ----------- Ensures all values are different
PRIMARY KEY ------ Unique identifier for table
FOREIGN KEY------- Connects two tables
CHECK	---------  Validates condition
DEFAULT	 ---------- Assigns default value	

This table enforces:
   • Unique employee IDs
   • Name cannot be empty
   • Email must be unique
   • Age must be ≥ 18
   • Default country is India


Most important constraints for interviews:
1. PRIMARY KEY
2. FOREIGN KEY
3. UNIQUE
4. NOT NULL


Topics