From: Tom Lane <tgl@sss.pgh.pa.us>
To: Andreas Joseph Krogh <andreak@officenet.no>
Cc: pgsql-sql@postgresql.org
Subject: Re: Returning the total number of rows as a separate column when using limit
Date: Mon, 05 Nov 2007 10:00:53 -0500
Message-ID: <19503.1194274853@sss.pgh.pa.us> (raw)
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>
Andreas Joseph Krogh <andreak@officenet.no> 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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: tgl@sss.pgh.pa.us, andreak@officenet.no
Subject: Re: Returning the total number of rows as a separate column when using limit
In-Reply-To: <19503.1194274853@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox