0

I need to insert a row into one table and use this row's id to insert two more rows into a different table within one transaction. I've tried this

begin;
insert into table default values returning table.id as C;
insert into table1(table1_id, column1) values (C, 1);
insert into table1(table1_id, column1) values (C, 2);
commit;

But it doesn't work. How can I fix it?

updated

2 Answers 2

1

You need a CTE, and you don't need a begin/commit to do it in one transaction:

WITH inserted AS (
    INSERT INTO ... RETURNING id
)
INSERT INTO other_table (id)
SELECT id
FROM inserted;

Edit: To insert two rows into a single table using that id, you could do that two ways:

  • two separate INSERT statements, one in the CTE and one in the "main" part
  • a single INSERT which joins on a list of values; a row will be inserted for each of those values.

With these tables as the setup:

CREATE TEMP TABLE t1 (id INTEGER);
CREATE TEMP TABLE t2 (id INTEGER, t TEXT);

Method 1:

WITH inserted1 AS (
        INSERT INTO t1
        SELECT 9
        RETURNING id
), inserted2 AS (
        INSERT INTO t2
        SELECT id, 'some val'
        FROM inserted1
        RETURNING id
)
INSERT INTO t2
SELECT id, 'other val'
FROM inserted1

Method 2:

WITH inserted AS (
        INSERT INTO t1
        SELECT 4
        RETURNING id
)
INSERT INTO t2
SELECT id, v
FROM inserted
CROSS JOIN (
        VALUES
        ('val1'),
        ('val2')
) vals(v)

If you run either, then check t2, you'll see it will contain the expected values.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. It works, but what if I need to add values to other columns and be able to insert multiple rows like this? I've updated my question to clarify
@Chickenfresh Updated my answer
Sorry, but why do you have 3 temp tables? I have only 2 tables and need to insert at least two rows with a couple values into table_2 using id of inserted row into first table_1
@Chickenfresh Updated
Is that Okay that in pgadmin it fails with error ERROR: current transaction is aborted, commands ignored until end of transaction block SQL state: 25P02?
|
0

Please find the below query:

insert into table1(columnName)values('stack2');

insert into table_2 values(SCOPE_IDENTITY(),'val1','val2');

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.