Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1muIFZ-0002rE-6l for pgsql-general@arkaria.postgresql.org; Mon, 06 Dec 2021 17:58:05 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.92) (envelope-from ) id 1muIFX-0004T0-Md for pgsql-general@arkaria.postgresql.org; Mon, 06 Dec 2021 17:58:03 +0000 Received: from makus.postgresql.org ([2001:4800:3e1:1::229]) by malur.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1muIFX-0004So-3G for pgsql-general@lists.postgresql.org; Mon, 06 Dec 2021 17:58:03 +0000 Received: from outbound2o.ore.mailhop.org ([54.187.213.119]) by makus.postgresql.org with esmtps (TLS1.3:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.92) (envelope-from ) id 1muIFU-0000q8-1m for pgsql-general@postgresql.org; Mon, 06 Dec 2021 17:58:02 +0000 ARC-Seal: i=1; a=rsa-sha256; t=1638813479; cv=none; d=outbound.mailhop.org; s=arc-outbound20181012; b=jkyUmPbO0RGxPn3/fZckUCUgW0OvcYz/dBL8xIlMSmGi1WTWoY9I0saU+DLBy8fDQzcrhKOmrUM6+ +gIMJ0zMQJUk4hGqG1Wz9fX1aT03+2iqpd2DZaerOntYc8XW7sf5QBhM+EfsnuDVe2xbjUVQ2g/ZcN VBBDLhD+GJkb+7gwfEcOOFZRfYObHfFDj9OApB5WwFyR3eBB4UzsJ6Ve69rM4XgCbS7fqFKtE0/t8p DJnuJnKP7DCRPbU9OdjU4qEBtKiXS7jDYASxJFGDY9ew7npe8DJXakVohR6Bjf2htO7Nr56/GKflZF cxsxHZZ1xN6CsZ7gY7cCDdfdH4mxJ7g== ARC-Message-Signature: i=1; a=rsa-sha256; c=relaxed/relaxed; d=outbound.mailhop.org; s=arc-outbound20181012; h=mime-version:content-type:references:in-reply-to:date:to:from:subject: message-id:dkim-signature:dkim-signature:dkim-signature:from; bh=txUeEMmZkziKlDJiUdMih53fl0yBPkPdV2TXvP4zf5E=; b=oQbPjcFdd2ZGbexdufNRsqmmwuPo5mZqppaiEEybXi+TMH7Fx9h7Cmk/dzZWKmWyPyUycTrdMDeBj iQJRTT3OHjuqvleI5LhwZr/yanZ3RIiPwnpPgKzltfgbS/YaAxAvRw9eFahPFs4OkRYmNM2kvdeZnJ COrVsUBkRzfl4DmSFMGAlxj8ImQYzcDTxLBC5xkphYdm9z4s/gZk3emjj5HbZFLdHlFSXVuX9Ip9lv pscZYar6v8M8ro0E/jOLk2ah16oASWxPNWHBUZdovFonh//UO22VKywRFDnDdRHvjC5uJ8RXQj8eEa qpcoNxqYE57Mo+lvxKbdBs/aYLysgIQ== ARC-Authentication-Results: i=1; outbound4.ore.mailhop.org; spf=pass smtp.mailfrom=lists.simkin.ca smtp.remote-ip=172.105.109.24; dkim=pass header.d=lists.simkin.ca header.s=athena header.a=rsa-sha256 header.b=s5VcJ5pg; dmarc=pass header.from=lists.simkin.ca; arc=none header.oldest-pass=0; DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=lists.simkin.ca; s=duo-1610662143981-d3c4c825; h=mime-version:content-type:references:in-reply-to:date:to:from:subject: message-id:from; bh=txUeEMmZkziKlDJiUdMih53fl0yBPkPdV2TXvP4zf5E=; b=Mn/Hu3jUAD5hbXxZYqb5Qm8xMCNbNfWvXTQlN3hsBlRYinpGL3mw+YveCEqPI6CB7CIzSCt70Txl9 KHm7efG5uoW4/giKGK0PW0Y5TUYAUtOxicyQnTD5k8wMiCMjM1VlL5gEcsYaXA3FE6EyJq4VpGiJS4 JTvcwdgA/1ilytLs= DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=outbound.mailhop.org; s=dkim-high; h=mime-version:content-type:references:in-reply-to:date:to:from:subject: message-id:from; bh=txUeEMmZkziKlDJiUdMih53fl0yBPkPdV2TXvP4zf5E=; b=ijgHObFx2dGMhx9vd/KqdYXEvaZGLo9+35Hja+IxeXdUTRLlNwd6Jn/MOOcXkkE7aQzLiloiBRDHy /r1j6ciEl76e0Tdk99PErBW0DlVB9ePKmtdOUukKkbvm+I2Z7E22T63aj24MVDoVgHxTGp5Uxov/us aQN+bJ+1BMiNctfWNPZxvvZhrJk8bwqWLuZ1JbCiAfoonz0Ou2X2Jh1Xn89Oy866LiewTpn3x6bDwB g+9cMnT+/1XgEMbtvEFi8THWrH5nQg7QiOjhBNjCvOA/t6pe+VCCwCLAXwxb8/6xZYTs/z6Wzt4Qcb bCcf0YJdqlqf+atySnUiFAIbdb024Kg== X-Originating-IP: 172.105.109.24 X-MHO-RoutePath: c2lta2lu X-MHO-User: 0ac087d6-56be-11ec-a681-89389772cfc7 X-Report-Abuse-To: https://support.duocircle.com/support/solutions/articles/5000540958-duocircle-standard-smtp-abuse-information X-Mail-Handler: DuoCircle Outbound SMTP Received: from athena.simkin.ca (athena.simkin.ca [172.105.109.24]) by outbound4.ore.mailhop.org (Halon) with ESMTPSA id 0ac087d6-56be-11ec-a681-89389772cfc7; Mon, 06 Dec 2021 17:57:58 +0000 (UTC) Received: from skynet.simkin.ca (node-1w7jr9sr73xr4ze19xwgjcteu.ipv6.telus.net [IPv6:2001:569:bce0:6400:fa75:a4ff:fe2f:92e6]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature ECDSA (P-384)) (No client certificate requested) by athena.simkin.ca (Postfix) with ESMTPSA id 5AF7AC6A13DB for ; Mon, 6 Dec 2021 09:57:55 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=lists.simkin.ca; s=athena; t=1638813475; bh=yC4ccNmOrrfjup7Dvadvv8m1O30BCl0gYJf3aftkaaM=; h=Subject:From:To:Date:From:To:Subject:Date:Reply-To; b=s5VcJ5pgFlpnILo6QwrjEMj/4w6IRRzV4SHWAGPnfNUmq61BrmAh6ZjK8UB2mdzSk kXqeYToVHJwLu9vJRZnro1F8JHWcczrWOuJNVUX1/PJdMj5nrxnRuP5B29gPIK6nmm N5oOzm3ex5mQHXSW2HTcm8fXf5YavDgLiOtjfLDRMpBvXl5E90ffSQ/0PPpM9yEZOy 4OuE9MdWjoimQO9DYUYViUBwTRId47Dxii5DIkF7AdfoGNm7w98fXOIMWGt6A+2cGE 7Q4A8XD9JEkYIpIOR2brpUbD18fZ4x0yK/vJnOTFuj9cW2HmxTDEofBdKWuH47clpX AduHXOSC75F+A== Received: from skynet.simkin.ca (skynet.simkin.ca [IPv6:::1]) by skynet.simkin.ca (Postfix) with ESMTP id 264D6105B1B00 for ; Mon, 6 Dec 2021 09:57:53 -0800 (PST) Message-ID: Subject: Re: Query planner issue with preferring primary key over a better index when using ORDER BY and LIMIT From: Alan Hodgson To: Postgres General Date: Mon, 06 Dec 2021 09:57:53 -0800 In-Reply-To: References: Content-Type: multipart/alternative; boundary="=-np2AHl9TwsjMuAz0FC0N" X-PGP-Key: fp="EF82 6F8D A3BA A096 FFA3 05F2 A7A0 40A5 34E5 AA0B"; id="0x34E5AA0B"; get= User-Agent: Evolution 3.40.4 MIME-Version: 1.0 List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Archived-At: Precedence: bulk --=-np2AHl9TwsjMuAz0FC0N Content-Type: text/plain; charset="ISO-8859-15" Content-Transfer-Encoding: 8bit On Mon, 2021-12-06 at 18:20 +0100, Francisco Olarte wrote: > > Can you post an explain analyze? To me it seems like the planner > thinks shipment_import_id is randomly distributed and the table is > well correlated with it's PK, so scanning it for the first id > should > be fast.    #explain analyze SELECT "shipment_import_records".* FROM     shipment_import_records" WHERE     shipment_import_records"."shipment_import_id" = 5090609 ORDER BY    "shipment_import_records"."id" ASC LIMIT 1;    ------------------------------------------------------------------ ---    ------------------------------------------------------------------ ---    -------------------------------------     Limit  (cost=0.44..873.08 rows=1 width=243) (actual    time=31689.725..31689.726 rows=1 loops=1)       ->  Index Scan using shipment_import_records_pkey on    shipment_import_records  (cost=0.44..5122405.71 rows=5870 width=243)    (actual time=31689.723..31689.724 rows=1 loops=1)             Filter: (shipment_import_id = 5090609)             Rows Removed by Filter: 28710802     Planning Time: 0.994 ms     Execution Time: 31689.744 ms    (6 rows)       The biggest one (but yes "earlier"): # explain analyze SELECT "shipment_import_records".* FROM "shipment_import_records" WHERE "shipment_import_records"."shipment_import_id" = 1247888 ORDER BY "shipment_import_records"."id" ASC LIMIT 1;                                                                                    QUERY PLAN                                                                                     --------------------------------------------------------------------- --------------------------------------------------------------------- ---------------------------- -------- Limit  (cost=0.44..426.59 rows=1 width=243) (actual time=8007.069..8007.070 rows=1 loops=1)   ->  Index Scan using shipment_import_records_pkey on shipment_import_records  (cost=0.44..5126628.40 rows=12030 width=243) (actual time=8007.068..8007.068 rows=1 l oops=1)         Filter: (shipment_import_id = 1247888)         Rows Removed by Filter: 10929193 Planning Time: 0.584 ms Execution Time: 8007.086 ms (6 rows) And the smallest/latest, which actually uses the "right" index:  # explain analyze SELECT "shipment_import_records".* FROM "shipment_import_records" WHERE "shipment_import_records"."shipment_import_id" = 5116174 ORDER BY  "shipment_import_records"."id" ASC LIMIT 1;                                                                                         QUERY PLAN                                                                                            --------------------------------------------------------------------- --------------------------------------------------------------------- ---------------------------- ------------------------ Limit  (cost=145.44..145.44 rows=1 width=243) (actual time=0.018..0.018 rows=1 loops=1)   ->  Sort  (cost=145.44..145.64 rows=79 width=243) (actual time=0.017..0.018 rows=1 loops=1)         Sort Key: id         Sort Method: quicksort  Memory: 26kB         ->  Index Scan using index_shipment_import_records_on_shipment_import_id on shipment_import_records  (cost=0.44..145.05 rows=79 width=243) (actual time=0.013 ..0.014 rows=1 loops=1)               Index Cond: (shipment_import_id = 5116174) Planning Time: 0.104 ms Execution Time: 0.032 ms (8 rows) > > But from the names of the field you may have correlation between > shipment_import_id and id hidden somewhere ( like they are two > serial > growing together, you query for the latest shipment ids and it > scans > all the table ). An explain analyze should show that ( or three, > one > for that shipment import id, one for 1, one for a really big one ) This is definitely the case. And we are generally looking for newer data for most operations. Thanks for looking at it. --=-np2AHl9TwsjMuAz0FC0N Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: quoted-printable
On Mon, 2021-12-06 at 18:20 +0100, Francisco = Olarte wrote:

Can you p= ost an explain analyze? To me it seems like the planner
thinks sh= ipment_import_id is randomly distributed and the table is
well co= rrelated with it's PK, so scanning it for the first id should
be = fast.

   shipment_import_records" W= HERE 
   shipment_import_re= cords"."shipment_import_id" =3D 5090609 ORDER BY
   "shipment_import_records"."id" ASC LIMIT 1;
   ----------------------------------------= -----------------------------
  = ---------------------------------------------------------------------
   ---------------------------------= ----
    Limit  (cost= =3D0.44..873.08 rows=3D1 width=3D243) (actual
   time=3D31689.725..31689.726 rows=3D1 loops=3D1)
      ->  Index S= can using shipment_import_records_pkey on
=    shipment_import_records  (cost=3D0.44..5122405.71 rows=3D= 5870 width=3D243)
   (actual tim= e=3D31689.723..31689.724 rows=3D1 loops=3D1)
            Filte= r: (shipment_import_id =3D 5090609)
 =            Rows Removed b= y Filter: 28710802
    Plan= ning Time: 0.994 ms
    Exe= cution Time: 31689.744 ms
   (6 = rows)


=
      The biggest one (but yes "earlier"):
<= div>
# explain analyze SELECT "shipment_import_records".* FR= OM "shipment_import_records" WHERE "shipment_import_records"."shipment_impo= rt_id" =3D 1247888 ORDER BY
"shipment_import_records"."id" ASC LIMIT 1;=  
&nb= sp;                     &= nbsp;                    =                     &nbs= p;                 QUERY PLAN  = ;            &n= bsp;            = ;            &n= bsp;            = ;            &n= bsp;         
  =       
-----------------------------------= ---------------------------------------------------------------------------= --------------------------------------------------------
--------
Limit  (cost=3D0.44..426.59 rows=3D1 width=3D243) (actual time=3D= 8007.069..8007.070 rows=3D1 loops=3D1)
  ->  Index Scan using shipment_import_records_pkey = on shipment_import_records  (cost=3D0.44..5126628.40 rows=3D12030 widt= h=3D243) (actual time=3D8007.068..8007.068 rows=3D1 l
oops=3D1)
        Filter: (shipment_impo= rt_id =3D 1247888)
        Rows Removed by Filter= : 10929193
Planning Time: 0.584 ms
Execution Time: 8007.086 ms
(6 rows)


And the smallest/latest, which actuall= y uses the "right" index:

 # e= xplain analyze SELECT "shipment_import_records".* FROM "shipment_import_rec= ords" WHERE "shipment_import_records"."shipment_import_id" =3D 5116174 ORDE= R BY 
"shipme= nt_import_records"."id" ASC LIMIT 1;      
                 =                      = ;                     &nb= sp;                     &= nbsp;QUERY PLAN           = ;            &n= bsp;            = ;            &n= bsp;            = ;     
      &nb= sp;            =      
-----------------------------------------= ---------------------------------------------------------------------------= --------------------------------------------------
---------------------= ---
Limit  (cost=3D145.44..145.44 rows=3D1 width=3D243) (actual time= =3D0.018..0.018 rows=3D1 loops=3D1)
  ->  Sort  (cost=3D145.44..145.64 rows=3D79 wi= dth=3D243) (actual time=3D0.017..0.018 rows=3D1 loops=3D1)
        Sort Key: id
        Sort Method: quicksort=  Memory: 26kB
        ->  Index Scan= using index_shipment_import_records_on_shipment_import_id on shipment_impo= rt_records  (cost=3D0.44..145.05 rows=3D79 width=3D243) (actual time= =3D0.013
..0.014 rows=3D1 loops=3D1)
           &nbs= p;  Index Cond: (shipment_import_id =3D 5116174)
Planning Time: 0.104 ms
Execution Time: 0.032 ms
(8 rows)


But from the names of the field you may have co= rrelation between
shipment_import_id and id hidden somewhere ( li= ke they are two serial
growing together, you query for the latest= shipment ids and it scans
all the table ). An explain analyze sh= ould show that ( or three, one
for that shipment import id, one f= or 1, one for a really big one )


=
This is definitely the case. And we are generally looking for ne= wer data for most operations.

Thanks for looking a= t it.
--=-np2AHl9TwsjMuAz0FC0N--