FK Incompatible Column Types

A foreign key needs comparable column types: integer referencing text fails at DDL time with an incompatible-types error until both ends match.

SqlData Integrity

Code

snippet
-- FK 两端列类型必须可比较:整数引用文本列,约束根本建不起来
CREATE TEMP TABLE invoices (
    invoice_id integer PRIMARY KEY
);

-- 引用列 integer,被引用列 text —— DDL 直接失败
-- CREATE TEMP TABLE broken_lines (
--     invoice_ref text REFERENCES invoices(invoice_id)
-- );
-- ERROR:  foreign key constraint ... cannot be implemented
-- DETAIL:  Key columns "invoice_id" and "invoice_ref" are of incompatible types:
--          integer and text

-- 修复:两端用同一类型
CREATE TEMP TABLE lines (
    invoice_ref integer REFERENCES invoices(invoice_id)
);

INSERT INTO invoices VALUES (1);
INSERT INTO lines VALUES (1);      -- 合法
INSERT INTO lines VALUES (9);      -- ERROR: violates foreign key constraint

How it works

What runs here is INSERT / CREATE — invoices and lines are the objects involved.

invoices and lines are created in this same file as session-local temp tables — nothing needs to exist beforehand, and they go away at session end.

Breaking the statements into their working parts: a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard binding child rows back to the parent table.

Using it

Nothing outside the file is needed: the session-local tables it touches (invoices, lines) are created by the file itself — point it at a scratch database and run the whole thing.

Key statements

CREATE TEMP TABLE lines (
    invoice_ref integer REFERENCES invoices(invoice_id)
);
INSERT INTO lines VALUES (9);      -- ERROR: violates foreign key constraint
CREATE TEMP TABLE invoices (
    invoice_id integer PRIMARY KEY
);

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`invoices`, `lines`.