Is there a way to insert a group of items that are dependent but consistent between them with unique primary keys and foreign keys but that are colliding with items in database.

For example, given a table A:

id  primary key,

and a table B:

 id primary key,
 id_a'  -- foreign key on A

I want to insert:

INSERT INTO A(id, name) VALUES (1, "a");
INSERT INTO B(id, name, id_a) VALUES (1, "b", 1);

But the keys A.id or B.id could be taken already. Is there a way to insert my elements with auto setting key and foreign keys in a consistent way without colliding with existing elements?

  • Does this answer your question?: dba.stackexchange.com/questions/3281/… Commented Nov 4, 2013 at 16:58
  • It won't help if there is several elements A and B. Edit : maybe with variables
    – hokkos
    Commented Nov 4, 2013 at 17:03
  • 2
    If you want to insert multiple rows in both tables, you can modify @Erwin's answer here: How do I insert a row which contains a foreign key? Commented Nov 4, 2013 at 17:05
  • The paragraph titled INSERT new FK rows at the same time has a statement that uses table structure identical to yours. Commented Nov 4, 2013 at 17:15
  • The problem is that I have tables C, D, E, ... with foreign keys between them, I am not sure writing functions for cascading creation is scalable with 40 tables.
    – hokkos
    Commented Nov 4, 2013 at 17:30

1 Answer 1


In reference to your comment, CTEs are scalable that way. You should do everything in a single transaction anyway. The related question @ypercube suggested should fit your case exactly:
How do I insert a row which contains a foreign key?

Your other option would be to employ lastval() and curval() to identify values most recently obtained from sequences. Not providing code, your question is too vague. These related questions on SO may be helpful:
Reference value of serial column in another column during same INSERT
PostgreSQL next value of the sequences?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.