Re: INSERT / UPDATE into 2 inner joined table simultaneously

From: Christopher Swingley <cswingle(at)swingleydev(dot)com>
To: Lou <lou(at)dayspringpublisher(dot)com>
Cc: pgsql-sql(at)lists(dot)postgresql(dot)org
Subject: Re: INSERT / UPDATE into 2 inner joined table simultaneously
Date: 2019-03-06 20:11:23
Message-ID: CAHsw449uo18j9fSxd-KZgwWSSf3nTqe2v6ho86U7OGNXFC4S2g@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Lou,

On Wed, Mar 6, 2019 at 10:59 AM Lou <lou(at)dayspringpublisher(dot)com> wrote:
> How can I INSERT new rows into both tables simultaneously with automatically created id numbers, and how can I UPDATE both tables simultaneously?

Although I have no idea why you would want to do this, you can insert
data into two tables with one query using a common table expression:

WITH cinsert AS (
INSERT INTO c (id, name) VALUES (1, 'Jones')
RETURNING id, name)
INSERT INTO p (id, name) (SELECT * FROM cinsert);

Cheers,

Chris
--
Christopher Swingley
Fairbanks, Alaska
http://swingleydev.com/
cswingle(at)swingleydev(dot)com

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Lou 2019-03-06 21:36:21 Re: INSERT / UPDATE into 2 inner joined table simultaneously
Previous Message Lou 2019-03-06 19:59:22 INSERT / UPDATE into 2 inner joined table simultaneously