MySQL FOREIGN KEY Constraint

The FOREIGN KEY constraint links two tables and ensures referential integrity. It prevents actions that would destroy links between tables.

Example with Tamil Kings

CREATE TABLE tamil_kingdoms (
    kingdom_id INT AUTO_INCREMENT PRIMARY KEY,
    kingdom_name VARCHAR(100) NOT NULL
);

CREATE TABLE tamil_kings_foreign_key (
    id INT AUTO_INCREMENT PRIMARY KEY,
    king_name VARCHAR(100),
    kingdom_id INT,
    FOREIGN KEY (kingdom_id) REFERENCES tamil_kingdoms(kingdom_id)
);

Code Explanation: The kingdom_id column in the tamil_kings_foreign_key table is a foreign key that references the kingdom_id column in the tamil_kingdoms table.

Best Practices

  • Ensure that foreign keys are used to maintain referential integrity between related tables.
  • Use ON DELETE and ON UPDATE actions to specify what should happen to related rows.

Key Takeaways

  • Foreign keys link tables and ensure that relationships between them remain consistent.
  • They are crucial for maintaining data integrity in relational databases.