How does AUTO_INCREMENT work in MySQL?

AUTO_INCREMENT facilitates the automatic generation of a unique number when inserting a new record into a table. Typically, this is applied to the PRIMARY KEY field, ensuring its automatic creation for each new record insertion.

MySQL AUTO_INCREMENT

MySQL employs the AUTO_INCREMENT keyword to enable the auto-increment functionality. The default initial value for AUTO_INCREMENT is 1, and it increments by 1 for each new record.

In the Product table, the Pid column can be defined as an AUTO_INCREMENT PRIMARY KEY field using the following SQL statement:

CREATE TABLE Product (
Pid int NOT NULL AUTO_INCREMENT,
ProductName varchar(255) NOT NULL,
Quantity int,
Price int,
PRIMARY KEY (Pid)
);

When inserting data into the Product table, there is no need to specify the values for the Pid column.

Take a look at the following insert query:

INSERT INTO Product (ProductName,Quantity,Price)
VALUES ('Oats',10,200);
INSERT INTO Product (ProductName,Quantity,Price)
VALUES ('Soap',5,100);

Code example

To enhance our understanding of how AUTO_INCREMENT works, let’s execute the code below and observe the output:

#!/usr/bin/env bash

mkdir -p /var/run/mysqld
chmod 777 -R /var/run/mysqld
chown -R mysql:mysql /var/lib/mysql /var/run/mysqld

# check if mysql is running before restarting it

/usr/bin/mysqld_safe &

# wait for mysql to start up
echo "Please wait for 3 seconds ..."
sleep 3
mysql -u root -Bse "DROP DATABASE IF EXISTS MovieIndustry;"
clear
# Launch MySQL
mysql < mysql.sql

AUTO_INCREMENT example

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved