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.
Code
-- 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- The references are `order_items`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.