Simple one-to-many database insertions in PostgreSQL
It’s quite often the case that in a normalized database there is a one-to-many relation that are being populated in a following fashin: loop: - one insert to “one” relation - multiple inserts to “many” relations.
We want to use autoincremented types like SERIAL for IDs linking these two relations and avoid unnecessary queries.
create table one( one_id serial primary_key, something….); create table many(many-id serial primary key, one_id references one(one_id) default currval(’one_one_id_seq’), something…);
And inserting like these: insert into one(something) values (some_values); insert into many(something) values(some_values1); insert into many(something) values(some_values2); …
If there is no string one-one, many-many pattern, you can still get the last value of the sequence by calling select currval(’one_one_id_seq’); and stroing it somewhere.
This works well in Postgres, but other databases have similar capabilities. BTW: currval() is stored per session, so there is no threat that the sequences get screwed with concurrent access.
May 23rd, 2007 at 9:53 pm
Can’t seem to find much on the web regarding this particular type of insert. Could you possibly help me with my insert if I post my table structure? Thanks, Andy