Received: from mail.gmx.net (mail.gmx.net [213.165.64.20]) by postgresql.org (8.11.3/8.11.4) with SMTP id fA8JJTm14075 for ; Thu, 8 Nov 2001 14:19:29 -0500 (EST) (envelope-from cniesen@gmx.net) Received: (qmail 1998 invoked by uid 0); 8 Nov 2001 19:19:29 -0000 Received: from pc79088.adp.iastate.edu (HELO D8VGHK.gmx.net) (129.186.79.88) by mail.gmx.net (mp003-rz3) with SMTP; 8 Nov 2001 19:19:29 -0000 Message-Id: <5.1.0.14.2.20011108122508.00ae2350@pop.gmx.net> X-Sender: 196541@pop.gmx.net X-Mailer: QUALCOMM Windows Eudora Version 5.1 Date: Thu, 08 Nov 2001 13:19:25 -0600 To: "Josh Berkus" From: Claus Heiko Niesen Subject: Re: Can this query be optimized? Cc: pgsql-sql@postgresql.org In-Reply-To: References: <16760.1005229805@sss.pgh.pa.us> Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii"; format=flowed X-Archive-Number: 200111/135 X-Sequence-Number: 5519 At 10:49 AM 11/08/2001, Josh wrote: >Claus, > > > > I'm stuck optimizing the following query: > > > select distinct extract(year from date) as year, extract(month from > > date) > > > as month, date from week_pics order by date desc; > > > > Perhaps it would work to forget the "distinct" and instead GROUP BY > > date. > >Also, do the following: >-- Make sure you have an index on week_pics.date Yes I do have one where the date is the first key of the index. But since I only extract partial data from the index column postgresql seems to ignore the index. Probably to difficult for it to see that the index is in the extract(year from date), extract(month from date) order. >-- Build the above query as a VIEW, which should improve performance >somewhat. What's the secret about the improved performance. Is it just that the query access plan doesn't have to be determined every time the query is executed or is there something else? >Technically, you could build an index on extract(month from date), I >believe, but I'm not sure how effective such an index would be in >practice. I just tried to build an index to see what the explain path would do but I get an error on the word extract: # create index week_pics_month_key on week_pics (extract(year from time_stamp), extract(month from time_stamp)); ERROR: parser: parse error at or near "extract" >-Josh Thanks for the help Josh Claus PS: Accidently I had also the date column selected in the query that I posted. This was incorrect and the query should have been: select distinct extract(year from date) as year, extract(month from date) as month from week_pics order by year desc, month desc;