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.
Code
-- 外键(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
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
- Which tables appear in this script?
- The references are `publishers`, `books`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.