Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Relational databases derive their real power from the ability to link records across multiple tables safely. A Foreign Key is an integrity constraint that establishes a direct parent-child relationship between two tables, ensuring that child records cannot reference non-existent parent records (Referential Integrity).
When a parent row is deleted or updated in departments, what should happen to the corresponding child rows in employees? You define this behavior using Referential Actions:
| Action | What Happens to Child Rows when Parent is Deleted/Updated? | Typical Use Case |
|---|---|---|
RESTRICT / NO ACTION | Blocks the delete/update of the parent if any child rows reference it. (Default behavior). | Preventing accidental deletion of departments that still contain active employees. |
CASCADE | Automatically deletes or updates all child rows when the parent row is deleted or updated! | Deleting an order automatically cascades to delete all its order_items. |
SET NULL | Sets the child column's value to NULL when the parent is deleted. (Child column must be nullable). | If a manager is deleted, set manager_id = NULL on their former reports. |
SET DEFAULT | Sets the child column to its defined default value (rarely used in MySQL). | System fallbacks. |
For a foreign key constraint to be successfully created:
InnoDB storage engine (MyISAM ignores foreign keys!).UNSIGNED), and byte lengths of the foreign key and parent key must match exactly!ON DELETE CASCADE. Deleting a single customer could silently wipe out 10 years of orders, invoices, and payments if cascaded blindly!ON DELETE RESTRICT?INT UNSIGNED column pointing to a parent key defined as INT SIGNED?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Primary Key & AUTO_INCREMENT | NOT NULL and DEFAULT Constraints |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.