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 1fzjK1-0001f1-HY for pgsql-general@arkaria.postgresql.org; Tue, 11 Sep 2018 14:07:17 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1fzjJz-0001y2-L3 for pgsql-general@arkaria.postgresql.org; Tue, 11 Sep 2018 14:07:15 +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 1fzjJz-0001xv-DC for pgsql-general@lists.postgresql.org; Tue, 11 Sep 2018 14:07:15 +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 1fzjJv-0002AB-P8 for pgsql-general@postgresql.org; Tue, 11 Sep 2018 14:07:14 +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 w8BE78CO021079; Tue, 11 Sep 2018 10:07:08 -0400 From: Tom Lane To: Arup Rakshit cc: pgsql-general@postgresql.org Subject: Re: Why order by column not using index with distinct keyword in select clause? In-reply-to: <9B9E43A3-5FA7-4FF4-8444-73C24DEE4107@zeit.io> References: <9B9E43A3-5FA7-4FF4-8444-73C24DEE4107@zeit.io> Comments: In-reply-to Arup Rakshit message dated "Tue, 11 Sep 2018 18:26:34 +0530" MIME-Version: 1.0 Content-Type: text/plain; charset="UTF-8" Content-ID: <21077.1536674828.1@sss.pgh.pa.us> Content-Transfer-Encoding: quoted-printable Date: Tue, 11 Sep 2018 10:07:08 -0400 Message-ID: <21078.1536674828@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk Arup Rakshit writes: > I have define a simple B Tree index on column *country* for users table.= I don=E2=80=99t understand why the order by column not using the index sc= an when using *distinct* keyword in the select clause. Can anyone explain = what is happening here? Doesn't look complicated to me: the cost of the hashagg+sort plan is 283.85, while the cost of the indexscan plans is 886.27, and adding a Uniq node on top of them would have been even more. The critical point here seems to be that the hashagg node is able to get rid of so many rows that the cost of sorting what remains is low. Also notable is that the IOS isn't giving you any advantage over a plain indexscan, which apparently is because none of the table's pages are marked all-visible. If the table is static then a VACUUM would help that. regards, tom lane