invalid foreign key
SQLSTATE 42830 is raised when a FOREIGN KEY constraint definition is structurally invalid — for example, the referenced columns do not form a unique or primary key in the referenced table, or the column counts do not match.
- 1The referenced columns in a FOREIGN KEY do not have a UNIQUE or PRIMARY KEY constraint in the referenced table
- 2The number of columns in the FOREIGN KEY differs from the number of referenced columns
- 3The data types of the foreign key columns do not match the referenced columns
Creating a FK referencing a non-unique column.
CREATE TABLE orders ( order_id INT, customer_name TEXT, FOREIGN KEY (customer_name) REFERENCES customers(name) -- name has no UNIQUE constraint );
expected output
ERROR: there is no unique constraint matching given keys for referenced table "customers"
Fix 1
Add a UNIQUE or PRIMARY KEY constraint to the referenced column
WHEN When the referenced column is not already unique.
ALTER TABLE customers ADD CONSTRAINT customers_name_key UNIQUE (name);
Why this works
Foreign keys must reference a column (or column combination) with a UNIQUE or PRIMARY KEY constraint in the parent table.
Fix 2
Reference the primary key of the parent table instead
WHEN When the foreign key should reference the natural primary key.
CREATE TABLE orders ( order_id INT, customer_id INT, FOREIGN KEY (customer_id) REFERENCES customers(id) );
Why this works
Primary keys are always unique and are the most common foreign key target.
Class 42 — Syntax Error or Access Rule Violation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev