Re: SELECT DISTINCT <constant> scans the table?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Markus Demleitner <msdemlei(at)ari(dot)uni-heidelberg(dot)de>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: SELECT DISTINCT <constant> scans the table?
Date: 2021-12-16 20:47:57
Message-ID: 1238959.1639687677@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Markus Demleitner <msdemlei(at)ari(dot)uni-heidelberg(dot)de> writes:
> Maximally stripped down, my problem is that

> select distinct 300 from <bigtable>

> seqscans <bigtable> (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 <bigtable> 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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Adrian Klaver 2021-12-16 21:05:37 Re: Packages, inner subprograms, and parameterizable anonymous blocks for PL/pgSQL
Previous Message Bryn Llewellyn 2021-12-16 20:36:22 Re: Packages, inner subprograms, and parameterizable anonymous blocks for PL/pgSQL