ERROR: duplicate key value violates unique constraint in PostgreSQL

ERROR: duplicate key value violates unique constraint in PostgreSQL

In this article, I will let you know that how to resolve primary key sequence issue in PostgreSQL. This issue will only come when your application care about gaps in sequence.

Gaps in sequence is normal when you perform some rollback transaction after some errors

Below is the formatted error message that you can get while inserting new rows:

    ERROR:  duplicate key value violates unique constraint "table_name_pkey"
    DETAIL:  Key (id)=(x) already exists.

If you get this error then here is the solution for you :

    SELECT setval('your_table_id_seq', COALESCE((SELECT MAX(id)+1 FROM your_table), 1), false);

SELECT nextval('your_table_id_seq'); this code will let you know the higher than the last result.

If you want to defend against concurrent inserts while you update the sequence then lock the table with below line of code.

LOCK TABLE your_table IN EXCLUSIVE MODE;

It will keep concurrent transactions from writing a higher number.

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
escort bayan escort bayan escort bayan escort bayan escort bayan escort bayan escort bayan sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort adapazarı escort adapazarı escort adapazarı escort adapazarı escort adapazarı escort adapazarı escort adapazarı escort serdivan escort serdivan escort serdivan escort serdivan escort serdivan escort serdivan escort serdivan escort sakarya escort bayan sakarya escort bayan sakarya escort bayan sakarya escort bayan sakarya escort bayan sakarya escort bayan sakarya escort bayan escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya serdivan escort sapanca escort karasu escort hendek escort izmir escort