Auto Increment Problem in Mysql - mysql

I created a table and set a field to auto increment some thing like this:
CREATE TABLE t1(id BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT) ENGINE = MyISAM AUTO_INCREMENT = 123456;
But to some reason i deleted some of the rows in the table.
Now the question is when i insert new rows in the table the new rows should be assigned id's of the rows which have been deleted rather than assigning new id's.
I do not want to reset all the id's
How can i do this??
Help appreciated:)

Sorry to say, but that is not the use of AUTO_INCREMENT. If you want to re-use id's, then you would have to write your own trigger functions, and doing this is generally considered bad practice.
Imagine you were on id 50,000, and deleted an entry with id 1... would you really want the next record you add to re-use id 1?

The whole point of AUTO_INCREMENT is to auto increment...
You can explicitly assign these ids though and mysql will allow it.

You are going to have to do this manually rather than rely on MySQL to do it for you. The AUTO-INCREMENT flag keeps an integer that is incremented upon every insert statement and is assigned as the PK of the subsequent insert. Unless you want to write an update trigger that resets this value to the lowest non-used integer, I would suggest processing this in a server-side scripting language.
In any case, though, why is using the auto increment value a problem?

To reset the autoincrement value, you can use
ALTER TABLE t1 AUTO_INCREMENT=1
The next inserted record will use ID 1.

This might be something you're after.
alter table Users AUTO_INCREMENT=0;
This will reset the auto_increment back to 0 + whatever the current highest id is.
if you have 30, your next entry would be 31

Related

Why mysql autoincrement increments the last used id rather then the last existing id

I am using mysql, and am looking at a strange behavior.
Scenario :
I have a table having table_id as primary key, which is set to auto-increment.
table_id more_columns
1 some value
2 others
Now if i delete row 2, and insert one more row, the table_id becomes 3 (Expected is 2)
table_id more_columns
1 some value
3 recent
Why is it so? Here I am loosing some ids (I know they are not important). Please put some lights on this behavior
In auto-increment field If a row is deleted, the auto_increment column of that row will not be re-assigned.
Please see here for more information.
For reasons why auto-increment doesn't use deleted values you can refer here(mentioned in comments by #AaronBlenkush).
The auto_increment value is a counter stored internally for each table. The counter is only increased, never decreased.
Every syntactically correct INSERT statement fired against the table increments this counter, even when it is rolled back and also when you define an insert value for the primary key.
A MySQL auto_increment column maintains a number internally, and will always increment it, even after deletions. If you need to fill in an empty space, you have to handle it yourself in PHP, rather than use the auto_increment keyword in the table definition.
Rolling back to fill in empty row ids can cause all sorts of difficulty if you have foreign key relationships to maintain, and it really isn't advised.
The auto_increment can be reset using a SQL statement, but this is not advised because it will cause duplicate key errors.
-- Doing this will cause problems!
ALTER table AUTO_INCREMENT=12345;
EDIT
To enforce your foreign key relationships as described in the comments, you should add to your table definition:
FOREIGN KEY (friendid) REFERENCES registration_table (id) ON DELETE SET NULL;
Fill in the correct table and column names. Now, when a user is deleted from the registration, their friend association is nulled. If you need to reassociate with a different user, that has to be handled with PHP. mysql_insert_id() is no longer helpful.
If you need to find the highest numbered id still in the database after deletion to associate with friends, use the following.
SELECT MAX(id) FROM registration_table;
After delete write this query
ALTER TABLE tablename AUTO_INCREMENT = 1

Reset the table Auto Increment and make it apply to the table

I have a table with around 10k rows which I've imported. The ID is a significant column to my application, and it has to be ordered. Currently, I got something like: 1,2,3,4,5....5789,9275,9276.....
It jumped from 5789 to 9275. Is there any way I can reset the Auto Increment but also make it apply to the table? which means, now it will start giving them IDS all over again from 1 to 10k
Thanks!
ALTER TABLE <tablename> AUTO_INCREMENT=<new_value>;
Of course you need to fix the high IDs and all references to them manually.
However, why do you care? Does it really matter if there's a hole in the IDs? If yes, you might want to use a separate column that's always set to MAX(col) + 1 instead of an AUTO_INCREMENT column.
You can certainly reset the auto_increment value to be whatever you want by simply issuing this query:
ALTER TABLE <tbl> AUTO_INCREMENT = <n>;
where tbl is your table name and n is the value to start it at. However, if you have existing IDs in that table already, I believe it will simply set the next inserted items ID to be max(id) + 1 of the ID column

Mysql Myisam re-using auto-incremented ids that are deleted

I have a table: test
id int(10) auto-increment
name char(36)
Now let us say my WHOLE table it filled from ID 1000 => max unique id number.
Id 1 - 1000 = deleted previously.
Question 1; WILL mysql re-use these deleted id's?
Question 2; If not, how to I go about having auto-increment or whatever to re-use unique identifier that does not exist in table?
The reason I am asking, is that my table will consist of alot of entries, and that alot of entries will be deleted all the time. What happens when I "run-out-of-id" when using auto-increment?
Thanks for any enlightment on this :)
-Tom
WILL mysql re-use these deleted id's?
When mysqld starts, it determines the next value for every AUTO_INCREMENT column by finding the maximum of the incumbent records (and adding 1). Therefore, if you delete the record with the highest value and restart the server, the deleted id will indeed be reused.
Otherwise, values will only be reused if you manually alter the next AUTO_INCREMENT value (this is not recommended as it is not concurrency-safe):
ALTER TABLE foo AUTO_INCREMENT = 12345;
If not, how to I go about having auto-increment or whatever to re-use unique identifier that does not exist in table?
Generally speaking, you don't: consider redesigning your data structure so that inserts/deletes do not happen in this fashion, or else use a larger integer type (BIGINT UNSIGNED is 8 bytes, so can go up to 2^64 or ~10^19).
What happens when I "run-out-of-id" when using auto-increment?
As stated in the manual:
Use the smallest integer data type for the AUTO_INCREMENT column that is large enough to hold the maximum sequence value you will need. When the column reaches the upper limit of the data type, the next attempt to generate a sequence number fails.
No, MySQL won't reuse the IDs from deleted records
Do you really need to? If the type of your autoincrement column is BIGINT, you've got 18446744073709551615 possible IDs
you need to reset the autoincrement, Autoincrement just keep incrementing and won't go back at least if you don't set it.
alter table tablename auto_increment=value
like this
mysql> alter table t1 auto_increment=200;
Query OK, 202 rows affected (0.04 sec)
Records: 202 Duplicates: 0 Warnings: 0
EDIT:
if you delete some records, the auto_increment will be "last value+1", it doesn't matter what you do, only if you delete the full table you'll be able to 'start over'.
The best would be with a trigger, but triggers can't alter tables (http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html)
So your last option is a store procedure take a look here: Is it possible to alter a table in mySql via stored procedures?
Which is not recommended.

prevent gaps in MySQL id field

I have a MySQL table with an auto incremement id field. When I delete a row and then insert a new row, The id of the row I deleted is skipped and the new gets an id of one greater than the previous row. Is there any way I can prevent this? I would like the new row to just replace the old one. Is there an important reason why this happens that I am missing?
The MySQL auto-increment function NEVER goes backward unless you force it to. And for a good reason. What if there was stray references to the missing records (logs, tables, etc...)?
You can force it by using this command:
ALTER TABLE tbl AUTO_INCREMENT = 1000;
Or, if you need to do it as part of the query:
LOCK TABLES tbl WRITE;
SELECT #id := MAX(id) FROM tbl;
INSERT INTO tbl SET id=#id, ...;
UNLOCK TABLES;
If you are using InnoDB, you could do this in a transaction instead...
Better to leave it be, however.
The definition of an autoincrement field is that every new row inserted is guaranteed to get a unique value. If you want to keep the old value then you must UPDATE the row instead of replacing it. If your design requires that autoincrement column values be contiguous then you will have to manage that yourself.
I'm sorry but I don't know the exact reason.
AFAIK you can't avoid that behavior unless you TRUNCATE the table or explicitly specify the id.

Does dropping a SQL table reset its ID value?

Will the ID auto-increment value be reset if I drop (wipe) a MySQL table? And, if I delete (for example) the entry N° 535, will this entry number be filled again later?
I don't want that ID to be filled with other new entries if I wiped old data. If this is not the behavior, then what's the solution to avoid this?
Which DBMS are you using? MySQL does reset the auto-increment value when you TRUNCATE a table. You can use the (much slower) DELETE FROM tablename to avoid this.
The auto_increment value doesn't change if you DELETE a line, but it is reseted if you do a TRUNCATE TABLE. And the next ID is always the current auto_increment value ("gaps" aren't filled again).
You can change the auto_increment value with ALTER TABLE table AUTO_INCREMENT = num
Yes. The solution would be to not DROP your table. Instead use DELETE FROM ...
If you drop a table, it will be gone along with any identity seed values.