If I have a table like this:
CREATE TABLE mytable
(
id SERIAL,
content TEXT,
copyofid INTEGER
);
Is there a way to copy id
into copyofid
in a single insert statement?
I tried:
INSERT INTO mytable(content, copyofid) VALUES("test", id);
But that doesn’t seem to work.
2
Answers
You can find the sequence behind your serial column using
pg_get_serial_sequence()
and access it usingcurrval()
to get what serial column just got as a result of yourINSERT
.Fiddle
Edouard makes makes a fair point that if you can specify the conditions when you want this behaviour, you can add them to the definition:
If they vary between inserts
The trigger will be better if
STABLE
are acceptedinsert
you’ll want to do more than just copy the id columnThe solution is to create a trigger function which is fired before inserting a new row in table mytable and which copy NEW.id into NEW.copyofid if a condition is true :
The condition can also be stated directly in the
WHEN
clause of the trigger instead of in the function :see the manual