Jump to content

insert into query question


Cyjm1120
Go to solution Solved by Jacques1,

Recommended Posts

Hi I am having troubles inserting item into a table with a primary key in it.

 

My problem is that every time I added a row into a table without specifying the primary key, mysql will not add it to the next available id.

 

For example, I have 5 rows initially and I added 10 rows into my table by using the insert into query. However when I delete the 10 rows and add another row in, the id of the additional row will become 16 instead of 6.

 

FYI, this is a php page that inserts my data into the table.

Link to comment
Share on other sites

  • Solution

MySQL does not magically reset the AUTO_INCREMENT counter when you delete rows. Once a number is taken, it won't be used again. This is the easiest and most robust solution.

 

If you absolutely must have this feature, you need to implement it yourself. But be aware that this is much harder than it may sound, because you have to deal with concurrent requests. For example, two rows may be inserted at (almost) the same time, in which case you must make sure that they don't take the same “next ID”.

 

My advice is, just stick to whatever number you get. An UNSIGNED INT can hold numbers up to 4 trillion, so there's not exactly a shortage of IDs. And if your application cannot handle gaps between the IDs, then that's the problem which needs to be fixed.

Link to comment
Share on other sites

Actually, you shouldn't expect AUTO_INCREMENT to yield a perfect sequence at all. There are all kinds of situations when a gap can occur. For example, if an INSERT query is aborted due to a constraint violation or a transaction rollback, then the reserved numbers will be skipped and never made available to you. You cannot even rely on the order of the numbers. You may get a low number after a high number due to a deferred query.

 

The only promise which AUTO_INCREMENT makes is that you get a unique number. The exact value depends on the underlying technical details and is more or less undefined.

Edited by Jacques1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.