Re: Query size?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Paul Tomblin <ptomblin(at)gmail(dot)com>
Cc: imad <immaad(at)gmail(dot)com>, pgsql-jdbc(at)postgresql(dot)org
Subject: Re: Query size?
Date: 2008-06-22 18:56:18
Message-ID: 15295.1214160978@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-jdbc

Paul Tomblin <ptomblin(at)gmail(dot)com> writes:
> What I'm asking though is if there is some way to know before I start
> returning results, short of doing a "COUNT(*)" first.

No. Postgres generates query results on the fly, so the server doesn't
know the number of rows that will be returned either, until the query
completes.

You can get an estimate by running EXPLAIN, but those estimates are
frequently far off the mark.

If you're really intent on having an accurate count before you fetch
the results, you can set up the query as a scrollable cursor, do MOVE
FORWARD ALL and note the move count, then MOVE BACKWARD ALL and start
fetching. This amounts to forcing the server to materialize the whole
result set before you start to fetch it, which is exceedingly expensive,
especially if the result set is very large.

Usually the best bet is to just limit how much you will fetch, using
LIMIT or a cursor as suggested by imad.

regards, tom lane

In response to

Browse pgsql-jdbc by date

  From Date Subject
Next Message Oliver Jowett 2008-06-23 06:32:10 Re: PreparedStatement implementation needet
Previous Message imad 2008-06-22 12:55:02 Re: Query size?