WHOATEMYNOODLES
WHOATEMYNOODLES

Reputation: 2641

Using the newly created primary key in another column

Using PostgreSQL

in my table I have the column "id" that is an auto incremented primary key. When I create a new row, I would like to use that newly created primary key value in another column of the new row. How would I do so?

enter image description here

Upvotes: 0

Views: 204

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270713

You need a trigger for this:

create or replace function t_update_message_id_trigger()
returns trigger as
$body$
begin
    new.message_id := new.id;
    return new;
end;
$body$ language plpgsql;

create trigger t_update_message_id before insert on t
    for each row execute procedure t_update_message_id_trigger();

Here is a db<>fiddle, illustrating how it works.

Upvotes: 1

Related Questions