Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 1779EB5DBD0 for ; Tue, 5 Jul 2011 21:27:49 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 32606-03 for ; Wed, 6 Jul 2011 00:27:42 +0000 (UTC) X-Greylist: delayed 00:09:24.061844 by SQLgrey-1.7.6 Received: from mail.kc8onw.net (kc8onw.net [206.55.209.81]) by mail.postgresql.org (Postfix) with ESMTP id 6845CB5DC14 for ; Tue, 5 Jul 2011 21:27:42 -0300 (ADT) Received: from [10.70.3.2] (c-98-223-39-129.hsd1.in.comcast.net [98.223.39.129]) by mail.kc8onw.net (Postfix) with ESMTPSA id 1EBF4A130A for ; Tue, 5 Jul 2011 20:18:17 -0400 (EDT) Message-ID: <4E13A9C2.9000906@kc8onw.net> Date: Tue, 05 Jul 2011 20:18:10 -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: Slow query when using ORDER BY *and* LIMIT 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/17 X-Sequence-Number: 44229 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. Thanks, Jonathan