I thought auto_increment prevents duplicates entries?

182 Views Asked by At

I am getting duplicate entry error for key 'primary' when trying to insert values and I can't get past it. I added auto_increment to the integer part of the composite key (term_taxonomy_id). Isn't auto_increment supposed to resolve duplicate entries in these situations by incrementing the error-causing record on the fly?

+------------------+---------------------+------+-----+---------+----------------+
| Field            | Type                | Null | Key | Default | Extra          |
+------------------+---------------------+------+-----+---------+----------------+
| object_id        | varchar(50)         | NO   | PRI | NULL    |                |
| term_taxonomy_id | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| term_order       | int(11)             | NO   |     | 0       |                |
+------------------+---------------------+------+-----+---------+----------------+
1

There are 1 best solutions below

0
On

https://dev.mysql.com/doc/refman/8.0/en/example-auto-increment.html says:

When you insert any other value into an AUTO_INCREMENT column, the column is set to that value and the sequence is reset so that the next automatically generated value follows sequentially from the largest column value.

So the auto-increment column generates a new, unique value only if you insert NULL or 0. If you specify a nonzero integer value, you override the auto-increment, and MySQL trusts that you are inserting the value you want. But that means you take responsibility for ensuring the values you insert are unique.