Received: from malur.postgresql.org ([2a02:16a8:dc51::56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fcX58-0000IO-SH for pgsql-performance@arkaria.postgresql.org; Mon, 09 Jul 2018 14:24:03 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1fcX56-0007pA-5s for pgsql-performance@arkaria.postgresql.org; Mon, 09 Jul 2018 14:24:00 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fcX55-0007p2-Uw for pgsql-performance@lists.postgresql.org; Mon, 09 Jul 2018 14:23:59 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fcX4y-0003pj-Bp for pgsql-performance@lists.postgresql.org; Mon, 09 Jul 2018 14:23:59 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id w69ENlUf009716; Mon, 9 Jul 2018 10:23:47 -0400 From: Tom Lane To: Nandakumar M cc: Pgsql Performance Subject: Re: Need help with optimising simple query In-reply-to: References: Comments: In-reply-to Nandakumar M message dated "Mon, 09 Jul 2018 17:17:23 +0530" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <9714.1531146227.1@sss.pgh.pa.us> Date: Mon, 09 Jul 2018 10:23:47 -0400 Message-ID: <9715.1531146227@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Nandakumar M writes: > I am having a query that has an order by and a limit clause. The > column on which I am doing order by is indexed (default b tree index). > However the index is not being used. On tweaking the query a bit I > found that when I use left join index is not used whereas when I use > inner join the index is used. The reason the index isn't being used is that the sort order the query requests isn't the same as the order provided by the index. Here: > performance_test=# explain analyze select * from parent left join > child on parent.child_id = child.id order by child.name limit 10; you're asking to sort by a column that will include null values for child.name anywhere that there's a parent row without a match for child_id. Those rows aren't even represented in the index on child.name, much less placed in the right order. regards, tom lane