Mysql – thesql set auto increment to 1 with foreign key

auto-incrementMySQL

I want to set auto increment to 1 by below command, but it doesn't works:

ALTER TABLE tablename AUTO_INCREMENT = 1

I searched and found out that I should use TRUNCATE TABLE. But this command fails due to foreign key constraint. Any idea?

Best Answer

If you ever need ALTER TABLE tablename AUTO_INCREMENT = 1 you are probably misusing AUTO_INCREMENT. AUTO_INCREMENT is designed to provide unique keys, nothing more. If you need it to be "1", you should invent your own mechanism; do not trust AUTO_INCREMENT.

Would you care to explain your purpose? Perhaps we can help you find a suitable workaround. (No "setting it to 1" is not the purpose, it is your attempted solution to some higher purpose. Step back.)