Understanding the Behavior of the AUTO_INCREMENT Column in MySQL

Most of us are familiar with AUTO_INCREMENT, and have used it in at least one context. However, the following behavior is a little tricky, especially when we fail to observe — and most of the time it is not reproducible due to the behavior or MySQL.

Consider the table that is created as below.

CREATE TABLE EMPLOYEE (EMP_ID INT PRIMARY KEY AUTO_INCREMENT,FIRST_NAME VARCHAR(25),LAST_NAME VARCHAR(30));

Observe that the column EMP_ID has the property to AUTO_INCREMENT.

Now, execute the following:

INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME) VALUES('Lope','Dey');

A record has been inserted with EMP_ID as 1.

Now use and UPDATE statement and set the value of 1 to 2. Essentially, you are trying to understand the way MySQL will work with this value.

Now, execute the following:

INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME) VALUES('Rina','Well');

We get an error indicating that there is a duplicate entry for the key PRIMARY.

Now, execute the following again and the error does not show up anymore.

INSERT INTO EMPLOYEE(FIRST_NAME, LAST_NAME) VALUES('Rina','Well');

The AUTO_INCREMENT value has been further incremented and a new number, i.e., 3 is now used and the record gets inserted successfully.

This is a good thing as well. But in case of errors observed, you may not be able to reproduce it. Be careful with UPDATES on AUTO_INCREMENT column values.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a