Received: from localhost (unknown [200.46.204.184]) by postgresql.org (Postfix) with ESMTP id 309809F95B5 for ; Mon, 5 Nov 2007 11:01:07 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.184]) (amavisd-maia, port 10024) with ESMTP id 49389-05 for ; Mon, 5 Nov 2007 11:00:54 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey-1.7.5 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id 6C1389F959C for ; Mon, 5 Nov 2007 11:01:02 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.1/8.14.1) with ESMTP id lA5F0rjB019504; Mon, 5 Nov 2007 10:00:53 -0500 (EST) To: Andreas Joseph Krogh cc: pgsql-sql@postgresql.org Subject: Re: Returning the total number of rows as a separate column when using limit In-reply-to: <200711051538.34536.andreak@officenet.no> References: <200711050836.38130.andreak@officenet.no> <18728.1194272302@sss.pgh.pa.us> <200711051538.34536.andreak@officenet.no> Comments: In-reply-to Andreas Joseph Krogh message dated "Mon, 05 Nov 2007 15:38:34 +0100" Date: Mon, 05 Nov 2007 10:00:53 -0500 Message-ID: <19503.1194274853@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200711/14 X-Sequence-Number: 29542 Andreas Joseph Krogh writes: > On Monday 05 November 2007 15:18:22 Tom Lane wrote: >> That's only an estimate. Since the query doesn't get executed to >> completion thanks to the LIMIT, Postgres really has no idea whether >> the estimate is accurate. > Ok. The query is ORDER-ed, but you're saying that it doesn't matter and PG > still doesn't have to know the total numbers even if it has to sort the > result? If there were a sort then the sort node would know how many rows it had sorted, but if you've got a small limit that's certainly not the plan type you'd prefer. The bottom line is that there is no free lunch. If you want an exact row count you have to execute the whole query, and it's gonna cost you. If you're willing to settle for an approximation, the usual thing is to EXPLAIN the query and dredge the row estimate out of that. create function estimate_rows(qry text) returns float8 as $$ declare r text; begin for r in execute 'explain ' || qry loop if substring(r from 'rows=[0-9]') is not null then return substring(r from 'rows=([0-9]+)'); end if; end loop; return null; end$$ language plpgsql strict; regards, tom lane