Lesson 09 � Intermediate

CONSTRAINTS:
DATA RULES.

Constraints se data ki quality maintain hoti hai � duplicate entries nahi, null values nahi, valid ranges hi. Database integrity ke liye zaroori hai. Bina constraints ke database mein garbage data bhar jayega.

? 20 min✓ Intermediate✓ Prerequisite: Data Types

WHY: Constraints kyun zaroori hain?

Socho ek school ka database hai � agar kisi student ka ID same ho jaye do students ka toh confusion ho jayega. Agar email field khali chhod di toh contact kaise karoge✓ Agar age negative daal di toh✓ Yeh sab problems constraints solve karte hain. They are the rules jo ensure karte hain ki data clean aur consistent rahe.

PRIMARY KEY

Har table ka unique identifier. Koi do rows ka same PRIMARY KEY nahi ho sakta. Auto-increment hota hai mostly � 1, 2, 3... automatically badhta jata hai.

FOREIGN KEY

Do tables ke beech ka relationship. Ek table ka column doosre table ke PRIMARY KEY ko refer karta hai. Students ka course_id courses table ke id ko point karta hai.

NOT NULL

Value mandatory hai � khali nahi chhod sakte. Name, email, phone � yeh sab NOT NULL hone chahiye kyunki bina inke record incomplete hai.

UNIQUE

Duplicate value nahi chalegi. Email, username, phone number � har ek unique hona chahiye. Do users ka same email nahi ho sakta.

HOW: Constraints ka syntax samjho

Constraints CREATE TABLE ke andar define hote hain. Column ke saath likhte hain ya table level par. Formula simple hai � column_name TYPE CONSTRAINT.

sql
-- PRIMARY KEY
CREATE TABLE students (
 id INT PRIMARY KEY,
 name VARCHAR(100) NOT NULL,
 email VARCHAR(100) UNIQUE,
 age INT CHECK (age >= 16)
);

-- FOREIGN KEY
CREATE TABLE enrollments (
 id INT PRIMARY KEY,
 student_id INT,
 course_id INT,
 FOREIGN KEY (student_id) REFERENCES students(id),
 FOREIGN KEY (course_id) REFERENCES courses(id)
);

-- DEFAULT value
CREATE TABLE products (
 id INT PRIMARY KEY,
 name VARCHAR(100) NOT NULL,
 price DECIMAL(10,2) DEFAULT 0.00,
 in_stock BOOLEAN DEFAULT TRUE
);

-- Composite primary key
CREATE TABLE order_items (
 order_id INT,
 product_id INT,
 quantity INT DEFAULT 1,
 PRIMARY KEY (order_id, product_id)
);
Mental model: Constraints ek rulebook hai tumhare database ka. PRIMARY KEY = roll number (unique ID), FOREIGN KEY = reference letter (relation), NOT NULL = attendance mandatory, UNIQUE = no duplicate IDs, CHECK = eligibility criteria.

Constraints detailed mein

PRIMARY KEY

Har table mein ek hi PRIMARY KEY hota hai. Auto-increment use karo toh SQL khud number badhata jayega. NULL nahi ho sakta aur duplicate bhi nahi.

FOREIGN KEY

Parent table ka PRIMARY KEY child table mein reference karta hai. Agar parent delete ho jaye toh cascade options hain � SET NULL, CASCADE, RESTRICT. Referential integrity maintain hoti hai.

NOT NULL + UNIQUE

NOT NULL se value mandatory hai. UNIQUE se duplicate nahi. Dono saath mein lagao toh � har row ka value hona chahiye aur unique bhi. Email ke liye perfect combination.

CHECK + DEFAULT

CHECK se range define karo � age >= 18, price > 0. DEFAULT se value set karo jab column khali ho � status DEFAULT 'active', quantity DEFAULT 1.

Composite Primary Key

Kabhi kabhi ek column unique nahi hota � do ya zyada columns mil ke unique identifier banate hain. Jaise order_items mein same order mein same product ek baar hi aa sakta hai:

sql
-- Composite key: order + product combination unique
CREATE TABLE order_items (
 order_id INT,
 product_id INT,
 quantity INT DEFAULT 1,
 PRIMARY KEY (order_id, product_id)
);

-- Ab same order mein same product duplicate nahi hoga
INSERT INTO order_items VALUES (1, 101, 2);
INSERT INTO order_items VALUES (1, 101, 3); -- ERROR! Duplicate
INSERT INTO order_items VALUES (1, 102, 1); -- OK, different product

FOREIGN KEY relationships

Tables ke beech relationship banana FOREIGN KEY se hota hai. Students ko courses se link karo, orders ko customers se � yeh relational database ki power hai:

sql
-- Parent table
CREATE TABLE courses (
 id INT PRIMARY KEY,
 course_name VARCHAR(100) NOT NULL,
 duration VARCHAR(50)
);

-- Child table with FOREIGN KEY
CREATE TABLE enrollments (
 id INT PRIMARY KEY,
 student_id INT,
 course_id INT,
 enrolled_date DATE DEFAULT CURRENT_DATE,
 FOREIGN KEY (student_id) REFERENCES students(id),
 FOREIGN KEY (course_id) REFERENCES courses(id)
);

-- Ab galat course_id daalenge toh error aayega
INSERT INTO enrollments VALUES (1, 1, 999); -- ERROR! course 999 exists nahi
Pro tip: FOREIGN KEY lagane se pehle ensure karo ki parent table mein referenced column PRIMARY KEY ya UNIQUE hai. Warna error aayega. Also, ON DELETE CASCADE lagao toh parent row delete hone par child rows bhi delete ho jayengi.

Try it: Table banao

Neeche ka editor SQL jaisa hai. Yahan apni table likho aur "Run Query" dabao. Screen par results dikhenge � yeh browser-based simulation hai, real database nahi.

SQL playgroundApni table constraints ke saath banao
Run Query dabayein

Quick check

Ek users table banao jismein PRIMARY KEY, NOT NULL, aur UNIQUE constraints ho.

CREATE TABLE users se shuru karo, id INT PRIMARY KEY likho, name VARCHAR(100) NOT NULL aur email VARCHAR(100) UNIQUE add karo.

Common constraint mistakes

Constraints complete?

Ab Aggregate functions par chalo � COUNT, SUM, AVG seekho jo data ko summarize karte hain.