Foreign Key Into A Partitioned Table
A foreign key can reference a partitioned table once its columns match a unique constraint that includes the partition key.
Code
CREATE TABLE customers (
id bigint NOT NULL,
region text NOT NULL,
name text NOT NULL,
PRIMARY KEY (id, region)
) PARTITION BY LIST (region);
CREATE TABLE customers_eu PARTITION OF customers FOR VALUES IN ('eu');
CREATE TABLE customers_us PARTITION OF customers FOR VALUES IN ('us');
INSERT INTO customers VALUES
(1, 'eu', 'ada'),
(2, 'us', 'bob');
-- 分区表的唯一约束必须包含分区键,因此外键也要带上 region 两列组合
CREATE TABLE orders (
id int GENERATED ALWAYS AS IDENTITY,
customer_id bigint NOT NULL,
customer_region text NOT NULL,
amount numeric NOT NULL
);
ALTER TABLE orders
ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id, customer_region)
REFERENCES customers (id, region);
INSERT INTO orders (customer_id, customer_region, amount) VALUES
(1, 'eu', 42.00);
-- 引用不存在的 (customer_id, region) 组合会被立即拒绝
-- INSERT INTO orders (customer_id, customer_region, amount) VALUES (9, 'eu', 1.00);
-- ERROR: insert or update on table "orders" violates foreign key constraint "orders_customer_fk"How the snippet works
What runs here is INSERT / CREATE / ALTER — customers and orders are the objects involved.
What the statements actually assemble: 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 customers table is the working surface here.
Key statements
CREATE TABLE customers (
id bigint NOT NULL,
region text NOT NULL,
name text NOT NULL,
PRIMARY KEY (id, region)
) PARTITION BY LIST (region);
CREATE TABLE customers_eu PARTITION OF customers FOR VALUES IN ('eu');
CREATE TABLE customers_us PARTITION OF customers FOR VALUES IN ('us');
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 are the relations in play here?
- `customers`, `orders`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.