Several solutions for running out of MySQL auto-increment IDs

After MySQL's auto-increment ID (AUTO_INCREMENT) is used up, there will be a problem of duplicate IDs, so how to solve this problem?

There are mainly the following solutions:

1. Change the table structure and expand the ID field type to extend the ID field type from int to bigint, so that it can support up to 9.2 x 10 to the 18th power, and basically there will be no running out.

For example:

ALTER TABLE `table_name` 
CHANGE `id` `id` BIGINT(20) NOT NULL AUTO_INCREMENT;

2. Modify the initial value and step size of AUTO_INCREMENT We can specify the initial value and step size of AUTO_INCREMENT when initializing the database table to avoid running out of IDs.

For example:

CREATE TABLE `table_name` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    ......
)AUTO_INCREMENT = 100  STEP = 2; 

This will make the id start at 100 and increment by 2.

3. Generate a random ID We can give up AUTO_INCREMENT and use the UUID() function to generate a random ID.

For example:

id VARCHAR(36) NOT NULL DEFAULT UUID();  

The ID generated by UUID() is unique, and basically there will be no duplication.

4. Using the sub-database and sub-table scheme, we can point different ID segments to the same table in different database instances to avoid the problem of running out of single-table IDs. Database routing can determine which database instance it is stored in based on the value of the ID. This requires the implementation of database sharding logic at the application layer, and the application decides which database instance to store new data in.

5. Regularly clean up unused IDs We can regularly clean up those IDs that have been used but are no longer used, and release them for new data. This requires us to carefully judge that those IDs will no longer be used at the business layer. For example, we can periodically clean up user IDs after users are deleted so that new users can reuse those IDs.

In short, running out of auto-increment IDs in MySQL is an unavoidable problem. We must take this problem into account in application design and take corresponding solutions. Choosing which solution needs to comprehensively consider various factors such as cost, sequel compatibility, and system architecture. Hope the above solution can help you.

write at the end

If you are interested in related articles, you can pay attention to the official account "Architecture Palace", and will continue to update AIGC, java basic interview questions, netty, spring boot, spring cloud and other series of articles, and a series of dry goods will be delivered at any time!

Guess you like

Origin blog.csdn.net/jinxinxin1314/article/details/130761809