Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mkBMM-0007E0-0f for pgsql-performance@arkaria.postgresql.org; Mon, 08 Nov 2021 20:35:18 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mkBMK-0007hf-VB for pgsql-performance@arkaria.postgresql.org; Mon, 08 Nov 2021 20:35:16 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mkBMK-0007hW-LM for pgsql-performance@lists.postgresql.org; Mon, 08 Nov 2021 20:35:16 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1mkBMI-0002cs-Do for pgsql-performance@lists.postgresql.org; Mon, 08 Nov 2021 20:35:15 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 1A8KZCae997054; Mon, 8 Nov 2021 15:35:12 -0500 From: Tom Lane To: Jimmy A cc: pgsql-performance@lists.postgresql.org Subject: Re: EXISTS by itself vs SELECT EXISTS much slower in query. In-reply-to: References: Comments: In-reply-to Jimmy A message dated "Sun, 07 Nov 2021 14:27:14 -0800" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <997052.1636403712.1@sss.pgh.pa.us> Date: Mon, 08 Nov 2021 15:35:12 -0500 Message-ID: <997053.1636403712@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Jimmy A 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