310

In MySQL, I have a table, and I want to set the auto_increment value to 5 instead of 1. Is this possible and what query statement does this?

John Joe
  • 12,412
  • 16
  • 70
  • 135
John Jones
  • 2,175
  • 2
  • 20
  • 29
  • you can't CHANGE, only increase – Vasilii Suricov Feb 23 '19 at 15:33
  • 2
    @VasiliiSuricov `You can change this option with ALTER TABLE, but in that case the new value must be higher than the highest value which is present in the AUTO_INCREMENT column.` [_source_](https://mariadb.com/kb/en/library/create-table/#auto_increment) If there is no higher value than what you want to set your `auto_increment`ed column, you can also decrease the value. ([mysql documentation](https://dev.mysql.com/doc/refman/5.7/en/alter-table.html)) – seyfahni Nov 20 '19 at 16:41

8 Answers8

609

You can use ALTER TABLE to change the auto_increment initial value:

ALTER TABLE tbl AUTO_INCREMENT = 5;

See the MySQL reference for more details.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
113

Yes, you can use the ALTER TABLE t AUTO_INCREMENT = 42 statement. However, you need to be aware that this will cause the rebuilding of your entire table, at least with InnoDB and certain MySQL versions. If you have an already existing dataset with millions of rows, it could take a very long time to complete.

In my experience, it's better to do the following:

BEGIN WORK;
-- You may also need to add other mandatory columns and values
INSERT INTO t (id) VALUES (42);
ROLLBACK;

In this way, even if you're rolling back the transaction, MySQL will keep the auto-increment value, and the change will be applied instantly.

You can verify this by issuing a SHOW CREATE TABLE t statement. You should see:

> SHOW CREATE TABLE t \G
*************************** 1. row ***************************
       Table: t
Create Table: CREATE TABLE `t` (
...
) ENGINE=InnoDB AUTO_INCREMENT=43 ...
Cosimo
  • 2,846
  • 1
  • 24
  • 26
  • 6
    THANKS! `SET foreign_key_checks = 0;` is also useful for this. – dnozay Mar 13 '13 at 19:26
  • Brilliant idea! Nitpick: `SHOW CREATE TABLE t` will actually return `43`, i.e. next value after inserting `42`. – petrkotek May 27 '14 at 06:52
  • 3
    @cosimo, Wait, isn't this **undocumented**? Did the manual said that it should work that way? If not it may break in a different (future) mysql setup. – Pacerier Feb 03 '15 at 15:12
  • 2
    @Pacerier yes, you are correct. This is relying on the way MySQL works currently. It might not work like that in the future. Given MySQL history though, I would assume it will continue to work that way for a long time. – Cosimo Feb 06 '15 at 09:16
  • @cosimo, Hopefully they would document it so that reliable code could actually use this good hack. As of now, code which wants to be reliable can't use this. – Pacerier Feb 08 '15 at 15:45
  • Personally I use this as alternative only when I need to do it manually *and* I have a very large table at hand :) I wouldn't put this into some code/library. – Cosimo Feb 09 '15 at 09:38
  • In 5.6, at least, the ALTER only to change the auto-increment does not seem to require a rebuild. – Alden W. May 01 '15 at 18:08
  • I'm pretty sure this is now documented: `In MySQL 8.0 and later, if you modify an AUTO_INCREMENT column value to a value larger than the current maximum auto-increment value, the new value is persisted, and subsequent INSERT operations allocate auto-increment values starting from the new, larger value`. From: https://dev.mysql.com/doc/refman/8.0/en/innodb-auto-increment-handling.html – Kerwin Sneijders Jul 17 '23 at 10:58
16

How to auto increment by one, starting at 10 in MySQL:

create table foobar(
  id             INT PRIMARY KEY AUTO_INCREMENT,
  moobar         VARCHAR(500)
); 
ALTER TABLE foobar AUTO_INCREMENT=10;

INSERT INTO foobar(moobar) values ("abc");
INSERT INTO foobar(moobar) values ("def");
INSERT INTO foobar(moobar) values ("xyz");

select * from foobar;

'10', 'abc'
'11', 'def'
'12', 'xyz'

This auto increments the id column by one starting at 10.

Auto increment in MySQL by 5, starting at 10:

drop table foobar
create table foobar(
  id             INT PRIMARY KEY AUTO_INCREMENT,
  moobar         VARCHAR(500)
); 
SET @@auto_increment_increment=5;
ALTER TABLE foobar AUTO_INCREMENT=10;

INSERT INTO foobar(moobar) values ("abc");
INSERT INTO foobar(moobar) values ("def");
INSERT INTO foobar(moobar) values ("xyz");

select * from foobar;
'11', 'abc'
'16', 'def'
'21', 'xyz'

This auto increments the id column by 5 each time, starting at 10.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
8

You can also do it using phpmyadmin. Just select the table than go to actions. And change the Auto increment below table options. Don't forget to click on start Auto increment in phpmyadmin

North-Wind
  • 156
  • 1
  • 12
6

Procedure to auto fix AUTO_INCREMENT value of table

DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(64))
BEGIN
    DECLARE _max_stmt VARCHAR(1024);
    DECLARE _stmt VARCHAR(1024);    
    SET @inc := 0;

    SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(`id`), 0) + 1 INTO @inc FROM ', _table);
    PREPARE _max_stmt FROM @MAX_SQL;
    EXECUTE _max_stmt;
    DEALLOCATE PREPARE _max_stmt;

    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', @inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
    DEALLOCATE PREPARE _stmt;
END//
DELIMITER ;

CALL update_auto_increment('your_table_name')
3

If you need this procedure for variable fieldnames instead of id this might be helpful:

DROP PROCEDURE IF EXISTS update_auto_increment;
DELIMITER //
CREATE PROCEDURE update_auto_increment (_table VARCHAR(128), _fieldname VARCHAR(128))
BEGIN
    DECLARE _max_stmt VARCHAR(1024);
    DECLARE _stmt VARCHAR(1024);    
    SET @inc := 0;

    SET @MAX_SQL := CONCAT('SELECT IFNULL(MAX(',_fieldname,'), 0) + 1 INTO @inc FROM ', _table);
    PREPARE _max_stmt FROM @MAX_SQL;
    EXECUTE _max_stmt;
    DEALLOCATE PREPARE _max_stmt;

    SET @SQL := CONCAT('ALTER TABLE ', _table, ' AUTO_INCREMENT =  ', @inc);
    PREPARE _stmt FROM @SQL;
    EXECUTE _stmt;
    DEALLOCATE PREPARE _stmt;
END //
DELIMITER ;

CALL update_auto_increment('your_table_name', 'autoincrement_fieldname');
Thomas K.
  • 25
  • 4
0

My case.

DELIMITER //

DROP PROCEDURE IF EXISTS fix_id;
CREATE PROCEDURE fix_id()
BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE tableName VARCHAR(255);
    DECLARE cur CURSOR FOR SELECT table_name FROM information_schema.tables WHERE table_schema = 'db'; -- database_name
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    OPEN cur;

    read_loop: LOOP
        FETCH cur INTO tableName;
        SELECT tableName AS '** DEBUG:';

        IF done THEN
            LEAVE read_loop;
        END IF;

        SET @COUNT = 0;
        SET @sql = CONCAT('UPDATE ', tableName, ' SET id = @COUNT:=@COUNT+1;');
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

        SET @T = NULL;
        SET @sql = CONCAT('SELECT MAX(id) INTO @T FROM ', tableName, ';');
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

        SET @sql = CONCAT('ALTER TABLE ', tableName, ' AUTO_INCREMENT = ', IFNULL(@T, 0) + 1);
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

    END LOOP read_loop;

    CLOSE cur;
END;
//

DELIMITER ;

-- CALL fix_id()
seunggabi
  • 1,699
  • 12
  • 12
-3

just export the table with data .. then copy its sql like

CREATE TABLE IF NOT EXISTS `employees` (
  `emp_badgenumber` int(20) NOT NULL AUTO_INCREMENT,
  `emp_fullname` varchar(100) NOT NULL,
  `emp_father_name` varchar(30) NOT NULL,
  `emp_mobile` varchar(20) DEFAULT NULL,
  `emp_cnic` varchar(20) DEFAULT NULL,
  `emp_gender` varchar(10) NOT NULL,
  `emp_is_deleted` tinyint(4) DEFAULT '0',
  `emp_registration_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `emp_overtime_allowed` tinyint(4) DEFAULT '1',
  PRIMARY KEY (`emp_badgenumber`),
  UNIQUE KEY `bagdenumber` (`emp_badgenumber`),
  KEY `emp_badgenumber` (`emp_badgenumber`),
  KEY `emp_badgenumber_2` (`emp_badgenumber`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=111121326 ;

now change auto increment value and execute sql.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156