Foreign Key Target Needs Unique Constraint

A foreign key can only reference columns covered by a PRIMARY KEY or UNIQUE constraint; creating one against a plain column fails with a matching-keys error.

SqlData Integrity

Code

snippet
-- 外键(FOREIGN KEY)的目标列集合必须带 PRIMARY KEY 或 UNIQUE 约束,
-- 指向普通列在建外键时直接失败(目标表没有能匹配该键集的唯一约束)
CREATE TABLE publishers (
    publisher_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    slug         text NOT NULL
);

-- slug 此时还没有 UNIQUE:这条会失败
-- CREATE TABLE books_bad (
--     book_id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
--     publisher text NOT NULL,
--     FOREIGN KEY (publisher) REFERENCES publishers (slug)
-- );

ALTER TABLE publishers ADD CONSTRAINT publishers_slug_key UNIQUE (slug);

-- 补上 UNIQUE 后外键才能建立,books.publisher 只能指向一个 publisher
CREATE TABLE books (
    book_id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    publisher text NOT NULL REFERENCES publishers (slug)
);

INSERT INTO publishers (slug) VALUES ('manning'), ('oreilly');
INSERT INTO books (publisher) VALUES ('manning'), ('oreilly');

What the code does

Several statements share this file — INSERT / CREATE / ALTER, with publishers and books among the objects involved.

Breaking the statements into their working parts: NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value; a foreign-key REFERENCES guard tying rows to the parent table.

Applying it

The publishers table is the working surface here.

Statements that matter

CREATE TABLE books (
book_id   bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
publisher text NOT NULL REFERENCES publishers (slug)
);
CREATE TABLE publishers (
publisher_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
slug         text NOT NULL
);
INSERT INTO publishers (slug) VALUES ('manning'), ('oreilly');

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
The references are `publishers`, `books`.