Understanding the Behavior of the AUTO_INCREMENT Column in MySQL

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:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved