1

I have two queries. The first creates a new user. The table has three fields, id, name and email. The id field is an autoincrement value.

The second query creates additional data related to this user, using the ID value.

How can I pass the RETURNING value of the first to the second query?

Example:

INSERT INTO users (
  name, 
  email
) VALUES (
  'John Doe',
  '[email protected]'
) RETURNING id;

INSERT INTO users_stuff (
  user_id,
  money,
  hasCar
) VALUES (
  id,
  1000,
  false
);

The above example doesn't work because the second query never receives the first one's RETURNING value, which would be the new record's autoincrement ID.

Is there a way though?

1 Answer 1

2

Use a CTE:

WITH u AS (
      INSERT INTO users (name, email)
          VALUES ('John Doe', '[email protected]')
          RETURNING id;
     )
INSERT INTO users_stuff (user_id, money, hasCar) 
    SELECT u.id, 1000, false
    FROM u;
Sign up to request clarification or add additional context in comments.

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.