312

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?

2
  • you can't CHANGE, only increase Feb 23, 2019 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 If there is no higher value than what you want to set your auto_incremented column, you can also decrease the value. (mysql documentation)
    – seyfahni
    Nov 20, 2019 at 16:41

8 Answers 8

612

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.

8
  • 6
    Anyone know if it is possible to do WITHOUT an ALTER?
    – thesmart
    Jul 23, 2012 at 22:15
  • 3
    Yes, it's possible. See my reply.
    – Cosimo
    Sep 13, 2012 at 7:03
  • 3
    MySQL 5.6 had a bug that wouldn't allow you to decrease the AUTO_INCREMENT value, but it has been fixed in 5.6.16 and 5.7.4, see bugs.mysql.com/bug.php?id=69882 Apr 9, 2014 at 14:35
  • 3
    Take a look at cosimo's warning about the table being rebuilt if you do this!
    – h00ligan
    Dec 5, 2014 at 14:05
  • 26
    To clarify: Setting the initial value to 5, means that the next insert will be 5. May 2, 2016 at 6:57
114

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 ...
8
  • 6
    THANKS! SET foreign_key_checks = 0; is also useful for this.
    – dnozay
    Mar 13, 2013 at 19:26
  • Brilliant idea! Nitpick: SHOW CREATE TABLE t will actually return 43, i.e. next value after inserting 42.
    – petrkotek
    May 27, 2014 at 6: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 3, 2015 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 6, 2015 at 9: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 8, 2015 at 15:45
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.

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

2
  • The menu item is now called Operations.
    – kiatng
    Jun 30, 2022 at 0:43
  • But you should understand that phpmyadmin will execute ALTER TABLE
    – Demiurg
    May 31 at 5:53
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');
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()
-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.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.