pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Tomas Vondra <tomas.vondra@enterprisedb.com>
Cc: Pavel Luzanov <p.luzanov@postgrespro.ru>
Cc: pgsql-general@lists.postgresql.org
Subject: Re: Strange behavior of function date_trunc
Date: Wed, 05 May 2021 10:11:15 -0400
Message-ID: <4015564.1620223875@sss.pgh.pa.us> (raw)
In-Reply-To: <8986e9dd-576a-3c3b-b523-3052519387fd@enterprisedb.com>
References: <6b4f0c89-3c15-d5bd-7909-62cc33b1a106@postgrespro.ru>
	<8986e9dd-576a-3c3b-b523-3052519387fd@enterprisedb.com>

Tomas Vondra <tomas.vondra@enterprisedb.com> writes:
> On 5/5/21 3:23 PM, Pavel Luzanov wrote:
>> It is very likely that the date_trunc function in the following example 
>> is executed for each line of the query. Although it marked as a STABLE 
>> and could only be called once.

> It could, but that's just an option - the database may do that, but it's 
> not required to do it. In this case it might be beneficial, but it'd 
> make the planner more complex etc.

Yeah, there simply is not any provision for caching the results of
stable functions in the way Pavel seems to be imagining.  People
have played around with patches for that, but nothing's been accepted.

> You can use CTE to execute it just once, I think:
>    with x as (select date_trunc('day', '2021-04-01'::timestamptz) as x)
>    select * from t where a > (select x from x);

Actually it's sufficient to write

select * from t where a > (select date_trunc('day', '2021-04-01'::timestamptz))

Postgres interprets that as an uncorrelated sub-select, so it's only done
once per outer query.  I think that these days, the CTE form would be
flattened into that anyway (without MATERIALIZED).

			regards, tom lane





view thread (3+ messages)

Message-ID: <4015564.1620223875@sss.pgh.pa.us>
Permalink:  ../4015564.1620223875@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/4015564.1620223875@sss.pgh.pa.us

 · 

reply

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: tgl@sss.pgh.pa.us, tomas.vondra@enterprisedb.com, p.luzanov@postgrespro.ru
  Subject: Re: Strange behavior of function date_trunc
  In-Reply-To: <4015564.1620223875@sss.pgh.pa.us>
  References: <6b4f0c89-3c15-d5bd-7909-62cc33b1a106@postgrespro.ru> <8986e9dd-576a-3c3b-b523-3052519387fd@enterprisedb.com> <4015564.1620223875@sss.pgh.pa.us>

* 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