Index Foreign Key Child Columns

Index foreign key child columns because PostgreSQL does not create them automatically, so parent deletes avoid scanning the child table.

SqlData Integrity

Code

snippet
-- PostgreSQL 不会为外键列自动建索引:父表 DELETE/UPDATE 验证引用时
-- 只能对子表做顺序扫描
CREATE TABLE orders (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);

CREATE TABLE order_items (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_id bigint NOT NULL REFERENCES orders (id),
    sku text NOT NULL
);

-- 给 FK 列补索引:父表删除时靠它定位子表引用行
CREATE INDEX order_items_order_id_idx ON order_items (order_id);

EXPLAIN (COSTS OFF)
SELECT count(*) FROM order_items WHERE order_id = 42;

How it works

Several statements share this file — SELECT / CREATE / EXPLAIN, with order_items among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value; a foreign-key REFERENCES guard tying rows to the parent table.

Using it

The order_items table is the working surface here.

Key statements

EXPLAIN (COSTS OFF)
SELECT count(*) FROM order_items WHERE order_id = 42;
CREATE TABLE order_items (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    order_id bigint NOT NULL REFERENCES orders (id),
    sku text NOT NULL
);
CREATE TABLE orders (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY
);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
The references are `order_items`.