Search code examples
mysqlauto-increment

Why auto_incremnt column increment it value after insert statement failed


I am using MySQL. I create two new tables. After inserting a new row in Employees table , i deliberately try to insert a new row in Orders table whose reference not exist in Employees table(i know it'll produce error). After that when i try to insert a new row in Orders table whose reference exist in Employees table it executes successfully but now first row of Orders table has id of 2. Why it increases even when first insert statement fails

CREATE TABLE Employees
(
EmpID SMALLINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
EmpFN VARCHAR(20) NOT NULL 
)
ENGINE=INNODB;

CREATE TABLE Orders
(
OrderID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,   
EmpID SMALLINT NOT NULL,
FOREIGN KEY (EmpID) REFERENCES Employees (EmpID)
)
ENGINE=INNODB;

Solution

  • AUTO_INCREMENT guarantees only that the next value will be bigger than the previous, but it does not guarantee that there will be no gap in the numbers.

    There is performance reason behind this. There is a hidden counter behind the AUTO_INCREMENT, which stores the actual value. This way the sequence does not have the transactional overhead what can be considerable in a distributed transactional environment. Besides the db can prefetch more values from the disk at once into its memory, what significantly lowers the required disk io.