MySQL auto-increment ID starts from 1 by default, how to set auto-increment ID to start from 0

    MySQL is a relational database, and it is one of the most popular relational databases in the world. In MySQL, auto-increment is a very useful function, which can automatically assign values ​​to primary keys and ensure that each primary key is unique. However, what many people don't know is that MySQL increments from 1 by default, which is not always suitable for all situations.

    In MySQL, we can change the initial value of auto-increment by explicitly specifying the auto-increment start value and step size when creating the table. For example:

CREATE TABLE example (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50)
) AUTO_INCREMENT=1000;

    In the example above, we explicitly set the auto-increment initial value to 1000. This means that when inserting the first record into the example table, the value of id will be 1000 instead of the default value of 1.

    Similarly, when changing the step size, we can do this:

CREATE TABLE example (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(50)
) AUTO_INCREMENT=1 INCREMENT BY 2;

    In the example above, we changed the step size to 2. This means that when the first record is inserted into the example table, the value of id will be 1, the second record will be 3, the third record will be 5, and so on.

    If you want to set the value of auto-increment id to start from 0, you can also set "AUTO_INCREMENT=0".

CREATE TABLE test_table (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
data VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=0;

    In short, MySQL's self-increment feature is very useful, it can automatically generate a unique primary key for us. However, in some cases, we may need to change the default values ​​of 1 for the auto-increment initial value and step size. Therefore, we only need to specify it explicitly when creating the table.

Guess you like

Origin blog.csdn.net/crazestone0614/article/details/132320899