Skip to lesson

Getting generated keys after INSERT

After saving a customer you want to say "your customer number is 42", but the id did not exist until the row was saved. The database picks it, so the program has to ask for it.

Why the program needs the new id

AUTO_INCREMENT is a column setting that makes MySQL pick the next whole number as the id of every new row. That id exists only after the row is saved, and it is called the generated key.

A products row has product_id INT AUTO_INCREMENT, so you send no id on INSERT: the database picks the next one. Yet the program needs it at once, for example as the order_id of each new order item.

Four steps. 1: the program sends INSERT INTO orders without an id. 2: MySQL saves the row and picks order_id 17 with AUTO_INCREMENT. 3: getGeneratedKeys returns 17 to the program. 4: the program inserts an order item that stores order_id 17 as its foreign key.

Asking for the keys on prepare

Statement.RETURN_GENERATED_KEYS is a flag passed to prepareStatement so the driver keeps the ids that an INSERT creates and getGeneratedKeys() can return them.

By default an INSERT does not return its new id. Ask for it when you prepare: con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS). Example 1 saves a category and prints its id.

Example 1 · Reading the new category id

Runs in: a Maven project with the MySQL driver and the ShopLite database

NewCategoryId.javaJava
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 NewCategoryId {    static int addCategory(Connection con, String name) throws SQLException {        String sql = "INSERT INTO categories (name) VALUES (?)";        try (PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {            ps.setString(1, name);            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                return keys.getInt(1);            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            con.setAutoCommit(false);            int id = addCategory(con, "Sports");            System.out.println("New category saved with id " + id);            con.rollback();        }    }}
Sample output
New category saved with id 8

What this code does

  • RETURN_GENERATED_KEYS on prepare tells the driver to keep the new id. After executeUpdate, getGeneratedKeys returns it.
  • The exact number depends on how many categories already exist, so your run may show a different id. The rollback keeps the practice data unchanged.

Without the flag, Connector/J's getGeneratedKeys() throws SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS ....

Fix the error

Fix the missing id

Read the error, then pick the line that fixes it.

Round 1 of 2

Pick the line that replaces line 2 so the id can be read.

String sql = "INSERT INTO categories (name) VALUES (?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "Garden");
ps.executeUpdate();
ResultSet keys = ps.getGeneratedKeys();

Error

java.sql.SQLException: Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate(), Statement.executeLargeUpdate() or Connection.prepareStatement().
Only an INSERT into a table with an AUTO_INCREMENT column produces a key. An UPDATE or a plain INSERT without such a column returns none.

Reading getGeneratedKeys()

getGeneratedKeys() is a PreparedStatement method that returns a small ResultSet with one row for each inserted row. The new id is in its first column.

After executeUpdate(), call getGeneratedKeys(). For a single-row INSERT, move to the row with keys.next() and read the id with keys.getInt(1).

Java
ps.executeUpdate();try (ResultSet keys = ps.getGeneratedKeys()) {    if (keys.next()) {        int newId = keys.getInt(1);   // the first column holds the new id    }}

Close that ResultSet like any other, with try-with-resources. For an INSERT of several rows, loop with while (keys.next()).

Returning the saved record with its id

A clean save method builds the object with its new id and returns it, so the caller gets the whole record. Example 2 saves a customer and returns a Customer record that carries the id.

Example 2 · Returning the saved customer record

Runs in: a Maven project with the MySQL driver and the ShopLite database

SavedCustomer.javaJava
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 SavedCustomer {    record Customer(int id, String name, String email) { }
    static Customer addCustomer(Connection con, String name, String email) throws SQLException {        String sql = "INSERT INTO customers (full_name, email) VALUES (?, ?)";        try (PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {            ps.setString(1, name);            ps.setString(2, email);            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                return new Customer(keys.getInt(1), name, email);            }        }    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            con.setAutoCommit(false);            Customer saved = addCustomer(con, "Neha Gupta", "neha.gupta@example.com");            System.out.println("Saved: " + saved);            con.rollback();        }    }}
Sample output
Saved: Customer[id=9, name=Neha Gupta, email=neha.gupta@example.com]

What this code does

  • The method reads the generated key and builds a Customer record that carries the new id, so the caller gets the whole record back.
  • The id, 9 here, is whatever the database assigned; it will differ on your database.

This way the id lives in one object, not in a loose int the caller has to track.

A child row using the new id

An order has a new order_id, and each order item stores it as a foreign key. Example 3 inserts the order, reads its id, then inserts the item with that id.

Example 3 · An order and its first item

Runs in: a Maven project with the MySQL driver and the ShopLite database

OrderWithItem.javaJava
import java.math.BigDecimal;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.time.LocalDateTime;
public class OrderWithItem {    static int placeOrder(Connection con, int customerId, int addressId,                          int productId, int qty, BigDecimal price) throws SQLException {        int orderId;        String orderSql = "INSERT INTO orders (customer_id, address_id, status, ordered_at)"                + " VALUES (?, ?, 'PLACED', ?)";        try (PreparedStatement ps = con.prepareStatement(orderSql, Statement.RETURN_GENERATED_KEYS)) {            ps.setInt(1, customerId);            ps.setInt(2, addressId);            ps.setObject(3, LocalDateTime.of(2026, 10, 16, 9, 0));            ps.executeUpdate();            try (ResultSet keys = ps.getGeneratedKeys()) {                keys.next();                orderId = keys.getInt(1);            }        }        String itemSql = "INSERT INTO order_items (order_id, product_id, quantity, unit_price)"                + " VALUES (?, ?, ?, ?)";        try (PreparedStatement ps = con.prepareStatement(itemSql)) {            ps.setInt(1, orderId);            ps.setInt(2, productId);            ps.setInt(3, qty);            ps.setBigDecimal(4, price);            ps.executeUpdate();        }        return orderId;    }
    public static void main(String[] args) throws SQLException {        try (Connection con = DriverManager.getConnection(                System.getenv("DB_URL"), System.getenv("DB_USER"), System.getenv("DB_PASSWORD"))) {            con.setAutoCommit(false);            int orderId = placeOrder(con, 1, 1, 1, 2, new BigDecimal("17999.00"));            System.out.println("Order " + orderId + " placed with its first item");            con.rollback();        }    }}
Sample output
Order 17 placed with its first item

What this code does

  • The order INSERT uses RETURN_GENERATED_KEYS, so orderId holds the new id. The item INSERT then stores that order_id.
  • Both rows are saved on one connection with auto-commit off; the rollback undoes them. Later lessons make such a save a single transaction.

The next lesson on batch inserts and the later transactions lesson show how to save many items at once and keep the whole thing all-or-nothing.

Next step

Check your understanding

10 quick questions