Changing ID values in MySQL database with SQL command [duplicate] - mysql

This question already has answers here:
Reorder / reset auto increment primary key
(16 answers)
Closed 3 years ago.
I have a table in my MySQL database where the id's of the entries starts from 3000 because the previous rows were deleted. What I would like achieve is to change the value of the id columns. I would need the rows to start from 1. If I have 1900 entries, I would need the id's from 1 to 1900. The id column in my database is set to AUTO_INCREMENT and the id is primary key.
My question is that is it possible to achieve this with an SQL command? Or I should rather create a new database and transfer the objects with new id's?

As mentioned here https://stackoverflow.com/a/43137256/5031885
UPDATE table_name SET id = 0 - id;
set #counter = 0;
UPDATE table_name SET id = (#counter := #counter + 1);
This will first set all id values to negative equivalents and then will loop each row, update and increment the counter.
This solution will not work if id column is unsigned.
Also, keep in mind that this will not change the current AUTO_INCREMENT pointer.
To help with auto-increment you can use:
ALTER TABLE table_name AUTO_INCREMENT = 1;
Even if we assign 1 to AUTO_INCREMENT, it will continue with the next key as it should.

You should better drop the column and again add it as it will surely lead to inconsistancy of data as its a primary key plus if it becomes a foreign key as a reference in other table then it would create more problems even after dropping the column
You need to drop the column and then add it again with autoincrement and if it is also a foreign key then you have to drop the constraints from both the tables using CASCADE.

Related

Reset primary key for all rows of mysql table starting at specific value

Hello is there a mysql command to loop through all rows of a table and reset the primary key starting at specific value, e.g. from 5000 upwards?
I do NOT simply want to reset the primary key for the next input but update all existing rows.
This is not what I need:
ALTER TABLE t1 AUTO_INCREMENT = 1;
You can use a variable and update it after setting the value in each row. (e.g: assuming your column name is id):
SET #startVal=5000 - 1; # we will increment startVal in every loop so we subtract 1 to begin with
UPDATE t1 SET id=(#startVal:=#startVal+1);

Setting AUTO_INCREMENT attr [duplicate]

I am trying to set up a script to generate a particular set of test data into my database, at the beginning of which I want to clear the tables concerned without dropping constraints (because the test data is not the appropriate place to be rebuilding constraints) and reset the AUTO_INCREMENT for each table since setting up the test data is much, much simpler if I can hard-code many of the IDs.
For example, I have two statements like this (there's a pair for nearly every table):
DELETE FROM AppointmentAttr
ALTER TABLE AppointmentAttr AUTO_INCREMENT = 1
and while the records are deleted, the auto-increment value is not reverting to 1, even though all the documentation and SO answers I can find indicate that this should work.
If I do the same statement in MySQL Workbench it also does not revert it.
This is on an INNODB database.
What am I missing?
(Note: I cannot use TRUNCATE due to the presence of constraints).
MySQL does not permit you to decrease the AUTO_INCREMENT value, as specified here:
http://dev.mysql.com/doc/refman/5.6/en/alter-table.html
You cannot reset the counter to a value less than or equal to the value that is currently in use. For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.
Even with your constraints, I would try one of the following:
Explicitly insert your identities for your test data. MySQL doesn't have problems with this, unlike some other database engines
Delete and recreate your identity column (or just change it from being an identity), if the constraints aren't on it itself.
Not use an Identity column and use another method (such as a procedure or outside code) to control your Identity. This is really a last resort and I wouldn't generally recommend it...
Note from OP: It was (1) that was what I needed.
From what I can see about the alter table statement.
You can reset auto increment value by using the ALTER TABLE statement. The syntax of the ALTER TABLE statement to reset auto increment value is as follows:
ALTER TABLE table_name AUTO_INCREMENT = value;
You specify the table name after the ALTER TABLE clause and the value which we want to reset to in the expression AUTO_INCREMENT = value.
Notice that the value must be greater than or equal to the current maximum value of the auto-increment column.
Which is where your problem lies I suspect. So basically you are left with a couple of options as follows:
TRUNCATE TABLE: which according to our discussion is not a option
DROP and RECREATE the table: A long and painful experience
ALTER auto number column: I have not tried this but you could theoretically alter the primary key column from auto number to a int and then make it a auto number again. Something like:
ALTER TABLE tblName MODIFY COLUMN pkKeyColumn BIGINT NOT NULL;
ALTER TABLE tblName MODIFY COLUMN pkKeyColumn BIGINT AUTONUMBER NOT NULL;
Hope these help a little.
Can you not drop the relevant, auto increment column and recreate it? Example follows:
;;assuming your column is called id and your table is tbl
ALTER TABLE tbl DROP COLUMN id;
ALTER TABLE tbl ADD COLUMN id BIGINT UNSIGNED DEFAULT 1 PRIMARY KEY FIRST;
This should work, but I don't use MySQL, just going off the docs. If you need further help, leave a comment and I'll do my best to help out.
I'm sure this has been long answered but when i need to truncate and can't I just do a set foreign_key_checks = 0 then run my truncate and then set foreign_key_checks = 1.
I've run into this problem when I've deleted middle rows from my table.
My answer would be to INSERT NEW DATA TO NOT EXISTING ID.
I expect that my answer still be usefull even if it's PHP not MYSQL.
First fetch your data.
if found not existing row Insert values and exit;
else if not found in whole loop then do insertion for default value;
$rez = mysql_query("SELECT * FROM users");
$exists = 1;
while($row = mysql_fetch_array($rez)){
if ( $exists != $row{'id'} ){
echo "found not existing id: ".$exists;
INSERT INTO users VALUES($exists,.. ,..);
exit;
} $exists += 1;
}
INSERT INTO users VALUES(NULL,.. ,..); ##auto_inc column converts NULL to latest
I HOPE it will help somehow.
In non-problematic circumstances you can do
ALTER TABLE tbl AUTO_INCREMENT = 0;
which brings auto_increment value to the lowest allowed at the time.
ALTER TABLE tbl DROP COLUMN id;
ALTER TABLE tbl ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id); in your phpMyAdmin
ALTER TABLE table_name AUTO_INCREMENT = value;
This worked for me, I had to set it to the last record in my database while going through the operations panel never worked for me.
This worked for me hope it helps.
SET #autoid = 0; UPDATE users set id = #autoid := (#autoid+1); ALTER TABLE users AUTO_INCREMENT = 1;

MySQL Update command with auto increment [duplicate]

This question already has answers here:
How to reset the auto increment number/column in a MySql table
(4 answers)
Closed 8 years ago.
I have a table named users_items. In this table there are 3 columns. 1 of them is called id. There are like 100.000 - 150.000 data in this table. id is set to AUTO_INCREMENT.
I want to reset all id's to 0 and than replace with numbers 1,2,3,4,5,6 continue like that.
You won't be able to make all of them 0 at the same time, as you can't have duplicates for the PK.
Create a copy of the table using phpMyAdmin or any tool you want or using SQL queries.
Then delete all data from the original table using:
DELETE users_items
Or:
TRUNCATE users_items
Then reset auto increment using:
ALTER TABLE users_items AUTO_INCREMENT = 1
If you used TRUNCATE then you won't have to reset the auto increment counter.
After this you can use SELECT and INSERT to get the data from the copied table back to this one:
INSERT INTO users_items (col2, col3...) SELECT col2, col3,... FROM users_items_copy
(Note: the id column was not touched while selecting and inserting rows.)
To start from one simply do the following:
ALTER TABLE tablename AUTO_INCREMENT = 1
IF need reference use following links:
altering table:
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html
Auto increament/Reset primary key:
Reorder / reset auto increment primary key
Mysql reset autoincreament:
http://www.mysqltutorial.org/mysql-reset-auto-increment

MySQL: How to update key column starting with "1"

I am wondering how an elegant solution for this issue could look like:
I have a table with approx. 100 entries and one primary key column which has auto increment enabled. The keys start at 200.
Now I would like to disable the auto increment feature and update the key column so that the keys start at "1". Of course, I could just create a second table and just select/insert these values.
But I would like to know whether it is possible to update the key values directly. As the current keys start at 200 and there are less values, it should work somehow, right?
I don't know why do you need to do like this.I think these queries will work
SET #INDEX = 0;
UPDATE `tablename1` SET ID = (#INDEX:=#INDEX+1);
ALTER TABLE `tablename1` AUTO_INCREMENT = 100;
AUTO_INCREMENT is set as 100 to update for next row. you need to set AUTO_INCREMENT with correct value in your query to generate ID that the way you want.

Fixing gaps in mysql table row id after we delete some of them [duplicate]

This question already has answers here:
How to handle fragmentation of auto_increment ID column in MySQL
(5 answers)
Closed 2 years ago.
I have a mysql table with more than 17000 rows in it. And I have deleted about 530 rows from some mid part of it. Now each row had a sequential AUTO-INCREAMENTED number primary key. As you can understand now several numbers for rows have been deleted. So i just wanted to ask that is there any way to fix all rows again in some flawless order?
You can but be carefull of other tables using this primary key as a foreign key
SET #count = 0;
UPDATE table SET table.id = #count:= #count + 1;
this will update the id column of the table table ... you then need to reset the auto_increment :
ALTER TABLE table AUTO_INCREMENT = 1;
This resets the next id to be MAX(id)+1 from the docs :
To change the value of the AUTO_INCREMENT counter to be used for new
rows, do this:
ALTER TABLE t2 AUTO_INCREMENT = value;
You cannot reset the counter to a value less than or equal to any that
have already been used. For MyISAM, if the value is less than or equal
to the maximum value currently in the AUTO_INCREMENT column, the value
is reset to the current maximum plus one
There is a simple fix for this with php, i just tested it out.
$count = 0;
while ($row = mysqli_fetch_array($res)){
$count++;
mysqli_query($con, "UPDATE table SET id='".$count."' WHERE id='".$row['id']."'");
}