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

Updated:   |  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 Buy Me A Coffee



Comments


Add a Comment


Please enter d20728 in the box below so that we can be sure you are a human.