Foreign key constraints

From CarlosCaPe/octorato · View interactive version

Foreign key constraints is an AI agent skill from the GitHub repository CarlosCaPe/octorato. Foreign Key Constraints

How to use this skill

Skill file

Foreign Key Constraints

What

ALTER TABLE ADD CONSTRAINT ... FOREIGN KEY enforces referential integrity

between tables. The FK guarantees that every value in the child column exists

in the parent table's referenced column.

Why

Without FKs, orphaned records accumulate silently. A HospitalId in an

appointments table might reference a hospital that no longer exists. FKs

catch this at INSERT/UPDATE time, preventing data corruption.

How

Standard FK pattern (NOT VALID + VALIDATE)

-- Step 1: Add the constraint without scanning existing rows (instant)
ALTER TABLE public."AppointmentInfo"
    ADD CONSTRAINT fk_appointmentinfo_hospitalid
    FOREIGN KEY ("HospitalId")
    REFERENCES public."Hospital"("HospitalId")
    NOT VALID;

-- Step 2: Validate existing rows (non-blocking, allows concurrent reads)
ALTER TABLE public."AppointmentInfo"
    VALIDATE CONSTRAINT fk_appointmentinfo_hospitalid;

Why NOT VALID + VALIDATE?

child table AND the referenced (parent) table -- lighter than the

ACCESS EXCLUSIVE used by most ALTER TABLE forms

(PG 16 docs: sql-altertable.html)

(SHARE UPDATE EXCLUSIVE) that allows concurrent reads AND writes;

it also acquires only ROW SHARE on the referenced table

(PG 16 docs: sql-altertable.html)

Best Practices

FK with explicit actions

ALTER TABLE public."ChildTable"
    ADD CONSTRAINT fk_child_parent
    FOREIGN KEY ("ParentId")
    REFERENCES public."ParentTable"("Id")
    ON DELETE CASCADE
    ON UPDATE CASCADE
    NOT VALID;

ALTER TABLE public."ChildTable"
    VALIDATE CONSTRAINT fk_child_parent;

Idempotent pattern

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.table_constraints
        WHERE constraint_name = 'fk_appointmentinfo_hospitalid'
          AND table_schema = 'public'
    ) THEN
        ALTER TABLE public."AppointmentInfo"
            ADD CONSTRAINT fk_appointmentinfo_hospitalid
            FOREIGN KEY ("HospitalId")
            REFERENCES public."Hospital"("HospitalId");
        RAISE NOTICE 'Created FK: fk_appointmentinfo_hospitalid';
    ELSE
        RAISE NOTICE 'Skipped: fk_appointmentinfo_hospitalid (already exists)';
    END IF;
END $$;

Pre-Requisites

Before adding a FK, verify:

  1. No orphans exist -- see Skill #24 (Orphan Detection & FK Rollout)

for the full scan + remediation workflow

  1. Parent column has a unique index (usually PK or UNIQUE constraint)
  2. Data types match between child and parent columns

When to Use

Where We Used It

Related Skills

before FK creation

References

-- see "Foreign keys and constraints" in Design & Modeling

Gotchas

SHARE ROW EXCLUSIVE -- coordinate with teams owning the parent table

checks the parent)

PostgreSQL does NOT auto-create indexes on FK columns

(PG 16 limitation -- see Skill #34)


Category: DDL | Origin: ,

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.