Received: from maia.hub.org (maia-4.hub.org [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 679EE634927 for ; Mon, 26 Apr 2010 15:23:57 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 50690-01-2 for ; Mon, 26 Apr 2010 18:23:41 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id 697E76352F8 for ; Mon, 26 Apr 2010 13:51:34 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id o3QGpWxM005253; Mon, 26 Apr 2010 12:51:32 -0400 (EDT) To: =?KOI8-R?B?68/Sz9TLz9cg4czFy9PBzsTS?= cc: pgsql-performance@postgresql.org Subject: Re: Planner issue on sorting joining of two tables with limit In-reply-to: References: Comments: In-reply-to =?KOI8-R?B?68/Sz9TLz9cg4czFy9PBzsTS?= message dated "Sun, 25 Apr 2010 22:22:29 +0400" Date: Mon, 26 Apr 2010 12:51:32 -0400 Message-ID: <5252.1272300692@sss.pgh.pa.us> From: Tom Lane 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: 201004/318 X-Sequence-Number: 38568 =?KOI8-R?B?68/Sz9TLz9cg4czFy9PBzsTS?= writes: > So PostgreSQL planner can produce the plan I need but it doesn't produce > this plan when I specify particular second ordering column. Well, no, because that plan wouldn't produce the specified ordering; or at least it would be a lucky coincidence if it did. It's only sorting on t1.value. > So is there any > way to make planner produce desired plan when particular second ordering > column is specified? Not when the ordering columns come from two different tables. (If they were in the same table then scanning a two-column index could produce the demanded sort order.) I don't see any way to satisfy this query without an explicit sort step, which means it has to look at the whole join output. If you're willing to make assumptions like "the required 10 rows will be within the first 100 t1.value rows" then you could nest an ORDER BY t1.value LIMIT 100 query inside something that did an ORDER BY with both columns. But this fails if you have too many duplicate t1.value values, and your test case suggests that you might have a lot of them. In any case it would stop being fast if you make the inner LIMIT very large. regards, tom lane