Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id E8424B5DEE9 for ; Wed, 8 Jun 2011 05:34:17 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 76076-01 for ; Wed, 8 Jun 2011 08:34:10 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from mail2.symstream.com (2.102.96.58.static.exetel.com.au [58.96.102.2]) by mail.postgresql.org (Postfix) with ESMTP id 9A5C7B5E068 for ; Wed, 8 Jun 2011 05:34:10 -0300 (ADT) Received: from symstream.com (unknown [192.168.0.254]) by mail2.symstream.com (Postfix) with SMTP id BDEAD6AD06 for ; Wed, 8 Jun 2011 18:34:08 +1000 (EST) Received: (qmail 9979 invoked by uid 453); 8 Jun 2011 08:34:07 -0000 X-Virus-Checked: Checked by ClamAV on symstream.com Received: from Unknown (HELO ajs-desktop.symstream.com) (192.168.0.22) by symstream.com (qpsmtpd/0.40) with ESMTP; Wed, 08 Jun 2011 18:34:07 +1000 From: anthony.shipman@symstream.com To: pgsql-performance@postgresql.org Subject: Re: strange query plan with LIMIT Date: Wed, 8 Jun 2011 18:34:07 +1000 User-Agent: KMail/1.9.4 Cc: Claudio Freire References: <201106071802.08272.anthony.shipman@symstream.com> In-Reply-To: MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Content-Disposition: inline Message-Id: <201106081834.07263.anthony.shipman@symstream.com> X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.9 tagged_above=-10 required=5 tests=BAYES_00=-1.9 X-Spam-Level: X-Archive-Number: 201106/56 X-Sequence-Number: 43989 On Wednesday 08 June 2011 17:39, Claudio Freire wrote: > Of course optimally executing a plan with limit is a lot different > than one without. I imagined that limit just cuts out a slice of the query results. If it can find 80000 rows in 0.5 seconds then I would have thought that returning just the first 100 of them should be just as easy. > > Just... why are you sorting by diag_id? > > I believe you would be better off sorting by timestamp than diag_id, > but I don't know what the query is supposed to do. The timestamp is only almost monotonic. I need to scan the table in slices and I use limit and offset to select the slice. I've forced the query order with some pgsql like: declare query character varying; rec record; begin -- PG 8.3 doesn't have the 'using' syntax nor 'return query execute' execute 'create temporary table tt on commit drop as ' || 'select diag_id from tdiag ' || v_where; query = 'select * from tdiag where diag_id in (select * from tt) ' || 'order by diag_id ' || v_limit || ' ' || v_offset; for rec in execute query loop return next rec; end loop; end; -- Anthony Shipman | Life is the interval Anthony.Shipman@symstream.com | between pay days.