It is possbile set/reset the AUTO_INCREMENT
value of a MySQL table via
ALTER TABLE some_table AUTO_INCREMENT = 1000
However I need to set the AUTO_INCREMENT
upon its existing value (to fix M-M replication), something like:
ALTER TABLE some_table SET AUTO_INCREMENT = AUTO_INCREMENT + 1
which is not working
Well actually, I would like to run this query for all tables within a database. But actually this is not very crucial.
I could not find out a way to deal with this problem, except running the queries manually. Will you please suggest something or point me out to some ideas.
Thanks
In MySQL, the syntax to change the starting value for an AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = start_value; table_name. The name of the table whose AUTO_INCREMENT value you wish to change.
In MySQL, the syntax to reset the AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = value; table_name.
What will happen if the MySQL AUTO_INCREMENT column reaches the upper limit of the data type? When the AUTO_INCREMENT column reaches the upper limit of data type then the subsequent effort to generate the sequence number fails.
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
Using:
ALTER TABLE some_table AUTO_INCREMENT = 0
...will reset the auto_increment value to be the next value based on the highest existing value in the auto_increment column.
To run this over all the tables, you'll need to use MySQL's dynamic SQL syntax called PreparedStatements because you can't supply the table name for an ALTER TABLE statement as a variable. You'll have to loop over the output from:
SELECT t.table_name FROM INFORMATION_SCHEMA.TABLES t WHERE t.table_schema = 'your_database_name'
...running the ALTER TABLE statement above for each table.
set @db = 'your_db_name'; SELECT concat('ALTER TABLE ', @db, '.', TABLE_NAME, ' AUTO_INCREMENT = 0;') FROM information_schema.TABLES WHERE TABLE_SCHEMA = @db AND TABLE_TYPE = 'BASE TABLE'
Then copy-paste and run the output you get.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With