Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1sADAD-008FYY-VO for pgsql-bugs@arkaria.postgresql.org; Thu, 23 May 2024 18:27:43 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.94.2) (envelope-from ) id 1sADAE-00FASo-2h for pgsql-bugs@arkaria.postgresql.org; Thu, 23 May 2024 18:27:42 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1sAD8o-00F6qb-Cx for pgsql-bugs@lists.postgresql.org; Thu, 23 May 2024 18:26:14 +0000 Received: from sss.pgh.pa.us ([68.162.161.243]) by magus.postgresql.org with esmtps (TLS1.3) tls TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (Exim 4.94.2) (envelope-from ) id 1sAD8l-000Pzd-OU for pgsql-bugs@lists.postgresql.org; Thu, 23 May 2024 18:26:13 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.15.2/8.15.2) with ESMTP id 44NIQAFW375312; Thu, 23 May 2024 14:26:10 -0400 From: Tom Lane To: alexander.berezin3000@gmail.com cc: pgsql-bugs@lists.postgresql.org Subject: Re: BUG #18477: A specific SQL query with "ORDER BY ... NULLS FIRST" is performing poorly if an ordering column is n In-reply-to: <18477-55fd294f03d66632@postgresql.org> References: <18477-55fd294f03d66632@postgresql.org> Comments: In-reply-to PG Bug reporting form message dated "Thu, 23 May 2024 17:34:12 -0000" MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-ID: <375310.1716488770.1@sss.pgh.pa.us> Date: Thu, 23 May 2024 14:26:10 -0400 Message-ID: <375311.1716488770@sss.pgh.pa.us> List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk PG Bug reporting form writes: > A specific SQL query with "ORDER BY ... NULLS FIRST" is performing poorly if > an ordering column is not nullable. The reason it's performing poorly is that ORDER BY updated_at NULLS FIRST is not compatible with the sort order of your index (which is, by default, NULLS LAST). So the query has to be done with an explicit sort, which requires reading the whole table. I know you are going to say that it shouldn't matter as long as the column is marked NOT NULL, but too bad: it does. This is not a bug, and it's not something we're likely to expend a great deal of sweat on improving. If you know the column is null-free, why are you writing NULLS FIRST? If you have a good reason to write NULLS FIRST, why not declare the index to match? regards, tom lane