X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 4DF9F52935 for ; Tue, 31 May 2005 13:00:29 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 87875-02 for ; Tue, 31 May 2005 16:00:19 +0000 (GMT) Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by svr1.postgresql.org (Postfix) with ESMTP id 9A184528C5 for ; Tue, 31 May 2005 13:00:19 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.13.1/8.13.1) with ESMTP id j4VG0DuN012894; Tue, 31 May 2005 12:00:16 -0400 (EDT) To: Nick Johnson Cc: pgsql-sql@postgresql.org Subject: Re: (Mis)using the PostgreSQL planner to get estimated row counts In-reply-to: References: Comments: In-reply-to Nick Johnson message dated "Wed, 25 May 2005 19:13:25 +1200" Date: Tue, 31 May 2005 12:00:13 -0400 Message-ID: <12893.1117555213@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.006 tagged_above=0 required=5 tests=AWL X-Spam-Level: X-Archive-Number: 200505/241 X-Sequence-Number: 21554 Nick Johnson writes: > I'm trying to write a PostgreSQL extension to estimate the number of > rows returned by a SELECT statement. Instead of fooling around at the C level, why don't you just do an EXPLAIN and parse out the first row of the result? For instance regression=# create function estimate_row_count(text) returns text as $$ regression$# declare x record; regression$# begin regression$# for x in execute 'EXPLAIN ' || $1 loop regression$# return substring(x."QUERY PLAN" from 'rows=([0-9]+) width='); regression$# end loop; regression$# end$$ language plpgsql strict; CREATE FUNCTION regression=# select estimate_row_count('select * from tenk1'); estimate_row_count -------------------- 10000 (1 row) Of course this is subject to future breakage due to changes in the output textual format, etc etc, but it's surely less fragile than anything written in C will be. Depending on what you want the results for, it might be best to ignore any top-level LIMIT node. regards, tom lane