Re: Multiple SELECT statements Using One WITH statement - Mailing list pgsql-general

From Johannes Graën
Subject Re: Multiple SELECT statements Using One WITH statement
Date
Msg-id 0fe21602-be12-6914-4f0d-53f116f969b5@selfnet.de
Whole thread Raw
In response to RE: Multiple SELECT statements Using One WITH statement  (Avi Weinberg <AviW@gilat.com>)
List pgsql-general
On 20/01/2022 15.42, Avi Weinberg wrote:
> Thanks David for the reply, but my question was a little different.
> 
> I know I can have multiple CTE queries like you showed, but I want to 
> have one single WITH query, and use it in multiple queries, not just by 
> one query the directly proceed the CTE.
> 
> Why do I need to execute the CTE query twice if I have two queries that 
> wants to use it?

When data is going to be provided to an application via a REST API, I 
find this pattern quite useful:

WITH list AS (
         SELECT generate_series(1,10) AS n
)
SELECT json_build_object(
         'even', (
                 SELECT json_agg(n)
                 FROM (
                         SELECT n
                         FROM list
                         WHERE n%2 = 0
                 ) even
         ),
         'odd', (
                 SELECT json_agg(n)
                 FROM (
                         SELECT n
                         FROM list
                         WHERE n%2 = 1
                 ) odd
         )
) obj;


If data is to be written to separate tables, writing the intermediate 
result to a temporary table as explained by Josef might be the simplest 
solution.



pgsql-general by date:

Previous
From: Josef Šimánek
Date:
Subject: Re: Multiple SELECT statements Using One WITH statement
Next
From: Duarte Carreira
Date:
Subject: Re: Query on postgres_fdw extension