sqlpostgresqltriggersprimary-keyentity-relationship

Insert inserted id to another table


Here's the scenario:

create table a (
 id serial primary key,
 val text
);

create table b (
 id serial primary key,
 a_id integer references a(id)
);

create rule a_inserted as on insert to a do also insert into b (a_id) values (new.id);

I'm trying to create a record in b referencing to a on insertion to a table. But what I get is that new.id is null, as it's automatically generated from a sequence. I also tried a trigger AFTER insert FOR EACH ROW, but result was the same. Any way to work this out?


Solution

  • Avoid rules, as they'll come back to bite you.

    Use an after trigger on table a that runs for each row. It should look something like this (untested):

    create function a_ins() returns trigger as $$
    begin
      insert into b (a_id) values (new.id);
      return null;
    end;
    $$ language plpgsql;
    
    create trigger a_ins after insert on a
    for each row execute procedure a_ins();