PostgreSQL "RETURNING"
Today I learned that PostgreSQL INSERT/UPDATE/DELETE has a RETURNING clause that returns the computed values.
We can use it to get values that are generated by database such as sequences or defaults.
Check this out:
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR NOT NULL UNIQUE
);
INSERT INTO users (email) VALUES ('user1@example.com');
-- INSERT 0 1
INSERT INTO users (email) VALUES ('user2@example.com') RETURNING *;
-- id | email
-- ----+-------------------
-- 2 | user2@example.com
-- (1 row)
h/t @joshuadavey
Tweet