From: Tom Lane <tgl@sss.pgh.pa.us>
To: Jimmy A <jimmypsql@gmail.com>
Cc: pgsql-performance@lists.postgresql.org
Subject: Re: EXISTS by itself vs SELECT EXISTS much slower in query.
Date: Mon, 08 Nov 2021 15:35:12 -0500
Message-ID: <997053.1636403712@sss.pgh.pa.us> (raw)
In-Reply-To: <CANU97yu0HxOdgZ_2J+kNRzeuh-XF4h2EYF8df2i--ruP0fuXwQ@mail.gmail.com>
References: <CANU97yu0HxOdgZ_2J+kNRzeuh-XF4h2EYF8df2i--ruP0fuXwQ@mail.gmail.com>
Jimmy A <jimmypsql@gmail.com> writes:
> I have two equivalent queries, one with an EXISTS clause by itself and one
> wrapped in a (SELECT EXISTS) and the "naked" exists is much slower.
> I would expect both to be the same speed / have same execution plan.
That is a dangerous assumption. In general, wrapping (SELECT ...) around
something has a significant performance impact, because it pushes Postgres
to try to decouple the sub-select's execution from the outer query.
As an example,
postgres=# select x, random() from generate_series(1,3) x;
x | random
---+---------------------
1 | 0.08595356832524814
2 | 0.6444265043474005
3 | 0.6878852071694332
(3 rows)
postgres=# select x, (select random()) from generate_series(1,3) x;
x | random
---+--------------------
1 | 0.7028987801136708
2 | 0.7028987801136708
3 | 0.7028987801136708
(3 rows)
That's not a bug: it's expected that the second query will evaluate
random() only once.
In the case at hand, I suspect you're getting a "hashed subplan"
in one query and not the other. The depesz.com display doesn't
really show that, but EXPLAIN VERBOSE would.
regards, tom lane
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 using the --to and --cc options:
reply via email
To: pgsql-performance@postgresql.org
Cc: tgl@sss.pgh.pa.us, jimmypsql@gmail.com, pgsql-performance@lists.postgresql.org
Subject: Re: EXISTS by itself vs SELECT EXISTS much slower in query.
In-Reply-To: <997053.1636403712@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