Re: Best way to know if there is a row

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Martin Marques <martin(at)bugs(dot)unl(dot)edu(dot)ar>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Best way to know if there is a row
Date: 2004-09-28 14:24:16
Message-ID: 14451.1096381456@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Martin Marques <martin(at)bugs(dot)unl(dot)edu(dot)ar> writes:
> I need to know if there is at least one row in the relation that comes from a
> determinated query. Which is the best way to do this:

> (a) Build the query with "SELECT * ..." and after executing the query see if
> numRows()>0
> (b) Build the query with "SELECT count(*) ...", fetch the row and see if
> count>0

Either of these implies computing the entire query result set, which is
much more computation than you want. Instead do
SELECT * .... LIMIT 1
and then see if you got a row or not. Aside from not computing useless
rows, the LIMIT will bias the optimizer in favor of fast-start plans.

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message T E Schmitz 2004-09-28 14:38:21 Re: CHECK col A not NULL if col B='x'
Previous Message Alexander M. Pravking 2004-09-28 14:15:04 Re: CHECK col A not NULL if col B='x'