X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id DDC8C3A3D58 for ; Mon, 17 Jan 2005 16:08:22 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 19503-04 for ; Mon, 17 Jan 2005 16:08:08 +0000 (GMT) Received: from frank.wiles.org (frank.wiles.org [24.124.39.75]) by svr1.postgresql.org (Postfix) with ESMTP id 62B573A3D32 for ; Mon, 17 Jan 2005 16:08:07 +0000 (GMT) Received: from kungfu (frank.wiles.org [127.0.0.1]) by frank.wiles.org (8.13.1/8.13.1) with SMTP id j0HG8uYf032346; Mon, 17 Jan 2005 10:08:56 -0600 Date: Mon, 17 Jan 2005 10:09:42 -0600 From: Frank Wiles To: Adrian Holovaty Cc: pgsql-performance@postgresql.org Subject: Re: Index on a function and SELECT DISTINCT Message-Id: <20050117100942.692be97a.frank@wiles.org> In-Reply-To: <200501141232.13139.postgresql@holovaty.com> References: <200501141232.13139.postgresql@holovaty.com> X-Mailer: Sylpheed version 0.9.10 (GTK+ 1.2.10; i386-redhat-linux-gnu) Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0 tagged_above=0 required=5 tests= X-Spam-Level: X-Archive-Number: 200501/202 X-Sequence-Number: 9892 On Fri, 14 Jan 2005 12:32:12 -0600 Adrian Holovaty 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. :) --------------------------------- Frank Wiles http://www.wiles.org ---------------------------------