Skip to content
Advertisement

Auto-increment a primary key in MySql

During the creation of tables using mysql on phpmyadmin, I always find an issue when it comes to primary keys and their auto-increments. When I insert lines into my table. The auto_increment works perfectly adding a value of 1 to each primary key on each new line. But when I delete a line for example a line where the primary key is ‘id = 4’ and I add a new line to the table. The primary key in the new line gets a value of ‘id = 5’ instead of ‘id = 4’. It acts like the old line was never deleted.

Here is an example of the SQL statement:

CREATE TABLE employe(
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30) NOT NULL
)

ENGINE = INNODB;

How do I find a solution to this problem ?

Thank you.

Advertisement

Answer

I’m pretty sure this is by design. If you had IDs up to 6 in your table and you deleted ID 2, would you want the next input to be an ID of 2? That doesn’t seem to follow the ACID properties. Also, if there was a dependence on that data, for example, if it was user data, and the ID determined user IDs, it would invalidate pre-existing information, since if user X was deleted and the same ID was assigned to user Y, that could cause integrity issues in dependent systems.

Also, imagine a table with 50 billion rows. Should the table run an O(n) search for the smallest missing ID every time you’re trying to insert a new record? I can see that getting out of hand really quickly.

Some links you might like to read:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement