Coding⏱️ 2 min read📅 2026-05-31

How to Fix: ERROR: there is no unique constraint matching given keys for referenced table "bar"

Postgres error due to non-unique constraint on referenced table.

Quick Answer: Remove the UNIQUE constraint from the bar table.

The error message you're encountering, 'ERROR: there is no unique constraint matching given keys for referenced table "bar"', indicates that the UNIQUE constraint on the foo_fk column in the bar table is being overridden by a PRIMARY KEY constraint.

⚠️ Common Causes

  • The problem arises from the combination of PRIMARY KEY and UNIQUE constraints on the same column.

🔧 Proven Troubleshooting Steps

Method 1: Remove the PRIMARY KEY Constraint from foo_fk Column

  1. Step 1: Drop the primary key constraint on the foo_fk column in the bar table using the following SQL query: ALTER TABLE bar DROP CONSTRAINT foo_fk_pkey;

Method 2: Remove the PRIMARY KEY Constraint from bar Table

  1. Step 1: Drop the primary key constraint on the pkey column in the bar table using the following SQL query: ALTER TABLE bar DROP CONSTRAINT pkey;

🎯 Final Words

By removing one of these constraints, you should be able to create the table structure without any issues. Remember that when creating a foreign key constraint, it is essential to ensure that there are no duplicate values in the referenced column.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions