How to Reset an MySQL AutoIncrement using a MAX value from another table?

ThinkCode picture ThinkCode · Mar 9, 2010 · Viewed 42.8k times · Source

I know this won't work, 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. Thank you!

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?

Answer

OMG Ponies picture OMG Ponies · Mar 9, 2010

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;