Received: from candle.pha.pa.us (216-55-132-35.dsl.san-diego.abac.net [216.55.132.35]) by postgresql.org (8.11.3/8.11.4) with ESMTP id g1EFgaE95043 for ; Thu, 14 Feb 2002 10:42:36 -0500 (EST) (envelope-from pgman@candle.pha.pa.us) Received: (from pgman@localhost) by candle.pha.pa.us (8.11.6/8.10.1) id g1EFgSV28050; Thu, 14 Feb 2002 10:42:28 -0500 (EST) From: Bruce Momjian Message-Id: <200202141542.g1EFgSV28050@candle.pha.pa.us> Subject: Re: Useless index In-Reply-To: <8617.1013699169@sss.pgh.pa.us> To: Tom Lane Date: Thu, 14 Feb 2002 10:42:28 -0500 (EST) CC: Brian McCane , pg-admin X-Mailer: ELM [version 2.4ME+ PL96 (25)] MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Type: text/plain; charset=US-ASCII X-Archive-Number: 200202/178 X-Sequence-Number: 3334 Tom Lane wrote: > Brian McCane writes: > > CREATE INDEX foo_index ON foo (bazid, score desc) ; > > > Which would be exactly what I want, and would complete in a split second. > > Instead, this thing runs FOREVER (okay, it just seems that way to my > > client :). Is there any way to get the equivalent index from PostgreSQL? > > You don't need a funny index, you just need to get the planner to notice > that that index can serve to create the desired output ordering. Try > > create table foo(bazid int, score int); > CREATE INDEX foo_index ON foo (bazid, score) ; > > explain select * from foo where bazid = 123456 > order by bazid desc, score desc limit 100 ; > > NOTICE: QUERY PLAN: > > Limit (cost=0.00..17.07 rows=5 width=8) > -> Index Scan Backward using foo_index on foo (cost=0.00..17.07 rows=5 width=8) Yes, I suspected it was the mixing of non-DESC and DESC that caused the index to be ignored. The user knows the index can be used because the have specified 'col = constant' but the index doesn't code doesn't have those details. Certainly a case of: col >= 10 AND col <= 11 would not allow a secondary DESC column to be used, while a secondary non-DESC column would be fine. I suppose there is no automatic fix we can do here except to ask users to use matching DESC when they are testing or a constant. In fact, I am unsure why you are specifying the primary column in the ORDER BY anyway if you know it will be a single value, except perhaps to try and get it to use the index, right? -- Bruce Momjian | http://candle.pha.pa.us pgman@candle.pha.pa.us | (610) 853-3000 + If your life is a hard drive, | 830 Blythe Avenue + Christ can be your backup. | Drexel Hill, Pennsylvania 19026