Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1dqQSI-0005Kt-CK for pgsql-bugs@arkaria.postgresql.org; Fri, 08 Sep 2017 21:04:50 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84_2) (envelope-from ) id 1dqQSH-00024z-Tp for pgsql-bugs@arkaria.postgresql.org; Fri, 08 Sep 2017 21:04:49 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1dqQSH-00024J-1l for pgsql-bugs@postgresql.org; Fri, 08 Sep 2017 21:04:49 +0000 Received: from hogranch.com ([75.101.82.47]) by makus.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1dqQSB-0008Oc-S7 for pgsql-bugs@postgresql.org; Fri, 08 Sep 2017 21:04:47 +0000 Received: from [192.168.0.2] (porker [192.168.0.2]) by hogranch.com (8.11.6/8.11.6) with ESMTP id v88L4aN18696 for ; Fri, 8 Sep 2017 14:04:36 -0700 Subject: Re: Query with "LIMIT 1" 10x slower than without LIMIT To: pgsql-bugs@postgresql.org References: From: John R Pierce Message-ID: Date: Fri, 8 Sep 2017 14:04:31 -0700 User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Thunderbird/52.3.0 MIME-Version: 1.0 In-Reply-To: Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 8bit Content-Language: en-US X-HawgScanner-Information: Please contact the ISP for more information X-HawgScanner: Found to be clean List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-bugs Precedence: bulk Sender: pgsql-bugs-owner@postgresql.org On 9/8/2017 1:10 PM, Aaron Tate wrote: > We have a number of queries that do a lot of summarization of data. > The base query only returns one row, but due to a Rails quirk, we have > to call rel.first to get the first (only) element of the list, which > in some cases uses a "LIMIT 1" for the underlying query. With or > without the LIMIT 1, the results are identical, but with the LIMIT 1, > a 400ms query might take 5000ms to execute. > > Please note that this does occur on PostgreSQL version 9.6.1, on Linux > or OSX. We can certainly work around it if we're mindful of it, but > it's a surprising "gotcha". 1) To make any sense of this would require seeing the actual queries, along with the schema. 2) A better way of doing that 'rel.first' thing in the general case would be a query that returns a cursor, then reading the first row from the cursor, then the whole thing.  of course, you're stuck with whatever the ORM (Rails) wants to do, so you probably have no option on this. -- john r pierce, recycling bits in santa cruz -- Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-bugs