From: Johannes Graën <johannes@selfnet.de>
To: pgsql-general@lists.postgresql.org
Subject: Re: Multiple SELECT statements Using One WITH statement
Date: Thu, 20 Jan 2022 16:28:29 +0100
Message-ID: <0fe21602-be12-6914-4f0d-53f116f969b5@selfnet.de> (raw)
In-Reply-To: <DB9PR07MB7180193C517B713F3983700CCB5A9@DB9PR07MB7180.eurprd07.prod.outlook.com>
References: <DB9PR07MB7180D7EB60AC27E3409E1572CB5A9@DB9PR07MB7180.eurprd07.prod.outlook.com>
<CAKFQuwatCDPT0tNojn5fVQ7NOkUgcZb9n5=GRRLz-gHF+XDddA@mail.gmail.com>
<DB9PR07MB7180193C517B713F3983700CCB5A9@DB9PR07MB7180.eurprd07.prod.outlook.com>
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.
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-general@postgresql.org
Cc: johannes@selfnet.de
Subject: Re: Multiple SELECT statements Using One WITH statement
In-Reply-To: <0fe21602-be12-6914-4f0d-53f116f969b5@selfnet.de>
References: <DB9PR07MB7180D7EB60AC27E3409E1572CB5A9@DB9PR07MB7180.eurprd07.prod.outlook.com> <CAKFQuwatCDPT0tNojn5fVQ7NOkUgcZb9n5=GRRLz-gHF+XDddA@mail.gmail.com> <DB9PR07MB7180193C517B713F3983700CCB5A9@DB9PR07MB7180.eurprd07.prod.outlook.com> <0fe21602-be12-6914-4f0d-53f116f969b5@selfnet.de>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox