Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a value from the last inserted row? [duplicate]

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.

like image 877
eflles Avatar asked Oct 27 '08 18:10

eflles


People also ask

How do I select the last inserted row in SQL?

If you are AUTO_INCREMENT with column, then you can use last_insert_id() method. This method gets the ID of the last inserted record in MySQL. Insert some records in the table using insert command.

How do I get the unique ID for the last inserted row?

9 Obtaining the Unique ID for the Last Inserted Row. If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id() function.

How do I get last inserted data?

you can get the id if you call LAST_INSERT_ID() function immediately after insertion and then you can use it. Show activity on this post. For any last inserted record will be get through mysql_insert_id() If your table contain any AUTO_INCREMENT column it will return that Value.

How can I get recently inserted rows in MySQL?

Use the LAST_INSERT_ID() Function to Get the ID of the Last Inserted Row in MySQL. The LAST INSERT ID() function can be used to get the ID of the last inserted or updated record (row) when using the INSERT or UPDATE command on a table with the AUTO INCREMENT field.


1 Answers

With PostgreSQL you can do it via the RETURNING keyword:

PostgresSQL - RETURNING

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"); rs.next(); rs.getInt(1); 
like image 156
Luc M Avatar answered Sep 19 '22 18:09

Luc M