How to Get Last Inserted ID from MySQL?
Last Updated :
28 Apr, 2025
In the world of Java programming and MySQL database management systems, you might be querying your MySQL database using a JDBC connection. In this article, we will look at fetching the latest ID after an insertion. Using Java's java.sql package, we will look at some examples of how to access the last inserted ID from MySQL.
In these examples, we'll learn how to smoothly retrieve the last inserted ID in Java applications, improving data management. Using Java's java.sql package, these techniques empower developers to optimize interactions with MySQL databases efficiently.
How to get the Last Inserted ID from MySQL in Java using java.sql
When any MySQL table includes an AUTO_INCREMENT column, MySQL generates the ID automatically. Here, we want to know the value of the AUTOINCREMENT column for the last INSERT statement executed. To get the last inserted ID from MySQL using Java, you create the JDBC connection and use conn.prepareStatement() method to which you must pass an additional parameter Statement.RETURN_GENERATED_KEYS.
Syntax:
<conn_obj>.prepareStatement(<sql-query>, Statement.RETURN_GENERATED_KEYS);
Parameters:
<sql-query>: An SQL query in string datatype.
Statement.RETURN_GENERATED_KEYS: A parameter to indicate that query returns id of last inserted record.
Returns:
An object of PreparedStatement class
NOTE: We can only get the last inserted id of the record for the tables from MySQL that contain an `id` column, which is of auto-increment type. The last inserted ID is not changed even if you run the UPDATE query to any column of that table.
Java.sql and JDBC
Java Database Connectivity (JDBC) is a standard Java API for interacting with relational databases. The java.sql package, part of the Java Standard Edition (SE), provides classes and interfaces to facilitate database operations.
Example 1: The table contains an `id` column, which is of auto-increment type
Let us assume that we have a database named "GFG" in which we have a table named "users". The schema for the table "users" is as follows:
CREATE TABLE users
(
id int AUTO_INCREMENT PRIMARY KEY,
name varchar(255) not null,
email varchar(255) not null,
age int not null
);
Now, we will insert two records into this table. The Java code below establishes a JDBC connection using connection parameters like username, password, database URL, and database name. The code contains an `InsertRecord()` method, which takes the JDBC connection object and the values for the insert query. The `InsertRecord()` method creates a PreparedStatement object and executes the query. To get the id of the last inserted record, it extracts the generatedKeys() from the executed query and returns the id.
Code:
Java
// importing required packages
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class GFG {
// database connection paramaters
private static final String DATABASE_URL
= "localhost:3306";
private static final String DATABASE = "gfg";
private static final String USERNAME = "root";
private static final String PASSWORD = "123";
// a function to insert record into MySQL database
// it returns the last inserted id for the record
public static int InsertRecord(Connection conn,
String name,
String email, int age)
throws SQLException
{
int id = 0;
String query
= "INSERT INTO users(name, email, age) values(?,?,?)";
// create a PreparedStatement object
PreparedStatement ps = conn.prepareStatement(
query, Statement.RETURN_GENERATED_KEYS);
// set the query paramaters/values
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, Integer.toString(age));
// execute the insert query
ps.executeUpdate();
// get the auto-generated keys
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
id = rs.getInt(1);
}
return id;
}
public static void main(String[] args)
{
try {
// create a connection object
Connection conn = DriverManager.getConnection(
"jdbc:mysql://" + DATABASE_URL + "/"
+ DATABASE,
USERNAME, PASSWORD);
// insert 1st record into table
int lastInsertedId1 = InsertRecord(
conn, "Girish", "[email protected]",
24);
// print the id of this 1st record inserted into
// table
System.out.println(
"Last Inserted Record Id was : "
+ lastInsertedId1);
// insert 2nd record into table
int lastInsertedId2 = InsertRecord(
conn, "Medha", "[email protected]",
23);
// print the id of this 2nd record inserted into
// table
System.out.println(
"Last Inserted Record Id was : "
+ lastInsertedId2);
conn.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
Last Inserted Record Id was : 1
Last Inserted Record Id was : 2
Output:
output of the program the when table contains auto increment columnData inserted using JDBC:
data inserted using JDBCExample 2: The table DOES NOT contain an `id` column, which is of auto-increment type
CREATE TABLE users
(
name varchar(255) not null,
email varchar(255) not null PRIMARY KEY,
age int not null
);
Again, we use the same code mentioned in the example above, but this time, we won't get the last inserted id for any record inserted into the `users` table since, now there is no AUTOINCREMENT type column in `users` table.
Last Inserted Record Id was : 0
Last Inserted Record Id was : 0
Output:
output of the program when table does not contain auto increment columnData inserted using JDBC:
data inserted using JDBCConclusion
Mastering the retrieval of the last inserted ID in MySQL with Java's java.sql package opens doors to enhanced database management. By following the steps outlined in this article, you can use them in your applications with this efficient approach to handling and utilizing newly inserted data.
As developers continue to optimize database interactions, the seamless retrieval of last-inserted IDs becomes a cornerstone, allowing for agile and precise management of data in Java applications. In the dynamic landscape of software development, these skills contribute to creating more resilient and efficient systems, ultimately enhancing the user experience.
Similar Reads
How to Get the Insert ID in SQL? When working with SQL databases, obtaining the insert ID (the auto-incremented primary key value) after inserting a new record is crucial for managing data relationships and ensuring seamless data referencing. In SQL databases, obtaining the insert ID after adding a new record to a table is a common
4 min read
How To Get Last Record In Each Group In MySQL? In MySQL, we group the data using the GROUP BY clause. There can be a need to access these groups and get the latest record in each group, for example, tracking the last login timestamp for each user. Knowing how to retrieve the latest record from a group is essential, as it is used in many practica
4 min read
How to Get the Identity of an Inserted Row in SQL In databases, Sometimes we need the identity of an inserted row in SQL. The identity value of the newly inserted row is very useful for various purposes in the database. In SQL, the RETURNING INTO clause within an INSERT statement enables retrieval of the inserted row's identity. When working with S
4 min read
How to get ID of the last updated row in MySQL? Many times, we require updating the data based on the last updated table id. We should write an update query in such a way that we can get the last updated ID in the update statement itself The code mentioned below has been created in a generalized sense and can be used easily just by replacing the
2 min read
How to Create id with AUTO_INCREMENT in MySQL? 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 databa
5 min read