PostgreSQL "there is no unique constraint matching given keys for referenced table" means you tried to create a foreign key that points at columns which are not covered by a primary key, a unique constraint or a suitable unique index on the parent table. PostgreSQL refuses before it looks at any data.
CREATE TABLE orders (
id bigint,
customer_id bigint REFERENCES customers (account_no)
);
ERROR: there is no unique constraint matching given keys for referenced table "customers"
The error has SQLSTATE 42830, invalid_foreign_key, in the error codes appendix. It appears at CREATE TABLE or ALTER TABLE ... ADD FOREIGN KEY time, so it is a schema problem, not a data problem. A close relative appears when you write REFERENCES customers without a column list on a table that has no primary key: "there is no primary key for referenced table".
Why PostgreSQL insists on uniqueness
A foreign key promises that each child row matches exactly one parent row. That only holds if the referenced columns are unique. The constraints chapter puts it plainly: a foreign key must reference columns that are a primary key, form a unique constraint, or are the columns of a non-partial unique index. A side effect is that the referenced side always has an index for fast lookups.
This is a common surprise after a migration from MySQL. InnoDB historically allowed a foreign key to reference any indexed column, even a non-unique one. MySQL 8.4 rejects that by default through restrict_fk_on_non_standard_key and marks the old behaviour as deprecated, but older schemas ported as-is still carry such keys. Our MySQL to PostgreSQL migration guide covers the other differences worth checking.
What counts as a "matching" unique index
The rules live in transformFkeyCheckAttrs in tablecmds.c. A unique index on the parent matches only if all of these hold:
- Exactly the same set of columns. The number of key columns must equal the number of foreign key columns, and every one must appear. Order does not matter: an index on
(b, a)serves a foreign key on(a, b). - No superset, no subset. A unique index on
(tenant_id, id)does not serve a foreign key onidalone, and a uniqueiddoes not serve a foreign key on(tenant_id, id). This catches multi-tenant schemas all the time. Columns in anINCLUDEclause are not key columns and do not count. - Not partial.
CREATE UNIQUE INDEX ... WHERE deleted_at IS NULLis ignored. - No expressions. A unique index on
lower(email)cannot back a foreign key. - Valid. An index left
INVALIDby a failedCREATE INDEX CONCURRENTLYis skipped. - Not deferrable. A
DEFERRABLEunique or primary key gives a different error: "cannot use a deferrable unique constraint for referenced table".
If the columns match but the types cannot be compared, the error changes again to "foreign key constraint ... cannot be implemented", with a DETAIL naming the incompatible types. This query shows which unique indexes the parent actually has:
-- every unique index on the parent, with flags that matter for foreign keys
SELECT i.indexrelid::regclass AS index_name,
pg_get_indexdef(i.indexrelid) AS definition,
i.indisprimary, i.indisvalid, i.indimmediate,
i.indpred IS NOT NULL AS is_partial,
i.indexprs IS NOT NULL AS has_expressions
FROM pg_index i
WHERE i.indrelid = 'customers'::regclass
AND i.indisunique;
How to fix it
- Reference the primary key if that is what you meant. Often the child column was simply pointed at the wrong parent column.
- Add a unique constraint on exactly the referenced columns, if they really are unique in the business sense.
- For composite keys, match the column set exactly. If the child carries
(tenant_id, customer_id), the parent needs a unique constraint on that pair, even ifcustomer_idis already unique on its own. - Replace partial or expression indexes with a plain unique constraint, or reference a different key. For soft-deleted rows, reference the surrogate primary key instead of the natural key.
-- the referenced column is not unique yet: make it unique
ALTER TABLE customers ADD CONSTRAINT customers_account_no_key UNIQUE (account_no);
-- composite key: the unique constraint must cover exactly the FK columns
ALTER TABLE order_lines
ADD CONSTRAINT order_lines_order_line_key UNIQUE (order_id, line_no);
ALTER TABLE shipments
ADD FOREIGN KEY (order_id, line_no)
REFERENCES order_lines (order_id, line_no);
Partitioned parent tables. Foreign keys can reference a partitioned table, but the partitioning limitations require any unique or primary key constraint on it to include all partition key columns. A table partitioned by created_at therefore cannot have a unique constraint on id alone, and a foreign key on order_id fails with this exact error. The child has to carry the partition key too, for example (order_id, order_created_at), or the parent must be partitioned by a column that is part of the natural key.
Adding the missing uniqueness on large tables
On a small table, ALTER TABLE ... ADD UNIQUE finishes before anyone notices. On a table with hundreds of millions of rows it builds an index while holding a lock that blocks writes. A safer sequence:
- Look for duplicates first. If duplicates exist, a unique index build can fail late, after most of the work is done. Run the
GROUP BY ... HAVING count(*) > 1check on a replica and clean up before you start. - Build with CONCURRENTLY. Per the CREATE INDEX reference,
CREATE UNIQUE INDEX CONCURRENTLYdoes not lock out inserts, updates or deletes, but it takes longer, cannot run inside a transaction block and leaves anINVALIDindex behind if it fails. Drop that and retry. Uniqueness is already enforced against new writes during the second table scan, so a writer inserting a duplicate in that window gets an error. - Attach it as a constraint.
ADD CONSTRAINT ... UNIQUE USING INDEXturns the finished index into a named constraint quickly, as the ALTER TABLE reference describes. A valid unique index is already enough for a foreign key, so this step is about clarity, not function. It is not supported on partitioned tables. - Partitioned tables need per-partition builds.
CONCURRENTLYis not supported on the partitioned table itself; build the index on each partition concurrently, then create the parent index, which then only attaches the existing ones. - Then add the foreign key as NOT VALID and validate it, so the child table is not scanned under a lock. The details of that step, and of the errors it can raise, are in our article on violates foreign key constraint.
-- 1. find duplicates first, or the index build fails at the end
SELECT account_no, count(*)
FROM customers
GROUP BY account_no
HAVING count(*) > 1
LIMIT 20;
-- 2. build the unique index without blocking writes
CREATE UNIQUE INDEX CONCURRENTLY customers_account_no_key ON customers (account_no);
-- 3. if it failed, it is left INVALID: drop it and retry
-- DROP INDEX CONCURRENTLY customers_account_no_key;
-- 4. optional: turn the index into a named constraint (fast)
ALTER TABLE customers
ADD CONSTRAINT customers_account_no_key UNIQUE USING INDEX customers_account_no_key;
-- 5. add the foreign key without a long lock, validate later
ALTER TABLE orders
ADD CONSTRAINT orders_customer_fkey
FOREIGN KEY (customer_id) REFERENCES customers (account_no) NOT VALID;
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fkey;
In our experience the duplicate check is the step that saves the most time. A unique index that fails at 95 percent on a large table costs as much I/O as one that succeeds, and you still have to clean the data afterwards.
Key takeaways
- The error (SQLSTATE 42830) means the referenced columns have no primary key, unique constraint or plain unique index covering exactly them.
- The match must be the same set of key columns, in any order; supersets, subsets,
INCLUDEcolumns, partial, expression, invalid and deferrable indexes do not count. - Schemas ported from MySQL often reference non-unique columns; MySQL 8.4 now rejects that by default too.
- Partitioned parents need the partition key in every unique constraint, so the child must reference it as well.
- On big tables check for duplicates, build the unique index
CONCURRENTLY, then add the foreign key asNOT VALIDand validate it.