How to set initial value and auto increment in MySQL?


The AUTO_INCREMENT attribute is used to generate a unique identify for new rows. If a column is declared as ‘NOT NULL’, it is possible to assign NULL to that column to generate a sequence of numbers.

When any value is inserted into an AUTO_INCREMENT column, the column gets set to that value, and the sequence also gets reset so that it generates values automatically, in the sequential range from largest column value.

An existing ‘AUTO_INCREMENT’ column can be updated that will reset the ‘AUTO_INCREMENT’ sequence as well. The most recent auto-generated ‘AUTO_INCREMENT; value can be retrieved using the ‘LAST_INSERT_ID()’ function in SQL or using the ‘mysql_insert_id()’ which is a C API function.

These functions are connection-specific, which means their return values are not affected by other connections which perform the insert operations. The smallest integer data type for ‘AUTO_INCREMENT’ column can be used, which would be large enough to hold the maximum sequence value which is required by the user.

Rules for AUTO_INCREMENT

The following rules need to be followed while using the AUTO_INCREMENT attribute −

  • Every table has only one AUTO_INCREMENT column whose data type would be an integer typically.

  • The AUTO_INCREMENT column needs to be indexed. This means it can either be a PRIMARY KEY or a UNIQUE index.

  • The AUTO_INCREMENT column must have a NOT NULL constraint on it.

  • When the AUTO_INCREMENT attribute is set to a column, MySQL automatically adds the NOT NULL constraint to the column on its own.

If an id column hasn’t been added to the table, the below statement can be used −

ALTER TABLE tableName ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT, ADD INDEX (id);

If an id column is already present, then the below command can be used −

ALTER TABLE tableName AUTO_INCREMENT=specificValue;

Here, tableName refers to the name of the table fr which the ‘AUTO_INCREMENT’ column needs to be set. The ‘specificValue’ refers to an integer from where the ‘AUTO_INCREMENT’ values are specified by the user to begin.

Updated on: 09-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements