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 1mxxfa-00053T-Ei for pgsql-general@arkaria.postgresql.org; Thu, 16 Dec 2021 20:48:06 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1mxxfZ-0008L3-Dq for pgsql-general@arkaria.postgresql.org; Thu, 16 Dec 2021 20:48:05 +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 1mxxfZ-0008Ku-3Q for pgsql-general@lists.postgresql.org; Thu, 16 Dec 2021 20:48:05 +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 1mxxfW-0007vi-6N for pgsql-general@lists.postgresql.org; Thu, 16 Dec 2021 20:48:04 +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 1BGKlvgR1238960; Thu, 16 Dec 2021 15:47:57 -0500 From: Tom Lane To: Markus Demleitner cc: pgsql-general@lists.postgresql.org Subject: Re: SELECT DISTINCT scans the table? In-reply-to: <20211216110014.27xcbjfs2rkpjz7t@victor> References: <20211216110014.27xcbjfs2rkpjz7t@victor> Comments: In-reply-to Markus Demleitner message dated "Thu, 16 Dec 2021 12:00:14 +0100" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <1238958.1639687677.1@sss.pgh.pa.us> Date: Thu, 16 Dec 2021 15:47:57 -0500 Message-ID: <1238959.1639687677@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk Markus Demleitner writes: > Maximally stripped down, my problem is that > select distinct 300 from > seqscans (at least in PostgreSQL 11.14). To me, it seems > obvious that this ought be be just one row containing 300 once > Postgres has established that is nonempty. > Why do things not work like this? Am I missing something major? That seems like the sort of optimization that we absolutely should not spend cycles looking for. If it were a trivial change consuming no detectable number of planning cycles, maybe it would be worth the development and maintenance effort; though I'd be dubious about the value. But the fact that it'd have to be transformed into something testing whether the table is nonempty makes it fairly nontrivial. I doubt it's worth the development cost plus the cycles imposed on every other query. regards, tom lane