Unique Foreign Key One To One

Add UNIQUE to the referencing column so a foreign key allows at most one child per parent, turning a one-to-many relationship into a true one-to-one.

SqlData Integrity

Code

snippet
-- 一对一 = FOREIGN KEY + 被引用列 UNIQUE:同一父行最多被子表引用一次
CREATE TABLE companies (
    id   integer PRIMARY KEY,
    name text NOT NULL
);

CREATE TABLE tax_profiles (
    id         integer PRIMARY KEY,
    company_id integer NOT NULL UNIQUE,
    vat_number text    NOT NULL,
    FOREIGN KEY (company_id) REFERENCES companies (id)
);

INSERT INTO companies (id, name) VALUES (1, 'acme'), (2, 'globex');
INSERT INTO tax_profiles (id, company_id, vat_number)
VALUES (1, 1, 'DE811');

-- 第二份档案再指向公司 1:外键本身满足,但 UNIQUE 先拦下
-- ERROR:  duplicate key value violates unique constraint "tax_profiles_company_id_key"
-- INSERT INTO tax_profiles (id, company_id, vat_number) VALUES (2, 1, 'DE999');

-- company_id 上有唯一索引:从任一方向关联都是至多一行
SELECT c.name, t.vat_number
FROM companies c
LEFT JOIN tax_profiles t ON t.company_id = c.id
ORDER BY c.id;

What the code does

Several statements share this file — SELECT / INSERT / CREATE, with companies and tax_profiles among the objects involved.

The SQL constructs in play: one JOIN combining rows across tables; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a foreign-key REFERENCES clause that anchors each child row to its parent.

Applying it

Run it in the companies database context.

Statements that matter

SELECT c.name, t.vat_number
FROM companies c
LEFT JOIN tax_profiles t ON t.company_id = c.id
ORDER BY c.id;
CREATE TABLE tax_profiles (
id         integer PRIMARY KEY,
company_id integer NOT NULL UNIQUE,
vat_number text    NOT NULL,
FOREIGN KEY (company_id) REFERENCES companies (id)
);
INSERT INTO tax_profiles (id, company_id, vat_number)
VALUES (1, 1, 'DE811');

Interactive Tools for This Topic

FAQ

What are the relations in play here?
The references are `companies`, `tax_profiles`, with one join tying the pair together.