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.

SqlData Integrity

Code

snippet
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

FAQ

What are the relations in play here?
`customers`, `orders`.