Is there a way to run this or similiar AUTO_INCREMENT command for all tables in a database?
ALTER TABLE tablename AUTO_INCREMENT = 1
Is there a way to run this or similiar AUTO_INCREMENT command for all tables in a database?
ALTER TABLE tablename AUTO_INCREMENT = 1
Try this:
SELECT GROUP_CONCAT(`t`.`query` SEPARATOR '; ')
FROM
(
SELECT
CONCAT('ALTER TABLE `', `a`.`table_name`, '` AUTO_INCREMENT = 1') AS `query`,
'1' AS `id`
FROM `information_schema`.`tables` AS `a`
WHERE `a`.`TABLE_SCHEMA` = 'my_database' # <<< change this to your target database
#AND `a`.`TABLE_TYPE` = 'BASE TABLE' << optional
AND `a`.`AUTO_INCREMENT` IS NOT NULL
) AS `t`
GROUP BY `t`.`id`
This will generate a query for each table, but will not run the queries, so you will have to run the generated queries yourself.
Result will look like this:
ALTER TABLE `tablename1` AUTO_INCREMENT = 1; ALTER TABLE `tablename2` AUTO_INCREMENT = 1; ALTER TABLE `tablename3` AUTO_INCREMENT = 1;
You can use xargs (replace DB_NAME
):
mysql -Nsr -e "SELECT t.table_name FROM INFORMATION_SCHEMA.TABLES t WHERE t.table_schema = 'DB_NAME' AND table_type = 'BASE TABLE'" | xargs -I {} mysql DB_NAME -e "ALTER TABLE {} AUTO_INCREMENT = 1;"