Postgres (SQL) - Resolve "duplicate key value violates unique constraint"

by
Jeremy Canfield |
Updated: September 16 2022
| Postgres (SQL) articles
Let's say duplicate key value violates unique constraint is being returned when attempting to insert a record into a Postgres table.
psql -U postgres_user -c "INSERT INTO "my_table" ("id", "name") VALUES ('12345', 'john.doe')"
ERROR: duplicate key value violates unique constraint "unique_name"
DETAIL: Key (name)=(john.doe) already exists.
Notice in this example that the "name" column has UNIQUE CONSTRAINT meaning each record in my_table must have a unique name.
~]$ psql --username postgres_user --dbname my_database
my_database=# \d my_table
Table "public.my_table"
Column | Type | Collation | Nullable | Default
-----------------------+--------------------------+-----------+----------+---------
id | uuid | | not null |
name | text | | |
Indexes:
"primary_key" PRIMARY KEY, btree (id)
"unique_name" UNIQUE CONSTRAINT, btree (name)
The most likely issue here is that there is already a record in my_table with name john.doe.
~]$ psql --username postgres_user --dbname my_database --command "select * from my_table where name = 'john.doe'" -x
-[ RECORD 1 ]---------+-------------------------------------
id | 12345
name | john.doe
Did you find this article helpful?
If so, consider buying me a coffee over at