MySQL + SQL · Lesson 20

Referential Integrity in DBMS

What is Referential Integrity?

Referential integrity ensures a foreign key value always matches an existing primary key in the related table (or is NULL). It stops "orphan" rows.

Example

CREATE TABLE fees (
  fee_id INT PRIMARY KEY,
  roll_no INT,
  FOREIGN KEY (roll_no) REFERENCES students(roll_no)
    ON DELETE CASCADE
);
You cannot add a fee for a roll_no that does not exist in students. ON DELETE CASCADE auto-removes fees if the student is deleted.

ON DELETE / ON UPDATE

  • CASCADE — change/delete children too.
  • SET NULL — set the foreign key to NULL.
  • RESTRICT — block the action if children exist.

Summary

  • Referential integrity keeps foreign keys pointing to valid rows.
  • ON DELETE CASCADE/SET NULL/RESTRICT control what happens to children.
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n

💻 Live Code Editor

Is page ki language (MYSQL) mein code likhein aur turant chalाएं — yahीं, bina kuch install kiye.
Powered by OneCompiler. Agar editor na khule to yahान naye tab mein kholein.

💻 Live Code Editor

Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें. Agar load na ho to naye tab mein kholें.