tags:

views:

142

answers:

3

i've got an column named 'id' in a mysql table which also is a primary key that auto-increments.

when i delete rows their id's will also be deleted thus creating "holes" in my id sequence, eg.

1, 2, 3, 9, 10, 30 and so on

is there a way of reusing these deleted id:s?

+1  A: 

You have two options:

  1. manually specify the ID (this drops the auto from the auto-increment)
  2. TRUNCATE the table - this will delete all the records in the table

It's always a bad idea to reuse the "holes" created by deleting rows, this has been answered before here at SO but I'm too sleepy right now to go and find that question.

Alix Axel
how could i manually specify the lowest id? could u show me the php code for it?
weng
@noname: Like I said in my answer you shouldn't do that, the "holes" as you refer exist to ensure data (relation) integrity, if you don't want to have gaps in your table you'll be better setting a `deleted` flag column in your table when you want to delete a record instead of actually issuing a `DELETE` SQL statement.
Alix Axel
i use id as a link name..so i want it not to have big jumps between numbers..i think ill manually specify the id.
weng
+1  A: 

You can try 'ALTER TABLE t2 AUTO_INCREMENT = 1;'

Eric Butera
Worked for me on MySQL 4.1, but see my answer about its ability that might not fit the intended usage.
OMG Ponies
+1  A: 

Using:

ALTER TABLE [your table name here] AUTO_INCREMENT = 1

... will reset the auto_increment value to be the next based on the highest existing value existing in the table. That means it can't be used to correct gaps of more than one.

The only reason to do this would be for cosmetic ones - the database doesn't care if records are sequential, only that they relate to one another consistently. There's no need to "correct" the values for the database's sake.

If you are displaying the id values to the user, which is why you'd like them to always be sequential, then I'd recommend adding a surrogate key. Use the surrogate key for displaying to the user, so the values can be re-sequenced as needed but referencial integrity is otherwise unaffected. The surrogate key in this case would be an integer column.

OMG Ponies