Skip to content

Instantly share code, notes, and snippets.

@bartdorsey
Created July 16, 2025 16:19
Show Gist options
  • Select an option

  • Save bartdorsey/be6262d420ef0a3938bbc838410dc1f4 to your computer and use it in GitHub Desktop.

Select an option

Save bartdorsey/be6262d420ef0a3938bbc838410dc1f4 to your computer and use it in GitHub Desktop.
Foreign Keys Quick Reference.md

PostgreSQL Foreign Keys - Quick Reference

1. Basic Foreign Key (Most Common)

CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INTEGER REFERENCES customers(id)
);

2. Add to Existing Table

ALTER TABLE orders 
ADD CONSTRAINT fk_customer 
FOREIGN KEY (customer_id) REFERENCES customers(id);

3. Named Constraint (Recommended)

CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INTEGER,
    CONSTRAINT fk_customer FOREIGN KEY (customer_id) REFERENCES customers(id)
);

4. With Actions

CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INTEGER REFERENCES customers(id) ON DELETE CASCADE
);

Common Actions

  • ON DELETE CASCADE - Delete child when parent deleted
  • ON DELETE SET NULL - Set FK to NULL when parent deleted
  • ON DELETE RESTRICT - Prevent parent deletion (default)

Drop Constraint

ALTER TABLE orders DROP CONSTRAINT fk_customer;

View Constraints

\d table_name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment