📜 ⬆️ ⬇️

Getting the id of the added entry in PostgeSQL

No matter how superfood you are, you’ve seen occasionally some interesting and convenient things that you’d think it’s time to know, but it didn’t add up. A sort of nishtyachok, finding who wants to exclaim: "Eureka!". This nishtyachkom for me was an element of the INSERT syntax in PostgreSQL, which I want to share with you.

Situation: After adding a record to the database, you need to get the id of this most freshly inserted record.
Solution on PostgreSQL: INSERT ... RETURNING id where id is PRIMARY_KEY in the table.

Simple and elegant, isn't it?

Detailed example:
')
postgres=# create table test (id serial,name text);
NOTICE: CREATE TABLE will create implicit sequence "test_id_seq" for serial column "test.id"
CREATE TABLE
postgres=# INSERT INTO test (name) VALUES ('My Name') RETURNING id;
id
----
1
postgres=# INSERT INTO test (name) VALUES ('My Name 1') RETURNING id;
id
----
2
(1 row)

Source: https://habr.com/ru/post/72590/


All Articles