Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id 8F3CFB5DC24 for ; Fri, 8 Jul 2011 19:24:18 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 20538-08 for ; Fri, 8 Jul 2011 22:24:12 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from mail.kc8onw.net (kc8onw.net [206.55.209.81]) by mail.postgresql.org (Postfix) with ESMTP id 233DDB5DBC1 for ; Fri, 8 Jul 2011 19:24:11 -0300 (ADT) Received: from [10.70.3.3] (c-98-223-39-129.hsd1.in.comcast.net [98.223.39.129]) by mail.kc8onw.net (Postfix) with ESMTPSA id 3B414107DDB for ; Fri, 8 Jul 2011 18:24:10 -0400 (EDT) Message-ID: <4E17836D.9070201@kc8onw.net> Date: Fri, 08 Jul 2011 18:23:41 -0400 From: Jonathan User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:5.0) Gecko/20110624 Thunderbird/5.0 MIME-Version: 1.0 To: pgsql-performance@postgresql.org Subject: Re: Slow query when using ORDER BY *and* LIMIT References: <4E13A9C2.9000906@kc8onw.net> In-Reply-To: <4E13A9C2.9000906@kc8onw.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201107/48 X-Sequence-Number: 44260 Does anyone have any suggestions for my problem? (I have to wonder if I'm somehow just not getting peoples attention or what. This is my second question this week on a public mailing list that has gotten exactly 0 replies) Jonathan On 7/5/2011 8:18 PM, Jonathan wrote: > I have a query that uses ORDER BY and LIMIT to get a set of image data > rows that match a given tag. When both ORDER BY and LIMIT are included > for some reason the planner chooses a very slow query plan. Dropping one > or the other results in a much faster query going from 4+ seconds -> 30 > ms. Database schema, EXPLAIN ANALYZE and other information can be found > at http://pgsql.privatepaste.com/31113c27bf Is there a way to convince > the planner to use the faster plan when doing both ORDER BY and LIMIT > without using SET options or will I need to disable the slow plan > options to force the planner to use the fast plan? > > I found some stuff in the mailing list archives that looks related but I > didn't see any fixes. Apparently the planner hopes the merge join will > find the LIMIT # of rows fairly quickly but instead it winds up scanning > almost the entire table.