This is a two-part question. Attached is a diagram for a PostgreSQL database table design. There are four tables. Table Main
has a one-to-many relationship wi
Answer to Q1: Use data-modifying CTEs and return the serial PK with the RETURNING
clause:
WITH ins_main AS (
INSERT INTO main(col1)
VALUES ('some value 1')
RETURNING main_id
)
, ins_submain AS (
INSERT INTO submain (main_id, col2)
SELECT main_id, 'some value 2'
FROM ins_main
RETURNING submain_id
)
INSERT INTO subsub (submain_id, col3)
SELECT submain_id, 'some value 3'
FROM ins_submain;
Requires Postgres 9.1 or later.
Related answers with explanation and links: