Search code examples
mysqlschemaauto-increment

Create new MySql schema from Backup .SQL source file resets auto increment id columns?


I am developing a large database schema that I desire to make available to clients.

I am new to MySql database administration. How do I restore a .sql file of the schema so that it also resets ALL auto incremental id columns back to 0 or Null again.

I actually restored to a new schema name and inserted a test record and found the auto id columns were incrementing from where they left-off in the last schema name.

How do I address this in MySql database modeling?

I want to always be able to 'spin-off' an exact copy of my current version data model for a paying customer.

Thank you.


Solution

  • You can dump the schema only, without data this way:

    $ mysqldump -d databasename > databasename-schema.sql
    

    If you use InnoDB tables (which you should), the auto-increment value is always reset every time you restart the MySQL instance. The value it is reset to in each table is equal to the max value currently stored in the table, plus 1. So if your tables are empty, the value will be 1.

    If you don't want to restart the MySQL instance after you restore, you can either strip the auto-increment clause in your CREATE TABLE statements before restoring:

    $ mysqldump -d databasename | sed -e 's/AUTO_INCREMENT=[0-9][0-9]*//' 
      > databasename-schema.sql
    

    Or else you can ALTER TABLE to reset the auto-increment value after restoring. This has to be done on a per-table basis, but you can query the list of tables that have auto-increment keys from the INFORMATION_SCHEMA:

    $ mysql -N -B -e "SELECT CONCAT('ALTER TABLE \`', table_schema, '\`.\`', 
      table_name, '\` AUTO_INCREMENT=1;') AS ddl FROM INFORMATION_SCHEMA.TABLES 
      WHERE table_schema = 'test' AND AUTO_INCREMENT IS NOT NULL" | mysql -v