Retrieving Auto-Generated Keys
Fast recall
Quick revision
Core answer
Whether you know the RETURN_GENERATED_KEYS + getGeneratedKeys flow.
Re-querying with a SELECT to find the new id instead of using getGeneratedKeys.
Note you must opt in at prepare time and the key comes back as a ResultSet.
Interview-ready guide
Interview answer
Connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS) asks the driver to make keys available. After executeUpdate, try (ResultSet keys = ps.getGeneratedKeys()) { if (keys.next()) id = keys.getLong(1); }. That common pattern works with many identity columns, but it is not an unconditional JDBC promise that every generated value or batch key is returned. Verify driver support and column ordering.
For example, after INSERT INTO customer(name) VALUES (?) I request RETURN_GENERATED_KEYS, execute the statement, call keys.next(), and read keys.getLong(1). Driver support and multi-row key behavior must be verified.
Retrieving Auto-Generated Keys
Direct Answer
Request generated keys when creating the PreparedStatement, execute the insert, then read the ResultSet from getGeneratedKeys. The capability and returned columns are driver/database dependent; check DatabaseMetaData.supportsGetGeneratedKeys and vendor documentation. Some databases work better with SQL such as INSERT ... RETURNING or with explicit key column names.
Code Example
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (PreparedStatement ps =
con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { // opt in
ps.setString(1, "Ravi");
ps.setString(2, "ravi@x.com");
ps.executeUpdate();
try (ResultSet keys = ps.getGeneratedKeys()) {
if (keys.next()) {
long newId = keys.getLong(1); // the auto-generated PK
System.out.println("new id: " + newId);
}
}
}
Common Mistakes & Pitfalls
- Forgetting
RETURN_GENERATED_KEYS:getGeneratedKeys()returns nothing without it. SELECT MAX(id)after insert: racy under concurrency — may return another session's id.- Not calling
keys.next(): the keys come back as a ResultSet you must advance. - Assuming column name: read by index
getLong(1)(key column naming varies).
Check your understanding
Answer these without looking back at the article.
- Why is SELECT MAX(id) unreliable for getting the new id?
- Do you need RETURN_GENERATED_KEYS at prepare time?
- How do you read the generated key from the ResultSet?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.