From: Assaf Gordon <assafgordon@gmail.com>
To: David G. Johnston <david.g.johnston@gmail.com>
Cc: pgsql-general@lists.postgresql.org <pgsql-general@lists.postgresql.org>
Subject: Re: connecting multiple INSERT CTEs to same record?
Date: Tue, 19 Oct 2021 17:45:24 -0600
Message-ID: <415b07c1-230f-bcb6-0b65-0514a1908777@gmail.com> (raw)
In-Reply-To: <CAKFQuwatrODxE48RrZkvxia3Jb9YyDsobpVME7FzPfhB1SL4HQ@mail.gmail.com>
References: <68708e28-dd17-13d6-2acd-9ca4f9735379@gmail.com>
<CAKFQuwatrODxE48RrZkvxia3Jb9YyDsobpVME7FzPfhB1SL4HQ@mail.gmail.com>
On 2021-10-19 1:13 p.m., David G. Johnston wrote:
>
> Instead of assigning a unique identifier to student after inserting it
> into the table, assign the identifier first. Generally this is done by
> using “nextval()”
Aha! Such elegant solution!
Seems obvious in hindsight, but I just couldn't figure it out nor find
any mentions to it online.
For others who might stumble upon this thread in the future,
the solution becomes:
====
with
-- pre-assign unique IDs for each record,
-- without inserting them to the table yet.
new_data_with_ids as (
select
nextval(pg_get_serial_sequence('students','id'))
as new_student_id,
new_data.*
from new_data )
,
-- Now insert the new names, with their pre-assigned IDs
new_students as (
insert into students(id,name)
select new_student_id, name
from new_data_with_ids
returning * -- optional
)
,
-- And use the IDs for other tables, too
new_classes as (
insert into classes(student_id, subject)
select new_student_id, subject
from new_data_with_ids
returning * --optional
)
-- return the new IDs with the data
select * from new_data_with_ids ;
===
Thank you!
Regards,
- Assaf Gordon
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: assafgordon@gmail.com, david.g.johnston@gmail.com
Subject: Re: connecting multiple INSERT CTEs to same record?
In-Reply-To: <415b07c1-230f-bcb6-0b65-0514a1908777@gmail.com>
References: <68708e28-dd17-13d6-2acd-9ca4f9735379@gmail.com> <CAKFQuwatrODxE48RrZkvxia3Jb9YyDsobpVME7FzPfhB1SL4HQ@mail.gmail.com> <415b07c1-230f-bcb6-0b65-0514a1908777@gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox