Re: Multiple SELECT statements Using One WITH statement

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Avi Weinberg <AviW(at)gilat(dot)com>
Cc: "pgsql-general(at)lists(dot)postgresql(dot)org" <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: Multiple SELECT statements Using One WITH statement
Date: 2022-01-20 16:45:49
Message-ID: CAKFQuwZvWs-P3-PUO58sPS23zyjY14oGRqDhjuRrQVj=DFJHtA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Jan 20, 2022 at 7:42 AM Avi Weinberg <AviW(at)gilat(dot)com> 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?
>
>
>
Sorry, that was a bit of a drive-by for me. I figured you could easily
test whether your proposed query structure would work and figured maybe you
didn't realize that CTEs could be chained together.

The short answer is that a query can only output a single result set so
having two top-level select statements is simply prohibited. And result
sets are not cached between statements so it isn't like there would be any
place to store intermediate CTE results automatically. As you've been
told, you can do that with temporary tables (it's a much bigger pain if you
want something that isn't session-local).

You can always write:

CREATE VIEW cte_view AS
WITH cte AS (...)
SELECT * FROM cte;

And then incorporate that into any queries that require the results of said
CTE.

David J.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Garfield Lewis 2022-01-20 17:00:36 Re: [EXT] Re: Can we get the CTID value
Previous Message Duarte Carreira 2022-01-20 15:59:07 Re: Query on postgres_fdw extension