Re: Multiple SELECT statements Using One WITH statement

From: Johannes Graën <johannes(at)selfnet(dot)de>
To: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Multiple SELECT statements Using One WITH statement
Date: 2022-01-20 15:28:29
Message-ID: 0fe21602-be12-6914-4f0d-53f116f969b5@selfnet.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Duarte Carreira 2022-01-20 15:59:07 Re: Query on postgres_fdw extension
Previous Message Josef Šimánek 2022-01-20 15:13:31 Re: Multiple SELECT statements Using One WITH statement