I googled and found this question, but the answer I am really looking for fulfils two criteria:
1. using purely MySQL queries
2. reset an existing table auto-increment to max(id) + 1
Since I couldn't find exactly what I want here, I have cobbled the answer from various answers and sharing it here.
Few things to note:
1. the table in question is InnoDB
2. the table uses the field `id` with type as `int` as primary key
3. the only way to do this purely in MySQL is to use stored procedure
4. my images below are using SequelPro as the GUI. You should be able to adapt it based on your preferred MySQL editor
5. I have tested this on MySQL **Ver 14.14 Distrib 5.5.61, for debian-linux-gnu**
## Step 1: Create Stored Procedure
create a stored procedure like this:
DELIMITER //
CREATE PROCEDURE reset_autoincrement(IN tablename varchar(200))
BEGIN
SET @get_next_inc = CONCAT('SELECT @next_inc := max(id) + 1 FROM ',tablename,';');
PREPARE stmt FROM @get_next_inc;
EXECUTE stmt;
SELECT @next_inc AS result;
DEALLOCATE PREPARE stmt;
set @alter_statement = concat('ALTER TABLE ', tablename, ' AUTO_INCREMENT = ', @next_inc, ';');
PREPARE stmt FROM @alter_statement;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
Then run it.
Before run, it looks like this when you look under Stored Procedures in your database.
[![enter image description here][1]][1]
When I run, I simply select the stored procedure and press Run Selection
[![enter image description here][2]][2]
Note: the delimiters part are crucial. Hence if you copy and paste from the top selected answers in this question, they tend not to work for this reason.
After I run, I should see the stored procedure
[![enter image description here][3]][3]
If you need to change the stored procedure, you need to delete the stored procedure, then select to run again.
## Step 2: Call the stored procedure
This time you can simply use normal MySQL queries.
call reset_autoincrement('products');
Originally from my own SQL queries notes in
[To see links please register here]
and adapted for Stack Overflow.
[1]:
[2]:
[3]: