pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Adrian Holovaty <postgresql@holovaty.com>
To: pgsql-performance@postgresql.org
Subject: Re: Index on a function and SELECT DISTINCT
Date: Mon, 17 Jan 2005 11:59:24 -0600
Message-ID: <200501171159.24797.postgresql@holovaty.com> (raw)
In-Reply-To: <20050117100942.692be97a.frank@wiles.org>
References: <200501141232.13139.postgresql@holovaty.com>
	<20050117100942.692be97a.frank@wiles.org>

Frank Wiles wrote:
> Adrian Holovaty <postgresql@holovaty.com> wrote:
> > If I have this table, function and index in Postgres 7.3.6 ...
> >
> > """
> > CREATE TABLE news_stories (
> >     id serial primary key NOT NULL,
> >     pub_date timestamp with time zone NOT NULL,
> >     ...
> > )
> > CREATE OR REPLACE FUNCTION get_year_trunc(timestamp with time zone)
> > returns timestamp with time zone AS 'SELECT date_trunc(\'year\',$1);'
> > LANGUAGE 'SQL' IMMUTABLE;
> > CREATE INDEX news_stories_pub_date_year_trunc ON
> > news_stories( get_year_trunc(pub_date) );
> > """
> >
> > ...why does this query not use the index?
> >
> > db=# EXPLAIN SELECT DISTINCT get_year_trunc(pub_date) FROM
> > news_stories;
> >                                    QUERY PLAN
> > ---------------------------------------------------------------------
> > ------------
> >  Unique  (cost=59597.31..61311.13 rows=3768 width=8)
> >    ->  Sort  (cost=59597.31..60454.22 rows=342764 width=8)
> >          Sort Key: date_trunc('year'::text, pub_date)
> >          ->  Seq Scan on news_stories  (cost=0.00..23390.55
> >          rows=342764
> > width=8)
> > (4 rows)
> >
> > The query is noticably slow (2 seconds) on a database with 150,000+
> > records. How can I speed it up?
>
>   It's doing a sequence scan because you're not limiting the query in
>   the FROM clause.  No point in using an index when you're asking for
>   the entire table. :)

Ah, that makes sense. So is there a way to optimize SELECT DISTINCT queries 
that have no WHERE clause?

Adrian



view thread (4+ messages)  latest in thread

Message-ID: <200501171159.24797.postgresql@holovaty.com>
Permalink:  ../200501171159.24797.postgresql@holovaty.com/
Also on:    postgresql.org/message-id/200501171159.24797.postgresql@holovaty.com

 · 

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 using the --to and --cc options:
  reply via email

  To: pgsql-performance@postgresql.org
  Cc: postgresql@holovaty.com
  Subject: Re: Index on a function and SELECT DISTINCT
  In-Reply-To: <200501171159.24797.postgresql@holovaty.com>

* 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