Incident Response

PostgreSQL: there is no unique constraint matching given keys for referenced table

A foreign key can only point at columns PostgreSQL can prove are unique. Here is exactly what counts as a match, why composite keys and partitioned tables trip people up, and how to add the missing constraint to a big table safely.

· 12 min read · AG Data Team

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:

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

  1. Reference the primary key if that is what you meant. Often the child column was simply pointed at the wrong parent column.
  2. Add a unique constraint on exactly the referenced columns, if they really are unique in the business sense.
  3. 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 if customer_id is already unique on its own.
  4. 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:

-- 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

PostgreSQL Errors Constraints Schema changes
Work with us

Schema migration stuck on constraints?

We design keys and constraints for PostgreSQL schemas, port foreign keys from MySQL and add uniqueness to large production tables without blocking writes.

Get in touch More from the blog