Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mcuN9-0003mi-AD for pgsql-general@arkaria.postgresql.org; Tue, 19 Oct 2021 19:02:03 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mcuN4-0002Aa-LK for pgsql-general@arkaria.postgresql.org; Tue, 19 Oct 2021 19:01:58 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mcjPk-0001QF-8s for pgsql-general@lists.postgresql.org; Tue, 19 Oct 2021 07:20:00 +0000 Received: from mail-pj1-x102e.google.com ([2607:f8b0:4864:20::102e]) by magus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_128_GCM_SHA256:128) (Exim 4.92) (envelope-from ) id 1mcjPh-0007pW-Lt for pgsql-general@lists.postgresql.org; Tue, 19 Oct 2021 07:19:59 +0000 Received: by mail-pj1-x102e.google.com with SMTP id na16-20020a17090b4c1000b0019f5bb661f9so1970676pjb.0 for ; Tue, 19 Oct 2021 00:19:57 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=to:from:subject:message-id:date:user-agent:mime-version :content-language:content-transfer-encoding; bh=xzp+//0b6wK2ZnKfXyuoliGfLfRsf3wLReXD4S5IvVY=; b=EkvqRCUGakHkwHmVRHadk+nVVXk9E3VWFGcSYgj39lfHZIlVtlqRwn0/7iiy53kXyh ME9sZzvANXAOamF31Ph3Au7NDUEYGhjbr5sFG/6SR9eTb0g6YlqIkm7hqWS/UUW3wyf3 MmkJmzwSDj2msd5pIhMfySwc0h73bK3ww7xZIFhGYIq0n8rVi4ISHYv2J/L+R1nJMhHs 7HQFSC0MAr0TFqwpLA+Iyti65qaAqJoJDygIypFtE3VzX/7xfh4NW+/Kamq4pj7b/8M6 wLDAzeXqGZsxWVm3nrceMAsm6OEcWnCTWTQzm/rD4jnUs4rUAIry09QMn4Hk4Vjc2X90 sGUw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:to:from:subject:message-id:date:user-agent :mime-version:content-language:content-transfer-encoding; bh=xzp+//0b6wK2ZnKfXyuoliGfLfRsf3wLReXD4S5IvVY=; b=GxkUxMs4j2wrVw7AIBpluWHuF+uI/VdXG/mqK/vX7b1mxBKvVbBcMQ0ZAk+WtNaq7I /OmuPrfbsBOeJ8Ie/ZqmhNyh8b4IEgXzOj03G6CeYLeGu92KcDX+dBojJZxEiGmP6Gci cqGx2TwQ1pKQmAiBBF3uVeT0Ipp5YadhQ2OW0VbJghdoB84VpquRaA4EL9RtdIMPZnXW QYhDZEoCJzZp9Mj3hCBL+L82J6RT5qBhZQrGzLWrKZDiLOQ9oAamRBBhujl9DeuWdcxH F7O2cFDOlZzAKyhFFNgvBOAT1oYeqkpvjAgFUriD2xHxoRLC064ndXEEEGJNcoMm0LqK s7vQ== X-Gm-Message-State: AOAM531cqhFSpk0x1ER1UERYmnlTLuI4a6NB2xbXvXLL5dx0Bxq01WqN Gpa6V1MbLAOnLZl0p4qLMY48qluOsrw= X-Google-Smtp-Source: ABdhPJyMxzgHHMSku41C00lwjUyCMHHvSsvRdVBprx9ShEQ/1d0RfTWJwGyq9+xOFvPQ9TF7HNjZ+g== X-Received: by 2002:a17:902:8b83:b029:12c:cbce:a52f with SMTP id ay3-20020a1709028b83b029012ccbcea52fmr31529022plb.9.1634627995348; Tue, 19 Oct 2021 00:19:55 -0700 (PDT) Received: from tomato.moose.housegordon.com (moose.housegordon.com. [184.68.105.38]) by smtp.googlemail.com with ESMTPSA id kk18sm1745234pjb.8.2021.10.19.00.19.54 for (version=TLS1_3 cipher=TLS_AES_128_GCM_SHA256 bits=128/128); Tue, 19 Oct 2021 00:19:54 -0700 (PDT) To: pgsql-general@lists.postgresql.org From: Assaf Gordon Subject: connecting multiple INSERT CTEs to same record? Message-ID: <68708e28-dd17-13d6-2acd-9ca4f9735379@gmail.com> Date: Tue, 19 Oct 2021 01:19:53 -0600 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Thunderbird/78.14.0 MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8; format=flowed Content-Language: en-US Content-Transfer-Encoding: 7bit List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Hello, I'm looking for a way to insert items to multiple tables (connected with foreign keys) using CTEs. I found few similar questions on stack-overflow and the mailing list, but no solution. Please consider this contrived example: A table of students, and a table of classes they are in: ==== create temp table students( id serial primary key, name varchar); create temp table classes( id serial primary key, student_id int not null references students(id), subject varchar); ==== And, I am given a list of new students and their classes (from an external source, imported into a temp table): ==== create temp table new_data ( name varchar, subject varchar); insert into new_data values ('John','Math'), ('Jane','Physics'), ('Moe','Science'), ('John','English'); -- different student with same name ==== I want to first create new 'students' record, and then create a corresponding 'classes' record. For that - I need both the newly assigned 'id', and they corresponding source record from 'new_data'. A trivial usage of "insert ... returning *" doesn't work - it can't return columns that were not directly inserted (and the 'subject' string wasn't inserted): === with new_students as ( insert into students(name) select name from new_data returning * ) insert into classes(student_id, subject) select new_students.id, -- how to get the subject matching to --- the newly inserted student? ?????? from new_students ; === I found a work-around, but it relies on a flimsy assumption - that within this transaction, the CTIDs for the 'new_data' and the newly inserted 'students' rows maintain the same order. Using this assumption, I calculate a unique value for each row with 'row_number() over (order by ctid)', assuming that the order stays the same, then join the tables to match the new student to its 'subject': === with new_data_with_order as ( select row_number() over (order by ctid) as new_order, * from new_data ) , new_students as ( insert into students(name) select name from new_data_with_order returning ctid,* ) , new_students_with_order as ( select row_number() over (order by ctid) as new_order, * from new_students ) , merged_data as ( -- Is this correct?? -- it is based on the assumption that the order -- of inserted rows into 'students' (and hence, their CTID order) -- is the same as the order of the rows in 'new_data' -- and their CTID. select * from new_students_with_order join new_data_with_order on new_students_with_order.new_order = new_data_with_order.new_order ) -- for troubleshooting: -- select * from merged_data ; insert into classes(student_id, subject) select id, -- merged_data.id is the newly assigned student.id primary key. subject from merged_data ; === So my question is: Is this assumption about CTID maintaining order (within the transaction) correct? Even when considering concurrency? Even if in strange coincidence 'VACCUUM' is running in parallel to this query? Or, Is there another way to achieve this? consider that this is a contrived example, in my use-case I need to update several tables. Of course it can be done on the application-level, one-by-one inserting new 'student' then inserting its 'classes' - but I prefer to avoid that. Sadly, I can't assume the student name is unique, so I can't "join" on it. Thanks! - Assaf Gordon