postgresql duplicate key violates unique constraint

前端 未结 8 939
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 10:37

Hi i have a question i know this was posted many times but i didn\'t find an answer to my problem. The problem is that i have a table and a column \"id\" i want it to be uni

相关标签:
8条回答
  • 2020-12-02 11:11

    The primary key is already protecting you from inserting duplicate values, as you're experiencing when you get that error. Adding another unique constraint isn't necessary to do that.

    The "duplicate key" error is telling you that the work was not done because it would produce a duplicate key, not that it discovered a duplicate key already commited to the table.

    0 讨论(0)
  • 2020-12-02 11:15

    This article explains that your sequence might be out of sync and that you have to manually bring it back in sync.

    An excerpt from the article in case the URL changes:

    If you get this message when trying to insert data into a PostgreSQL database:

    ERROR:  duplicate key violates unique constraint
    

    That likely means that the primary key sequence in the table you're working with has somehow become out of sync, likely because of a mass import process (or something along those lines). Call it a "bug by design", but it seems that you have to manually reset the a primary key index after restoring from a dump file. At any rate, to see if your values are out of sync, run these two commands:

    SELECT MAX(the_primary_key) FROM the_table;   
    SELECT nextval('the_primary_key_sequence');
    

    If the first value is higher than the second value, your sequence is out of sync. Back up your PG database (just in case), then run thisL

    SELECT setval('the_primary_key_sequence', (SELECT MAX(the_primary_key) FROM the_table)+1);
    

    That will set the sequence to the next available value that's higher than any existing primary key in the sequence.

    0 讨论(0)
提交回复
热议问题