โ SQL Constraints
Essential for data integrity & important in interviews ๐ฏ
๐ง 1. What are Constraints in SQL?
Constraints are rules applied on table columns
๐ to maintain accurate & valid data
Think like this ๐
๐ โDatabase safety rulesโ
โก 2. Why Use Constraints?
โ Prevent invalid data
โ Maintain consistency
โ Improve data integrity
โ Enforce relationships
๐ Types of Constraints
NOT NULL
โข Purpose: Prevent NULL values
UNIQUE
โข Purpose: No duplicate values
PRIMARY KEY
โข Purpose: Unique identifier
FOREIGN KEY
โข Purpose: Create relationship
CHECK
โข Purpose: Apply condition
DEFAULT
โข Purpose: Set default value
๐ฅ 3. NOT NULL Constraint
๐ Column cannot contain NULL
CREATE TABLE employees (
emp_id INT,
name VARCHAR(50) NOT NULL
);
๐ฅ 4. UNIQUE Constraint
๐ Prevent duplicate values
CREATE TABLE users (
email VARCHAR(100) UNIQUE
);
๐ฅ 5. PRIMARY KEY
๐ Unique + NOT NULL
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
name VARCHAR(50)
);
โ Every row must have unique emp_id
๐ฅ 6. FOREIGN KEY
๐ Creates relationship between tables
CREATE TABLE employees (
emp_id INT PRIMARY KEY,
dept_id INT,
FOREIGN KEY (dept_id)
REFERENCES departments(dept_id)
);
โ dept_id must exist in departments table
๐ฅ 7. CHECK Constraint
๐ Restrict values using condition
CREATE TABLE employees (
salary INT CHECK (salary > 0)
);
โ Salary cannot be negative
๐ฅ 8. DEFAULT Constraint
๐ Assign default value automatically
CREATE TABLE employees (
city VARCHAR(50) DEFAULT 'Pune'
);
๐ฏ 9. Practice Tasks
1. Create table using PRIMARY KEY
2. Add UNIQUE constraint on email
3. Create FOREIGN KEY relationship
4. Use CHECK for salary > 0
5. Add DEFAULT city value
โก Mini Challenge ๐ฅ
๐ Create students table with:
โข student_id โ PRIMARY KEY
โข email โ UNIQUE
โข age > 18 using CHECK
โข city default = 'Mumbai'
Double Tap โค๏ธ For More