MySQL Delete all rows from table and reset ID to zero

后端 未结 5 2003
野性不改
野性不改 2020-12-12 09:29

I need to delete all rows from a table but when I add a new row, I want the primary key ID, which has an auto increment, to start again from 0 respectively from 1.

5条回答
  •  佛祖请我去吃肉
    2020-12-12 10:12

    If table has foreign keys then I always use following code:

    SET FOREIGN_KEY_CHECKS = 0; -- disable a foreign keys check
    SET AUTOCOMMIT = 0; -- disable autocommit
    START TRANSACTION; -- begin transaction
    
    /*
    DELETE FROM table_name;
    ALTER TABLE table_name AUTO_INCREMENT = 1;
    -- or
    TRUNCATE table_name;
    -- or
    DROP TABLE table_name;
    CREATE TABLE table_name ( ... );
    */
    
    SET FOREIGN_KEY_CHECKS = 1; -- enable a foreign keys check
    COMMIT;  -- make a commit
    SET AUTOCOMMIT = 1 ;
    

    But difference will be in execution time. Look at above Sorin's answer.

提交回复
热议问题