Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Postgres 42830: no unique constraint matching keys

A foreign key needs a unique or primary key on the referenced columns. Add the matching constraint on the parent, order the migration, and check validity.

~5 min readSQL
#postgresql#foreign-keys#migrations#constraints
Bold white headline reading NO UNIQUE KEY with a Postgres foreign key crate blocked at an amber parent gate on the right.

Introduction & Quick Summary

A migration fails while creating a foreign key:

code
ERROR: there is no unique constraint matching given keys for referenced table "users" SQLSTATE: 42830

The foreign key points at a column set that is not unique in the referenced table. PostgreSQL requires the referenced columns to be covered by a unique constraint or a unique index, because otherwise the constraint could not identify a single parent row. SQLSTATE 42830 is specifically this validation failure; it is not a missing table (42P01) or a type mismatch (42804).

Where it appears:

  • A composite foreign key referencing (tenant_id, user_id) when users has a primary key on id only.
  • A migration that creates the FK before the unique index it depends on, in the same transaction.
  • A unique index that was created CONCURRENTLY and is still invalid after a failed build.
  • A partitioned parent table where the unique index exists on partitions but not on the parent.
  • A table copied from another schema where the primary key was dropped during a rename.

Quick answer: create a unique constraint or unique index on exactly the referenced column set in the parent table, then add the foreign key. Order the migration so the parent's uniqueness exists before any child references it.

Core Mechanics, Signatures & Reproducible Setup

A foreign key is a claim that each child row matches at most one parent row. PostgreSQL enforces that by requiring an index it can trust to be unique on the referenced columns. Primary keys and UNIQUE constraints both create such an index; a plain index does not, and neither does a partial unique index, because the constraint must hold for every row.

Reproduce the failure and fix it:

CREATE TABLE tenants (id bigint PRIMARY KEY); CREATE TABLE users ( id bigint NOT NULL, tenant_id bigint NOT NULL REFERENCES tenants(id), email text NOT NULL, PRIMARY KEY (id) -- unique on id alone ); CREATE TABLE sessions ( id bigserial PRIMARY KEY, tenant_id bigint NOT NULL, user_id bigint NOT NULL, CONSTRAINT sessions_user_fk FOREIGN KEY (tenant_id, user_id) REFERENCES users (tenant_id, id) ); -- ERROR: there is no unique constraint matching given keys for referenced table "users"

The parent needs the same pair to be unique:

ALTER TABLE users ADD CONSTRAINT users_tenant_id_key UNIQUE (tenant_id, id); -- now the same CREATE TABLE sessions statement succeeds

If users.id is already unique globally, UNIQUE (tenant_id, id) is redundant for correctness and still required for this FK shape, because the FK names both columns. The alternative is to reference only id.

What counts as a valid parent key:

Parent objectUsable by a foreign keyNote
PRIMARY KEY (a, b)yesexact column set
UNIQUE (a, b)yescreates a unique index
CREATE UNIQUE INDEX ... (a, b)yesnon-partial, valid
CREATE UNIQUE INDEX ... WHERE ...nopartial index cannot back an FK
Plain INDEX (a, b)nonot unique
EXCLUDE USING gist (...)noexclusion constraint is not a unique key
Invalid index after a failed CONCURRENTLY buildnoindisvalid = false

Key Comparison Table

The 42-class errors around foreign keys, and what each one asks for:

SQLSTATEMessageMeaningFix
42830no unique constraint matching given keysparent side lacks uniquenessadd unique constraint or index
42P01relation does not existwrong schema or orderingqualify the name, fix migration order
42703column does not existtypo in the column listcorrect the name
42804foreign key constraint cannot be implementedtype mismatch between columnsalign types
23503insert or update violates foreign keychild row has no parentinsert the parent first
23505duplicate key violates unique constraintuniqueness you just added already violateddeduplicate before adding

Two ways to satisfy the same FK, with different costs:

ApproachDDLEffect on writes
Unique constraint on the pairUNIQUE (tenant_id, id)extra index maintained on every insert
Reference the primary key onlyFOREIGN KEY (user_id) REFERENCES users (id)no extra index, loses tenant scoping guarantee
Separate table per tenantschema-level partitionmore objects, smaller indexes

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Migrations that create things in the wrong order

A single migration file that creates the child first fails on a fresh database and passes on a machine where the constraint already exists:

BEGIN; CREATE TABLE sessions (...); ALTER TABLE sessions ADD CONSTRAINT sessions_user_fk FOREIGN KEY (tenant_id, user_id) REFERENCES users (tenant_id, id); -- 42830 CREATE TABLE users (...); ALTER TABLE users ADD CONSTRAINT users_tenant_id_key UNIQUE (tenant_id, id); COMMIT;

DDL in PostgreSQL is transactional, so the whole migration rolls back and the database is unchanged — which is why the second run fails identically. Put the uniqueness before the reference, and keep each migration runnable from an empty database.

2. CONCURRENTLY leaves an invalid index

A unique index built with CREATE UNIQUE INDEX CONCURRENTLY that failed is left behind as invalid, and a foreign key cannot use it:

SELECT indexrelid::regclass AS index, indisvalid, indisunique FROM pg_index WHERE indrelid = 'users'::regclass;

If indisvalid is false, drop and rebuild the index outside a transaction:

sql
DROP INDEX CONCURRENTLY IF EXISTS users_tenant_id_idx; CREATE UNIQUE INDEX CONCURRENTLY users_tenant_id_idx ON users (tenant_id, id);

CONCURRENTLY cannot run inside a transaction block, so ORMs that wrap migrations in one need a separate migration entry for it.

3. Partitioned tables and the parent's uniqueness

From PostgreSQL 11 a partitioned table can be the parent of a foreign key, and the uniqueness must exist on the partitioned table itself, which means the partition key must be part of the unique index:

CREATE TABLE events ( id bigint NOT NULL, tenant_id bigint NOT NULL, occurred date NOT NULL, PRIMARY KEY (tenant_id, id) -- must include the partition key ) PARTITION BY RANGE (occurred);

A primary key of (tenant_id, id) on a table partitioned by occurred is rejected with unique constraint on partitioned table must include all partitioning columns, and an FK referencing a column set without the partition key fails with 42830. Include the partition key in the candidate key.

4. Composite keys and type alignment

Even with a correct unique constraint, a type mismatch produces a different but adjacent error:

-- tenant_id is bigint in users and integer in sessions ALTER TABLE sessions ADD CONSTRAINT sessions_user_fk FOREIGN KEY (tenant_id, user_id) REFERENCES users (tenant_id, id); -- ERROR: foreign key constraint "sessions_user_fk" cannot be implemented -- DETAIL: Key columns "tenant_id" are of a compatible type... (42804)

Verify the actual types before adding the constraint:

SELECT table_name, column_name, data_type FROM information_schema.columns WHERE table_name IN ('users', 'sessions') AND column_name IN ('tenant_id', 'id') ORDER BY table_name, column_name;

Mixed bigint/integer in a composite FK fails; text/varchar usually works because the underlying type is compatible, but uuid/text never does.

5. Auditing an unfamiliar schema before writing the FK

Inspect existing constraints instead of guessing what is already unique:

SELECT conrelid::regclass AS table, conname, contype, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid = 'users'::regclass;

contype values are p (primary key), u (unique), and f (foreign key). A u row with the pair means the FK will succeed; the absence of one is the answer to 42830, and the fix is one ALTER TABLE ... ADD CONSTRAINT on the parent.

Common Compilation/Runtime Mistakes & Version Gotchas

Adding the unique index to the child table. The error names the referenced table. A unique index on sessions (tenant_id, user_id) does not help; it makes duplicate sessions impossible instead.

Using a partial unique index. CREATE UNIQUE INDEX ON users (tenant_id, id) WHERE deleted_at IS NULL looks correct because active rows are unique, and PostgreSQL still rejects it for an FK. Drop the WHERE clause, or enforce the FK against a view of active rows instead.

Assuming column order is irrelevant. Build the unique constraint with the same column list as the FK, in the same order, and both sides stay readable. A mismatch in order is accepted in most cases but makes the intent hard to audit and confuses ORMs that introspect constraints.

Version differences worth knowing. PostgreSQL 15 added ON DELETE SET NULL (column_list) and made NULLS NOT DISTINCT available for unique constraints; a UNIQUE NULLS NOT DISTINCT constraint still backs an FK, while a plain UNIQUE with nullable columns allows multiple NULL parents and can surprise you when a composite key includes a nullable tenant. PostgreSQL 17 and 18 tightened validation of partitioned foreign keys and constraint inheritance, so a schema restored from an older dump may report 42830 where the original creation succeeded.

Reading the schema quickly. Format the DDL with the SQL formatter and generate a structural view of the tables with the schema designer before editing migrations that other people own, so the column order and types match what the database actually has.

Reference material: PostgreSQL foreign keys and PostgreSQL error codes.

Official references

primary documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.