Learning the RETURNING clause for INSERT
In PostgreSQL, we can add the RETURNING
keyword to the insert
statement. The RETURNING
keyword in PostgreSQL provides an opportunity to return the values of any columns from an insert
or update
statement after the insert or update was run. For example, if we want to return all the fields of the record that we have just inserted, we have to perform a query as follows:
forumdb=> insert into j_posts_tags (tag_pk,post_pk) values(1,3) returning *;
tag_pk | post_pk
--------+---------
1 | 3
(1 row)
INSERT 0 1
The *
means that we want to return all the fields of the record that we have just inserted; if we want to return only some fields, we have to specify what fields the query has to return:
forumdb=> insert into j_posts_tags (tag_pk,post_pk) values(1,2) returning tag_pk;
tag_pk
--------
1
(1 row)
INSERT 0 1
This feature will show itself to be particularly useful at the end of the chapter when we talk about...