HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMajor

Use same Postgres WITH in multiple queries

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
samepostgreswithmultiplequeriesuse

Problem

I would like to use same WITH in multiple queries.

WITH x AS (INSERT ... RETURNING id)
INSERT INTO t2 VALUES (x);
INSERT INTO t3 VALUES (x);


How would I do that? Do I have to create a temporary table instead?

Solution

You can chain multiple CTEs that perform an INSERT:

with x (id) as (
  insert into ... 
  returning id
), t2_insert as (
  insert into t2 (id)
  select id
  from x
)
insert into t3
select id
from x;

Code Snippets

with x (id) as (
  insert into ... 
  returning id
), t2_insert as (
  insert into t2 (id)
  select id
  from x
)
insert into t3
select id
from x;

Context

StackExchange Database Administrators Q#171123, answer score: 21

Revisions (0)

No revisions yet.