0

here's an example to complete the title, this is the inner of my function (i am using postgresql but i guess this is pure SQL language)

$$
  INSERT INTO foo VALUES (DEFAULT, $1) RETURNING id;
  INSERT INTO link_foo_to_bar VALUES (1, <?>);
$$ language SQL;

two things to notice here, I RETURNING the id of the first insert, how to catch it as to use the returned id as the second argument of the second insert marked as < ? > ?

1
  • 1
    Gordon's answer is probably what you need, but I suggest you also Read this post. Commented May 10, 2015 at 16:24

2 Answers 2

5

You can use a CTE to capture the rows inserted from the first insert:

with firstinsert as (
      INSERT INTO foo VALUES (DEFAULT, $1) RETURNING id
     )
INSERT INTO link_foo_to_bar 
    select 1, id
    from firstinsert;
Sign up to request clarification or add additional context in comments.

3 Comments

I valid the other answer as it is more neat and logic as the id i'm using is a sequence. but thanks for your answer I didn't know this way of writing constants.
This example works for any kind of returning value, not just a sequence value.
@FrankHeikens . . . In addition, it doesn't suffer from race conditions, that can invalidate the other answer.
1

If the first column is a serial/primary key, I would use CURRVAL function:

$$
  INSERT INTO foo VALUES (DEFAULT, $1);
  INSERT INTO link_foo_to_bar VALUES (1, CURRVAL('foo_id_seq'));
$$ language SQL;

2 Comments

neat. i may ask a novice question here but are the INSERT statements synchronous ? what if the first insert has a big load of data to insert, is the CURRVAL going to be updated properly as the process switch on the second INSERT ?
It is absolutely safe - CURRVAL returns last returned value from any sequence for current session.

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.