Re: Elegant way to insert of some value in some tables in shortinstruction - Mailing list pgsql-novice

From Andreas Kretschmer
Subject Re: Elegant way to insert of some value in some tables in shortinstruction
Date
Msg-id ac135b18-0561-43ad-bf3c-967bd2d09f18@a-kretschmer.de
Whole thread Raw
In response to RE: Elegant way to insert of some value in some tables in shortinstruction  (David Raymond <David.Raymond@tomtom.com>)
List pgsql-novice

Am 13.03.19 um 20:25 schrieb David Raymond:
>
> ...but inserts into different tables need to be done in different statements.

you can insert into 2 tables within 1 statement using writeable common 
table expressions (wCTE):


test=# create table table1(a int, b int, c int);
CREATE TABLE
test=*# create table table2(a int, b int, c int);
CREATE TABLE
test=*# with x as (insert into table1 values (1,2,3) returning *) insert 
into table2 select * from x;
INSERT 0 1
test=*# select * from table1;
  a | b | c
---+---+---
  1 | 2 | 3
(1 row)

test=*# select * from table2;
  a | b | c
---+---+---
  1 | 2 | 3
(1 row)

test=*# with x as (insert into table1 values (4,5,6) returning *) insert 
into table2 select * from x;
INSERT 0 1
test=*# select * from table1;
  a | b | c
---+---+---
  1 | 2 | 3
  4 | 5 | 6
(2 rows)

test=*# select * from table2;
  a | b | c
---+---+---
  1 | 2 | 3
  4 | 5 | 6
(2 rows)

test=*#



Regards, Andreas

-- 
2ndQuadrant - The PostgreSQL Support Company.
www.2ndQuadrant.com



pgsql-novice by date:

Previous
From: David Rowley
Date:
Subject: Re: Parallel Aggregates for string_agg and array_agg
Next
From: "Ila B."
Date:
Subject: Problems wording a GROUP BY ranked query