Received: from localhost (wm.hub.org [200.46.204.128]) by postgresql.org (Postfix) with ESMTP id D77A69FB336 for ; Wed, 18 Oct 2006 18:07:37 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.128]) (amavisd-new, port 10024) with ESMTP id 94511-01 for ; Wed, 18 Oct 2006 21:07:32 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey- Received: from servata.com (ip-216-152-249-241.servata.com [216.152.249.241]) by postgresql.org (Postfix) with ESMTP id 2CBAA9FB2CC for ; Wed, 18 Oct 2006 18:07:31 -0300 (ADT) Received: from [209.162.219.253] (helo=dogma.v10.wvs) by servata.com with esmtpa (Exim 4.50) id 1GaIdK-0006A0-S7; Wed, 18 Oct 2006 14:07:27 -0700 Subject: Re: Postgresql 8.1.4 - performance issues for select on From: Jeff Davis To: Ioana Danes Cc: pgsql-performance@postgresql.org In-Reply-To: <20061018195134.72985.qmail@web55902.mail.re3.yahoo.com> References: <20061018195134.72985.qmail@web55902.mail.re3.yahoo.com> Content-Type: text/plain Date: Wed, 18 Oct 2006 14:07:28 -0700 Message-Id: <1161205648.31645.262.camel@dogma.v10.wvs> Mime-Version: 1.0 X-Mailer: Evolution 2.0.4 (2.0.4-7) Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.134 tagged_above=0 required=5 tests=FORGED_RCVD_HELO, SPF_HELO_PASS X-Spam-Level: X-Archive-Number: 200610/375 X-Sequence-Number: 21504 On Wed, 2006-10-18 at 15:51 -0400, Ioana Danes wrote: > Hi everyone, > Testing some selects I know we have in the application > I got into a scenario where my plan does not work > without doing code change. This scenario is: > > select max(transid) from alltransaction; > > because the planner does not use the existent indexes > on the 2 new tables: public.transaction and > archive.transaction > First, the query is expanded into something like (I'm being inexact here): SELECT max(transid) FROM (SELECT * FROM public.transaction UNION SELECT * FROM archive.transaction); PostgreSQL added a hack to the max() aggregate so that, in the simple case, it can recognize that what it really wants to do is use the index. Using the index for an aggregate only works in special cases, like min() and max(). What PostgreSQL actually does is to transform a query from: SELECT max(value) FROM sometable; Into: SELECT value FROM sometable ORDER BY value DESC LIMIT 1; In your case, it would need to transform the query into something more like: SELECT max(transid) FROM ( SELECT transid FROM ( SELECT transid FROM public.transaction ORDER BY transid DESC LIMIT 1 ) t1 UNION SELECT transid FROM ( SELECT transid FROM archive.transaction ORDER BY transid DESC LIMIT 1 ) t2 ) t; The reason for that is because PostgreSQL (apparently) isn't smart enough to do a mergesort on the two indexes to sort the result of the UNION. At least, I can't get PostgreSQL to sort over two UNIONed tables using an index; perhaps I'm missing it. Regards, Jeff Davis