1

Given a database with hundreds or thousands of tables:

Considering that all tables were empty. Is there a way to automatically set auto_increment to 1 for all tables?

helloworld
  • 527
  • 6
  • 21
  • 1
    `auto_increment` can **only be unique** on a given table. – N.B. Mar 19 '15 at 16:42
  • 2
    You'd need to loop through all the tables (not possible to do this en masse directly in MySQL, AFAIK), and use something like this: https://stackoverflow.com/questions/970597/change-auto-increment-starting-number – Piskvor left the building Mar 19 '15 at 16:45
  • 2
    You can do this by running a command in the shell. You can try something like: https://stackoverflow.com/questions/1912813/truncate-all-tables-in-a-mysql-database-in-one-command . What's more, if all the tables are really empty, you can just truncate all them as the answer from the link without any changing the command. – Frederick Zhang Mar 19 '15 at 17:00
  • @AD7six debugging and testing purposes – helloworld Mar 19 '15 at 17:11

2 Answers2

1

Could try give it a go in PHP? Would have to know all of the table names.

$tableName = array('somename', 'someOtherName', ...);

foreach ($tableName as $key) {
//Do the query
ALTER TABLE $key MODIFY COLUMN id INT auto_increment
}

Pseudo code.. but you get the idea right?

meowfishcat
  • 137
  • 14
1

a database with hundreds or thousands of tables

That's likely to be a big mistake.

To do the task, write a Stored Procedure that creates a Cursor walking through information_schema.TABLES and building the SQL needed for each table. Then prepare() and execute() it.

If the SQL is not allowed in a Stored Procedure, then simply SELECT the SQL to show it. Then manually copy and past it into the mysql commandline tool.

Rick James
  • 135,179
  • 13
  • 127
  • 222