eflles eflles - 1 year ago 94
Java Question

How to get a value from the last inserted row?

Is there some way to get a value from the last inserted row?

I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table.

I am using Java with a JDBC and PostgreSQL.

Answer Source

With PostgreSQL you can do it via the RETURNING keyword:


INSERT INTO mytable( field_1, field_2,... )
VALUES ( value_1, value_2 ) RETURNING anyfield

It will return the value of "anyfield". "anyfield" may be a sequence or not.

To use it with JDBC, do:

ResultSet rs = statement.executeQuery("INSERT ... RETURNING ID");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download