Search code examples
mysqlsqlselectauto-incrementalter-table

Alter AUTO_INCREMENT value by select result


Basically what I want is a working-version of the following code:

ALTER TABLE table_name
AUTO_INCREMENT =
(
    SELECT
        `AUTO_INCREMENT`
    FROM
        INFORMATION_SCHEMA.TABLES
    WHERE
        TABLE_SCHEMA = 'database_name'
    AND TABLE_NAME = 'another_table_name'
);

The error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AUTO_INCREMENT =

The reason:

According to MySQL Doc:

InnoDB uses the in-memory auto-increment counter as long as the server runs. When the server is stopped and restarted, InnoDB reinitializes the counter for each table for the first INSERT to the table, as described earlier.

This means that whenever I restart the server, my auto_increment values are set to the minimum possible.

I have a table called ticket and another one called ticket_backup. Both of them have a column id that is shared. Records inside the ticket table are available and can be claimed by customers. When they claim the ticket I insert the record inside ticket_backup and then I erase them from ticket table. As of today, I have 56 thousand tickets already claimed (inside ticket_backup) and 0 tickets available. If I restart the server now and don't perform the ALTER TABLE, the first ticket I make available will have id 1 which is an ID already taken by ticket_backup, thus causing me duplicate key error if I don't fix the auto-increment value. The reason for me to want this in a single query is to be able to easily perform the query on server startup.


Solution

  • Try this:

    SELECT `AUTO_INCREMENT` INTO @AutoInc
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_SCHEMA = 'database_name' AND TABLE_NAME = 'another_table_name';
    
    SET @s:=CONCAT('ALTER TABLE `database_name`.`table_name` AUTO_INCREMENT=', @AutoInc);
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;