Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 568
Marco Aurélio Deleu Avatar asked Dec 15 '22 17:12

Marco Aurélio Deleu


2 Answers

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;
like image 190
Saharsh Shah Avatar answered Dec 30 '22 16:12

Saharsh Shah


Just upon quick glance, the error says it all. Syntax is incorrect

The syntax should adhere to:

ALTER TABLE table_name AUTO_INCREMENT=<INTEGER_VALUE>;

So looking at your query, remove the word "SET"

ALTER TABLE table_name AUTO_INCREMENT =
(
    SELECT
        `AUTO_INCREMENT`
    FROM
        INFORMATION_SCHEMA.TABLES
    WHERE
        TABLE_SCHEMA = 'database_name'
    AND TABLE_NAME = 'another_table_name'
);
like image 42
rurouni88 Avatar answered Dec 30 '22 18:12

rurouni88