{
    "slug": "db_foreign_keys",
    "term": "Foreign Keys & Referential Integrity",
    "category": "database",
    "difficulty": "intermediate",
    "short": "A foreign key is a column that references the primary key of another table, enforcing referential integrity — no orphaned rows pointing to non-existent parents.",
    "long": "Foreign keys enforce that every child row has a corresponding parent row. ON DELETE CASCADE removes children when the parent is deleted. ON DELETE RESTRICT (default in PostgreSQL) blocks deletion if children exist. ON DELETE SET NULL nullifies the FK column. Foreign keys also create implicit indexes in MySQL but not PostgreSQL — you must add them explicitly. Many applications disable FK constraints for performance and rely on application-level validation, which always drifts.",
    "aliases": [
        "FK",
        "referential integrity",
        "ON DELETE CASCADE"
    ],
    "tags": [
        "database",
        "sql",
        "integrity",
        "design"
    ],
    "misconception": "ORMs handle referential integrity so FK constraints are redundant — application code has bugs; the database constraint is the last reliable safety net.",
    "why_it_matters": "Without FK constraints, a deleted user leaves orphaned orders, comments, and settings that accumulate silently — queries return null joins and application code crashes unpredictably.",
    "common_mistakes": [
        "Not adding an index on the FK column in PostgreSQL — joins and cascade operations do full table scans without it.",
        "Using ON DELETE CASCADE everywhere without considering whether child records should survive parent deletion.",
        "Disabling FK checks during bulk imports and forgetting to re-enable them — orphaned rows persist permanently.",
        "Not specifying ON DELETE behaviour — defaults differ between MySQL (RESTRICT) and other databases."
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "db_normalisation_forms",
        "db_schema_design",
        "db_transactions",
        "database_indexing"
    ],
    "prerequisites": [
        "data_normalisation",
        "acid_properties",
        "db_schema_design"
    ],
    "refs": [
        "https://www.postgresql.org/docs/current/ddl-constraints.html#DDL-CONSTRAINTS-FK"
    ],
    "bad_code": "-- No FK constraint — orphaned rows accumulate silently:\nCREATE TABLE orders (\n    id INT PRIMARY KEY,\n    user_id INT  -- No FK: user deleted, orders remain with dangling user_id\n);\n-- DELETE FROM users WHERE id = 42;\n-- orders still has rows with user_id = 42 — silent data corruption",
    "good_code": "-- FK with explicit delete behaviour:\nCREATE TABLE orders (\n    id INT PRIMARY KEY,\n    user_id INT NOT NULL\n        REFERENCES users(id)\n        ON DELETE RESTRICT   -- Block user deletion if orders exist\n);\n-- PostgreSQL: also add index\nCREATE INDEX idx_orders_user_id ON orders(user_id);",
    "quick_fix": "Always define foreign key constraints — they prevent orphaned records at the database level regardless of what application code does; add indexes on FK columns for JOIN performance",
    "severity": "high",
    "effort": "low",
    "created": "2026-03-15",
    "updated": "2026-03-22",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/db_foreign_keys",
        "html_url": "https://codeclaritylab.com/glossary/db_foreign_keys",
        "json_url": "https://codeclaritylab.com/glossary/db_foreign_keys.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[Foreign Keys & Referential Integrity](https://codeclaritylab.com/glossary/db_foreign_keys) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/db_foreign_keys"
            }
        }
    }
}