Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1ZkwL9-00060R-Q6 for pgsql-performance@arkaria.postgresql.org; Sat, 10 Oct 2015 15:45:43 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84) (envelope-from ) id 1ZkwL9-0007if-A9 for pgsql-performance@arkaria.postgresql.org; Sat, 10 Oct 2015 15:45:43 +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.84) (envelope-from ) id 1ZkwL7-0007iS-Np for pgsql-performance@postgresql.org; Sat, 10 Oct 2015 15:45:41 +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.84) (envelope-from ) id 1ZkwL4-0005Um-T3 for pgsql-performance@postgresql.org; Sat, 10 Oct 2015 15:45:41 +0000 Received: from pro.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id t9AFja59027926; Sat, 10 Oct 2015 11:45:36 -0400 From: Tom Lane To: Marcio Ribeiro cc: pgsql-performance@postgresql.org Subject: Re: LIMIT 1 poor query plan In-reply-to: References: Comments: In-reply-to Marcio Ribeiro message dated "Sat, 10 Oct 2015 05:52:35 -0300" Date: Sat, 10 Oct 2015 10:45:36 -0500 Message-ID: <48410.1444491936@sss.pgh.pa.us> X-Pg-Spam-Score: -1.9 (-) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-performance Precedence: bulk Sender: pgsql-performance-owner@postgresql.org Marcio Ribeiro writes: > Short question: > Why would pg optimizer choose a worst (slower) query plan for a > query with 'LIMIT 1' instead of, say, 'LIMIT 3'? > Complete scenario: > Query: 'SELECT * FROM a WHERE a.b_id = 42 ORDER BY created LIMIT 1' > - b_id is a FK to b; > - created is a datetime with the time of the creation of the row; > - both 'b' and 'created' are indexed separately > This query, with the LIMIT 1, uses the index on created, which is much > slower (10x) than if it used the index on b_id It's trying to avoid a sort; or to be less anthropomorphic, the estimated cost of scanning the "created" index until it hits the first row with b_id=42 is less than the estimated cost of collecting all the rows with b_id=42 and then sorting them by "created". The estimates unfortunately are kind of shaky because it's hard to predict how many rows will get skipped before finding one with b_id=42. If you do this type of query often enough to care about its performance, you could consider creating a two-column index on (b_id, created) (in that order). regards, tom lane -- Sent via pgsql-performance mailing list (pgsql-performance@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-performance