How to Create id with AUTO_INCREMENT in MySQL?
Last Updated :
03 Jul, 2024
Primary keys in databases uniquely identify each record, ensuring data integrity and efficient retrieval. AUTO_INCREMENT, a feature in MySQL, automatically assigns unique numeric identifiers to new rows, simplifying data management.
Understanding these concepts is crucial for designing robust database schemas that optimize data storage and retrieval. This introduction briefly covers the importance of primary keys, AUTO_INCREMENT functionality, and their relevance in database design.
Solutions for AUTO_INCREMENT IDs in MySQL
So we have some common solutions with some built-in functions and some with procedures(Triggers) that we will create. Let's first understand them.
- AUTO_INCREMENT: This is the built-in property used to solve the above issue. It will automatically add the new ID after the last one, and we don't have to give anything related to the primary key in the Insert statement.
- Trigger: This approach will require the understanding of triggers. It will trigger the procedure as soon as the insert query is run. We will create a Trigger which will run before actual insertion in the database so that we can count the id and then we can append the id by ourselves.
1. AUTO_INCREMENT with Create Statement
In this, we will look to Create a table and with it, we will mention the "AUTO_INCREMENT" As discussed it will manage the id by itself.
Syntax:
CREATE TABLE table_name (
id INT AUTO_INCREMENT PRIMARY KEY,
--Other columns
);
Example
CREATE TABLE AutoIncrement (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
age INT
);
Now insert some values into it to see whether the id is generating by itself
INSERT INTO AutoIncrement (name, age)
VALUES ("John", 20),
("Mark", 35),
("Johnson", 40);
Output:
id | name | age |
---|
1 | John | 20 |
2 | Mark | 35 |
3 | Johnson | 40 |
So we have not given the values for the id column but as we have set the column to AUTO_INCREMENT it will automatically assign the value according to the last value used for the table.
Now we will delete the row with id=3
to see if the table is recalculating the ID:
DELETE FROM AutoIncrement WHERE id = 3;
SELECT * FROM AutoIncrement;
Output:
Now add another row by using the below query and apply the select statement.
INSERT INTO AutoIncrement(name, age)
VALUES ("Watson",20);
SELECT * from AutoIncrement
Output:
id | name | age |
---|
1 | John | 20 |
2 | Mark | 35 |
4 | Watson | 20 |
So it is clear from the above query that AUTO_INCREMENT doesn't take the last ID from the database but it will take the ID based on the last inserted ID.
We can also change the AUTO_INCREMENT starting value other than 1 by using giving AUTO_INCREMENT = value property.
2. AUTO_INCREMENT with Alter Statement
Now let's say we have a table that was created without AUTO_INCREMENT
. We can use the ALTER
statement to add it.
Let's Create a table without AUTO_INCREMENT
CREATE TABLE AutoIncrementAlt (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);
Insert the Rows into it
INSERT INTO AutoIncrementAlt (id, name, age)
VALUES (1, "Watson", 20),
(2, "Mark", 35),
(4, "Johnson", 40);
SELECT * FROM AutoIncrementAlt;
Output:
id | name | age |
---|
1 | Watson | 20 |
2 | Mark | 35 |
4 | Johnson | 40 |
Now we will add AUTO_INCREMENT to this and remember if we give only AUTO_INCREMENT then it will start from 1 but here we want it to start from 5
ALTER TABLE AutoIncrementAlt
MODIFY COLUMN id INT AUTO_INCREMENT;
ALTER TABLE AutoIncrementAlt AUTO_INCREMENT = 5;
And now we can add rows
INSERT INTO AutoIncrementAlt (id, name, age)
VALUES (3, "JOHN", 20);
SELECT * FROM AutoIncrementAlt;
Output:
id | name | age |
---|
1 | Watson | 20 |
2 | Mark | 35 |
4 | Johnson | 40 |
5 | John | 20 |
By this, we can use AUTO_INCREMENT to achieve the auto-incrementing primary key.
3. Create AUTO_INCREMENT Id Without Trigger
so now we won't Auto_Increment with column. But we will mimic this behavior with triggers. The trigger will automatically be called when an insert query is applied.
First, let's create another table for better understanding.
CREATE TABLE AutoIncrementWithTrigger (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);
Now we will create a trigger which will be called Before Insert.
DELIMITER //
CREATE TRIGGER trg_before_insert
BEFORE INSERT ON AutoIncrementWithTrigger
FOR EACH ROW
BEGIN
DECLARE last_id INT;
SET last_id = (SELECT COALESCE(MAX(id), 0) FROM AutoIncrementWithTrigger);
SET NEW.id = last_id + 1;
END;
//
DELIMITER ;
Let's See what this trigger is doing.
- BEFORE INSERT: Mentions when the trigger should execute
- FOR EACH ROW: Tells to execute the trigger for all rows and not for the whole block
- COALESCE(MAX(id), 0): It will find the maximum id used in the table and if id is not assigned then it will give 0.
- NEW.id: last_id+1 - This will assign the incremented id to the newly added row.
Now we will insert the rows to look at the results.
INSERT INTO AutoIncrementWithTrigger (name, age)
VALUES ("John", 20),
("Mark", 35),
("Johnson", 40);
Output:
id | name | age |
---|
1 | John | 20 |
2 | Mark | 35 |
3 | Johnson | 40 |
By this, we can use AUTO_INCREMENT to achieve the auto-incrementing primary key. Thus we can use triggers to calculate the id and assign it to new records.
Conclusion
So, Using this approach we can create a column with auto increment. This helps when we want to create a record from our backend API or service. At that time we reduce our Database calls because we don't have to worry much about the last id. Also, it will remove the chances of any mismatch with the already present ID.
Similar Reads
SQL Interview Questions
Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Tutorial
SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS
In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
8 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
ACID Properties in DBMS
In the world of Database Management Systems (DBMS), transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliabilit
8 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read