Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reset an MySQL AutoIncrement using a MAX value from another table?

I know this won't work. I tried it in various forms and failed all times. What is the simplest way to achieve the following result?

ALTER TABLE XYZ AUTO_INCREMENT = (select max(ID) from ABC); 

This is great for automation projects.

SELECT @max := (max(ID)+1) from ABC;        -> This works! select ID from ABC where ID = (@max-1);     -> This works! ALTER TABLE XYZ AUTO_INCREMENT = (@max+1);  -> This fails :( Why? 
like image 314
ThinkCode Avatar asked Mar 09 '10 16:03

ThinkCode


People also ask

How do I reset Autoincrement?

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. The name of the table whose AUTO_INCREMENT column you wish to reset.

Does truncate table reset auto increment?

The TRUNCATE TABLE statement removes all the data from a table and resets the auto-increment value to zero.

What happens when an auto increment column reaches maximum value in the table?

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.

Which of the following will be used to reset the auto increment column value?

Using the ALTER TABLE Statement. The ALTER TABLE statement is used to change the name of a table or any table field. It is also used to add, delete, or reset an existing column in a table. MySQL also allows this statement to reset the auto-increment column value whenever we want.


1 Answers

Use a prepared statement:

  SELECT @max := MAX(ID)+ 1 FROM ABC;    PREPARE stmt FROM 'ALTER TABLE ABC AUTO_INCREMENT = ?';   EXECUTE stmt USING @max;    DEALLOCATE PREPARE stmt; 
like image 159
OMG Ponies Avatar answered Sep 28 '22 06:09

OMG Ponies