Postgres Create Table With Foreign Key

9 min read

Creating a dependable relational database schema relies heavily on the ability to enforce relationships between tables. Practically speaking, in PostgreSQL, the mechanism that binds these relationships together is the foreign key constraint. Understanding how to properly define, implement, and manage these constraints is fundamental for maintaining data integrity and ensuring that your application logic remains consistent with the underlying data structure.

A foreign key in PostgreSQL is a column (or a group of columns) in one table that uniquely identifies a row in another table. The table containing the foreign key is often called the child table, while the table containing the candidate key (usually the primary key) is the parent table or referenced table. This constraint prevents actions that would destroy links between tables, such as inserting a record in the child table with a reference that doesn't exist in the parent, or deleting a record in the parent table that is still referenced by the child.

Basic Syntax for Creating a Table with a Foreign Key

The most common way to establish a foreign key is during the initial table creation using the CREATE TABLE statement. You can define the constraint inline (column level) or as a separate table constraint (table level).

Inline Column Constraint Definition

This method is concise and works well when the foreign key consists of a single column. You simply append the REFERENCES clause to the column definition.

CREATE TABLE orders (
    order_id SERIAL PRIMARY KEY,
    order_date DATE NOT NULL DEFAULT CURRENT_DATE,
    customer_id INTEGER NOT NULL REFERENCES customers(customer_id),
    total_amount NUMERIC(10, 2) CHECK (total_amount > 0)
);

In this example, the customer_id column in the orders table is constrained to only accept values that exist in the customer_id column of the customers table. If the customers table does not exist yet, or if the referenced column is not a primary key or unique constraint, PostgreSQL will throw an error And it works..

The official docs gloss over this. That's a mistake.

Table-Level Constraint Definition

For composite foreign keys (spanning multiple columns) or for better readability and naming control, the table-level syntax is preferred. This allows you to explicitly name the constraint using the CONSTRAINT keyword.

CREATE TABLE order_items (
    order_id INTEGER NOT NULL,
    product_id INTEGER NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    unit_price NUMERIC(10, 2) NOT NULL,
    PRIMARY KEY (order_id, product_id),
    CONSTRAINT fk_order_items_order
        FOREIGN KEY (order_id)
        REFERENCES orders (order_id)
        ON DELETE CASCADE,
    CONSTRAINT fk_order_items_product
        FOREIGN KEY (product_id)
        REFERENCES products (product_id)
        ON DELETE RESTRICT
);

Here, the CONSTRAINT fk_order_items_order names the foreign key explicitly. Now, naming constraints is a best practice because it makes error messages significantly more readable (e. That said, g. , "duplicate key value violates unique constraint fk_order_items_order" vs a system-generated name like $1) and simplifies future maintenance tasks like dropping or disabling the constraint.

Deep Dive: Referential Actions (ON DELETE / ON UPDATE)

One of the most powerful features of PostgreSQL foreign keys is the ability to define referential actions. These dictate what happens to the child rows when the referenced parent row is modified or deleted. If omitted, the default behavior is NO ACTION (which effectively means RESTRICT in PostgreSQL, checking the constraint immediately).

1. ON DELETE CASCADE

This is the most aggressive option. When a row in the parent table is deleted, PostgreSQL automatically deletes all matching rows in the child table.

  • Use case: order_items linked to orders. If an order is cancelled and deleted, the line items lose their purpose and should be removed automatically.
  • Warning: Use with extreme caution. A single DELETE on a high-level parent can trigger a massive cascade of deletions down a hierarchy of tables, potentially locking large portions of the database and causing performance spikes.

2. ON DELETE RESTRICT (Default)

Prevents the deletion of the parent row if any referencing rows exist in the child table. The transaction will abort with an error. This is the safest default for critical lookup data (e.g., products, users, categories).

3. ON DELETE SET NULL

Sets the foreign key column(s) in the child table to NULL when the parent row is deleted.

  • Requirement: The foreign key column(s) must not have a NOT NULL constraint.
  • Use case: An employees table referencing a departments table. If a department is dissolved, employees remain but become unassigned (department_id becomes NULL).

4. ON DELETE SET DEFAULT

Sets the foreign key column(s) to their defined default value upon parent deletion Most people skip this — try not to..

  • Requirement: A default value must be defined for the column, and that default value must exist in the parent table (or be NULL).

5. ON DELETE NO ACTION

Similar to RESTRICT, but the check timing differs slightly in standard SQL (deferred vs immediate). In PostgreSQL, NO ACTION and RESTRICT are functionally identical for immediate constraints, but NO ACTION allows the check to be deferred until the end of the transaction if the constraint is defined as DEFERRABLE.

The same actions apply to ON UPDATE, triggering when the primary key value of the parent row changes. Updating primary keys is generally discouraged in relational design, but if necessary, ON UPDATE CASCADE propagates the new key value to child tables automatically.

Adding Foreign Keys to Existing Tables (ALTER TABLE)

Schema evolution is a constant in software development. You will frequently need to add foreign keys to tables that already contain data.

ALTER TABLE shipments
ADD CONSTRAINT fk_shipments_order
FOREIGN KEY (order_id)
REFERENCES orders (order_id)
ON DELETE SET NULL;

Critical Performance Note: When you run this command on a large table, PostgreSQL acquires an ACCESS EXCLUSIVE lock on both the child table (shipments) and the parent table (orders). It then performs a full sequential scan of the child table to validate every existing row against the parent table.

On tables with millions of rows, this validation phase can take minutes or hours, blocking all reads and writes to both tables. For production systems, the standard strategy to avoid downtime is:

  1. Create the constraint as NOT VALID:
    ALTER TABLE shipments
    ADD CONSTRAINT fk_shipments_order
    FOREIGN KEY (order_id)
    REFERENCES orders (order_id)
    NOT VALID;
    
    This skips the validation scan and acquires only a brief lock.
  2. Validate the constraint in a separate transaction (which still locks but allows you to control timing):
    ALTER TABLE shipments VALIDATE CONSTRAINT fk_shipments_order;
    
  3. Once validated, the constraint behaves exactly like a standard foreign key for all new inserts/updates.

Composite Foreign Keys

Sometimes a relationship is defined by a combination of columns rather than a single surrogate key (like id or uuid). This is common in multi-tenant applications or when using natural keys.

CREATE TABLE inventory (
    warehouse_id UUID NOT NULL,
    product_sku VARCHAR(50) NOT NULL,
    quantity_on_hand INTEGER NOT NULL DEFAULT 0,
    PRIMARY KEY (warehouse_id, product_sku),
    CONSTRAINT fk_inventory_warehouse
        FOREIGN KEY (warehouse_id)
        REFERENCES warehouses (id),
    CONSTRAINT fk_inventory_product

### Completing the Composite Foreign Key Definition  

To enforce a relationship that depends on more than one attribute, the foreign key must reference a matching set of columns in the parent table. The syntax is simply a comma‑separated list on both sides of the `FOREIGN KEY` clause:

```sql
CREATE TABLE inventory (
    warehouse_id   UUID NOT NULL,
    product_sku    VARCHAR(50) NOT NULL,
    quantity_on_hand INTEGER NOT NULL DEFAULT 0,
    PRIMARY KEY (warehouse_id, product_sku),

    CONSTRAINT fk_inventory_warehouse
        FOREIGN KEY (warehouse_id)
        REFERENCES warehouses (id),

    CONSTRAINT fk_inventory_product
        FOREIGN KEY (warehouse_id, product_sku)
        REFERENCES products (warehouse_id, product_sku)
);

In this example, a row in inventory is only allowed when the combination of warehouse_id and product_sku exists in the products table. The parent table therefore needs a unique (or primary‑key) constraint covering the same two columns, otherwise the foreign key would have nothing to match against.

Why Use Composite Keys?

  • Natural relationships – In multi‑tenant systems, a product may belong to a specific warehouse, and the same SKU can appear in different warehouses without conflict. A composite key captures that granularity.
  • Avoid surrogate keys – When a natural identifier already guarantees uniqueness, adding a synthetic id column can introduce unnecessary duplication.
  • Data integrity at the grain level – The database guarantees that a row cannot be referenced unless the exact tuple exists, preventing orphaned entries that a single‑column FK could not enforce.

Indexing Considerations

PostgreSQL automatically creates an index for a foreign key constraint only if the referenced columns are part of a primary key or a unique constraint. In the composite example above, the products table must have a unique (or primary‑key) constraint on (warehouse_id, product_sku). If that uniqueness is enforced by a separate index, the foreign key lookup will benefit from it, and the child table’s own index on (warehouse_id, product_sku) will speed up inserts, updates, and deletes that involve the composite key.

It sounds simple, but the gap is usually here.

If the parent table lacks a suitable unique constraint, PostgreSQL will still allow the foreign key to be created, but it will perform a sequential scan to check each row, which can become a serious performance bottleneck for large tables. Because of this, always confirm that the parent side of a composite foreign key is backed by a unique index that matches the column order exactly.

Referential Actions on Composite Keys

The same ON DELETE, ON UPDATE, and ON INSERT clauses that apply to single‑column foreign keys are available for composite keys:

  • ON DELETE CASCADE – When a row in products is removed, all corresponding rows in inventory disappear automatically.
  • ON UPDATE RESTRICT (the default) – An update to either the warehouse_id or product_sku in the parent is rejected if it would break the match with existing child rows.
  • ON UPDATE CASCADE – The parent’s composite key can be updated, and the change propagates to the child table, provided the new combination already exists in inventory (or you allow the update to succeed by first inserting a matching row).

Because the foreign key spans multiple columns, the database must compare all components simultaneously. Basically, the order of columns in the index matters: the index on the parent must start with the same column order as the foreign key definition, otherwise the lookup cannot be satisfied efficiently Still holds up..

Common Pitfalls

  1. Mismatched column order – Reversing the order of columns in the parent’s unique constraint will cause the foreign key to be created, but lookups will fall back to a sequential scan, dramatically slowing DML.
  2. Missing uniqueness – If the parent table does not enforce uniqueness on the composite set, the foreign key will reference a non‑deterministic set of rows, leading to ambiguous references and potential data anomalies.
  3. Over‑constraining inserts – Inserting a child row that references a parent row with a NULL value in any of the composite columns will fail, even if the other columns match, because NULL never equals anything.
This Week's New Stuff

Trending Now

Similar Territory

Keep the Momentum

Thank you for reading about Postgres Create Table With Foreign Key. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home