How to get an ID of the inserted row in Postgres with Java JDBC

Posted on 17-05-2013 17:09 by graham
This tutorial should you how to insert a new row into a database table and get the ID of the newly inserted record in the same transaction.

The use of RETURNING keyword

The RETURNING keyword in Postgres returns a value of any field after an insert.
INSERT INTO users (name) VALUES ('John') RETURNING id

To call this statement with JDBC, you can do the following:
Integer newId = new JdbcTemplate(dataSource).queryForLong("INSERT INTO users (name) VALUES ('John') RETURNING id");


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems