pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Andreas Kretschmer <andreas@a-kretschmer.de>
To: pgsql-general@lists.postgresql.org
Subject: Re: Why scan all columns when we select distinct c1?
Date: Sun, 14 Jan 2024 16:31:50 +0100
Message-ID: <7301b250-7240-4b45-aab6-82ebf6d9edbb@a-kretschmer.de> (raw)
In-Reply-To: <CAOe1Go3uHkTrgBMm1O2pVWQAV09ZxVW_vaKM1GeAkAu_RByt2A@mail.gmail.com>
References: <CAOe1Go3uHkTrgBMm1O2pVWQAV09ZxVW_vaKM1GeAkAu_RByt2A@mail.gmail.com>



Am 14.01.24 um 12:17 schrieb Yongtao Huang:
>
>
> My question is why scan all columns in PG 16.01?
> If `select distinct c1`, scan the column `c1` is enough, like PG 9.4.

good question, I think because the seq scan always reads the column. If 
you create an index on c1, this changes:

postgres=# create index idx1 on t1(c1);
CREATE INDEX
postgres=# set enable_seqscan to off;
SET
postgres=# explain (costs, verbose) select distinct c1 from t1;
                                      QUERY PLAN
-------------------------------------------------------------------------------------
  Unique  (cost=0.15..63.93 rows=200 width=4)
    Output: c1
    ->  Index Only Scan using idx1 on public.t1  (cost=0.15..61.10 
rows=1130 width=4)
          Output: c1
(4 rows)


now we scan only the index and not the heap.

Regards, Andreas

-- 
Andreas Kretschmer
CYBERTEC PostgreSQL Services and Support






view thread (6+ messages)  latest in thread

Message-ID: <7301b250-7240-4b45-aab6-82ebf6d9edbb@a-kretschmer.de>
Permalink:  ../7301b250-7240-4b45-aab6-82ebf6d9edbb@a-kretschmer.de/
Also on:    postgresql.org/message-id/7301b250-7240-4b45-aab6-82ebf6d9edbb@a-kretschmer.de

 · 

reply

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 from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: andreas@a-kretschmer.de
  Subject: Re: Why scan all columns when we select distinct c1?
  In-Reply-To: <7301b250-7240-4b45-aab6-82ebf6d9edbb@a-kretschmer.de>
  References: <CAOe1Go3uHkTrgBMm1O2pVWQAV09ZxVW_vaKM1GeAkAu_RByt2A@mail.gmail.com> <7301b250-7240-4b45-aab6-82ebf6d9edbb@a-kretschmer.de>

* 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