Re: Returning the total number of rows as a separate column when using limit - Mailing list pgsql-sql

From Tom Lane
Subject Re: Returning the total number of rows as a separate column when using limit
Date
Msg-id 19503.1194274853@sss.pgh.pa.us
Whole thread Raw
In response to Re: Returning the total number of rows as a separate column when using limit  (Andreas Joseph Krogh <andreak@officenet.no>)
Responses Re: Returning the total number of rows as a separate column when using limit
List pgsql-sql
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(rfrom 'rows=([0-9]+)');   end if; end loop; return null;
 
end$$ language plpgsql strict;
        regards, tom lane


pgsql-sql by date:

Previous
From: Andreas Joseph Krogh
Date:
Subject: Re: Returning the total number of rows as a separate column when using limit
Next
From: Ehab Galal
Date:
Subject: Re: omitting redundant join predicate