Re: COUNT(*) and index-only scans

From: Jeff Janes <jeff(dot)janes(at)gmail(dot)com>
To: Kevin Grittner <Kevin(dot)Grittner(at)wicourts(dot)gov>
Cc: Bruce Momjian <bruce(at)momjian(dot)us>, PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>
Subject: Re: COUNT(*) and index-only scans
Date: 2011-10-11 02:29:27
Message-ID: CAMkU=1wj0HBK_Mps8JgYzes-wZp5nuGw4GgvUz4Rmr5ud+xMUQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

On Mon, Oct 10, 2011 at 10:36 AM, Kevin Grittner
<Kevin(dot)Grittner(at)wicourts(dot)gov> wrote:
> Bruce Momjian <bruce(at)momjian(dot)us> wrote:
>> I talked to Robert Haas and he said that index-only scans do not
>> optimize COUNT(*).  Is this something we can do for PG 9.2?  Is
>> anyone working on this?
>
> Well, it's not that it doesn't optimize COUNT(*) -- it's that it
> doesn't yet cost the index scan as cheaper than a table scan when
> you're accessing every row.
>
> create table t (id int not null primary key);
> insert into t select generate_series(1, 1000000);
> vacuum freeze analyze;
> explain analyze select count(*) from t
>  where id between 500000 and 500010;
>
> That gives you an index-only scan; but without the WHERE clause it
> uses a seq scan.

If you convert the where clause to "where id is not null" it uses the
index only scan again, but only if you nudge it too with
enable_seqscan=off.

I'm not sure why it needs the nudge in one case but not the other.

Cheers,

Jeff

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Fujii Masao 2011-10-11 02:46:37 Re: unite recovery.conf and postgresql.conf
Previous Message Florian Pflug 2011-10-11 01:29:09 Re: Bug in walsender when calling out to do_pg_stop_backup (and others?)