Received: from localhost (maia-3.hub.org [200.46.204.184]) by postgresql.org (Postfix) with ESMTP id 8DDCD9FB615 for ; Sat, 28 Jul 2007 16:58:21 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.184]) (amavisd-maia, port 10024) with ESMTP id 57390-04 for ; Sat, 28 Jul 2007 16:58:06 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from mail.emolecules.com (66-226-76-106.dedicated.abac.net [66.226.76.106]) by postgresql.org (Postfix) with ESMTP id 62DC59FB5AD for ; Sat, 28 Jul 2007 16:58:18 -0300 (ADT) Received: (qmail 3626 invoked by uid 2020); 28 Jul 2007 12:58:42 -0700 Received: from wsip-68-224-174-233.sd.sd.cox.net (HELO ?192.168.0.3?) (68.224.174.233) by 192.168.0.4 with SMTP; 28 Jul 2007 12:58:42 -0700 Message-ID: <46ABA1AA.7020701@emolecules.com> Date: Sat, 28 Jul 2007 13:06:02 -0700 From: Craig James User-Agent: Thunderbird 1.5.0.12 (X11/20070509) MIME-Version: 1.0 To: Tilmann Singer CC: andrew@pillette.com, pgsql-performance@postgresql.org Subject: Re: Slow query with backwards index scan References: <200707281903.l6SJ3qs07818@pillette.com> <20070728192713.GH19392@tils.net> In-Reply-To: <20070728192713.GH19392@tils.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=0.226 tagged_above=0 required=5 tests=AWL=0.125, BAYES_50=0.001, RDNS_DYNAMIC=0.1 X-Spam-Level: X-Archive-Number: 200707/401 X-Sequence-Number: 26085 Tilmann Singer wrote: > * andrew@pillette.com [20070728 21:05]: >> Let's try putting the sort/limit in each piece of the UNION to speed them up separately. >> >> SELECT * FROM ( >> (SELECT * FROM large_table lt >> WHERE lt.user_id = 12345 >> ORDER BY created_at DESC LIMIT 10) AS q1 >> UNION >> (SELECT * FROM large_table lt >> WHERE user_id IN (SELECT contact_id FROM relationships WHERE user_id=12345) >> ORDER BY created_at DESC LIMIT 10) AS q2 >> ORDER BY created_at DESC LIMIT 10; > > It's not possible to use ORDER BY or LIMIT within unioned queries. > > http://www.postgresql.org/docs/8.2/static/sql-select.html#SQL-UNION If I'm reading this documentation correctly, it *is* possible, as long as they're inside of a sub-select, as in this case. Craig