Re: Strange behavior of some volatile function like random(), nextval() - Mailing list pgsql-hackers

From David G. Johnston
Subject Re: Strange behavior of some volatile function like random(), nextval()
Date
Msg-id CAKFQuwbxcFcCN-FYqwSeH0-GkwLhC6rzVOWSDG=v9vYJLR0e0g@mail.gmail.com
Whole thread Raw
In response to Re: Strange behavior of some volatile function like random(), nextval()  (Michael Paquier <michael.paquier@gmail.com>)
Responses Re: Strange behavior of some volatile function like random(), nextval()  (Alex Ignatov <a.ignatov@postgrespro.ru>)
Re: Strange behavior of some volatile function like random(), nextval()  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-hackers
More specifically...
On Wed, Jun 29, 2016 at 7:34 AM, Michael Paquier <michael.paquier@gmail.com> wrote:
On Wed, Jun 29, 2016 at 7:43 PM, Alex Ignatov <a.ignatov@postgrespro.ru> wrote:
> Hello!
>
> Got some strange behavior of random() function:
>
> postgres=# select (select random() ) from generate_series(1,10) as i;
>       random
> -------------------
>  0.831577288918197
> [...]
> (10 rows)

I recall that this is treated as an implicit LATERAL, meaning that
random() is calculated only once.

A non-correlated (i.e., does not refer to outer variables) subquery placed into the target-list need only have its value computed once - so that is what happens.  The fact that a volatile function can return different values given the same arguments doesn't mean much when the function is only ever called a single time.​


> postgres=# select (select random()+i*0 ) from generate_series(1,10) as i;
>       ?column?
> --------------------
>    0.97471913928166
> [...]
> (10 rows)

But not that. So those results do not surprise me.


​A correlated subquery, on the other hand, has to be called once for every row and is evaluated within the context supplied by said row​.  Each time random is called it returns a new value.

Section 4.2.11 (9.6 docs)

Maybe this could be worded better but the first part talks about a single execution while "any one execution" is mentioned in reference to "the surrounding query".

​I do think that defining "correlated" and "non-correlated" subqueries within this section would be worthwhile.

David J.


pgsql-hackers by date:

Previous
From: Fabien COELHO
Date:
Subject: Re: pgbench unable to scale beyond 100 concurrent connections
Next
From: Sachin Kotwal
Date:
Subject: Re: pgbench unable to scale beyond 100 concurrent connections