Postgresql – Postgres create an insert return rule

postgresqlpostgresql-9.3

I am failing to create a rule which will return the insert's data.

The table is:

CREATE TABLE foo(a int, b text);

My attempt for the rule is:

CREATE RULE return_data AS ON INSERT TO foo DO RETURN *;

Best Answer

RETURN isn't a valid command in a rule definition; you can only use SELECT, INSERT, UPDATE, DELETE, and NOTIFY.

You can create an ALSO rule to return the value of the new row, something like this:

> CREATE RULE return_data AS ON INSERT TO FOO DO ALSO SELECT NEW.*;
CREATE RULE

> INSERT INTO foo VALUES (1, 'test');
 a |  b
---+------
 1 | test
(1 row)

INSERT 0 1

Note that you can do something identical by just adding the RETURNING clause to the INSERT statement:

> INSERT INTO foo VALUES (2, 'test 123') RETURNING *;
 a |    b
---+----------
 2 | test 123
(1 row)


INSERT 0 1