Interview Questions, Answers and Tutorials

Category: 10. Working with Constraints

Teaching Your Database to Say “YES” and “NO” with DEFAULT and CHECK Constraints

Imagine your database is a school If there are no rules, students can: That would be chaosSo we use constraints to keep data clean, safe, and sensible. Today, we learn two important rules: We’ll learn this using MySQL. What Is a Constraint? A constraint is a rule applied to a column to control what data can go inside it. Think of it as: Traffic rules for your database roads DEFAULT Constraint – The Helpful Friend What Is DEFAULT? The DEFAULT constraint gives a column a predefined valueOnly when you don’t provide one Example If you forget your school uniform, the…

Keeping Data Clean with UNIQUE and NOT NULL Constraints

Unique and NOT NULL Constraints Imagine you are making a school register. That’s exactly what NOT NULL and UNIQUE constraints do in a database We’ll learn this using MySQL. What Are Constraints? (Super Simple) Constraints are rules that tell the database: “Hey! Data must behave nicely!” They protect your data from mistakes. NOT NULL Constraint Example: Creating a Table with NOT NULL Allowed Not Allowed Error:Column 'name' cannot be null Adding NOT NULL to Existing Table UNIQUE Constraint Example: Creating a Table with UNIQUE Allowed Not Allowed Error:Duplicate entry 'a@gmail.com' for key 'email' Adding UNIQUE Constraint Later UNIQUE vs NOT…

Key Keepers of the Database! Solving Mysteries with Primary & Foreign Keys

What Are Keys in a Database? A key is like an ID card for data. We mainly use two keys: Primary Key (The Super ID) Imagine your school roll number: That’s exactly what a Primary Key does! Rules of a Primary Key A Primary Key:✔ Is unique (no duplicates)✔ Is not NULL✔ Identifies one and only one row Example Table: students What’s happening? Wrong Example (Duplicate Primary Key) MySQL says: “Hey! Two students can’t have the same ID!” Foreign Key (The Connector) Imagine: That classroom number is a Foreign Key. A Foreign Key connects one table to another table Example…