Re: How to force select to return exactly one row

From: "Brent Wood" <b(dot)wood(at)niwa(dot)co(dot)nz>
To: <kobruleht2(at)hot(dot)ee>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: How to force select to return exactly one row
Date: 2010-06-21 22:38:04
Message-ID: 4C20928C0200007B0002A00E@gwia.niwa.co.nz
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Use a case staement to test for a null output, & return whatever you want in the event of it being null, else the actual value:

from the top of my head, something like:

SELECT case when
(select somecolumns
FROM ko
RIGHT JOIN (SELECT 1) _forceonerow ON true
LEFT JOIN t1 ON t1.primarykey= ko.t1foreignkwey
...
LEFT JOIN tn ON tn.primarykey= ko.tnforeignkwey
WHERE ko.primarykey is null or ko.primarykey='someprimarykeyvalue') not null

then (select somecolumns

FROM ko
RIGHT JOIN (SELECT 1) _forceonerow ON true
LEFT JOIN t1 ON t1.primarykey= ko.t1foreignkwey
...
LEFT JOIN tn ON tn.primarykey= ko.tnforeignkwey
WHERE ko.primarykey is null or ko.primarykey='someprimarykeyvalue')

else
0
end

It does require the query to be run twice, so does have extra overhead. You could wrap a function around this to get & store the result & test that, then having stored it you can use it for the output value without a second query. All depends on how much overhead there is in teh query.

HTH,

Brent Wood

Brent Wood
DBA/GIS consultant
NIWA, Wellington
New Zealand
>>> "Andrus" 06/22/10 10:12 AM >>>

Autogenerated select statement contains 0 .. n left joins:

SELECT somecolumns
FROM ko
LEFT JOIN t1 ON t1.primarykey= ko.t1foreignkwey
...
LEFT JOIN tn ON tn.primarykey= ko.tnforeignkwey
WHERE ko.primarykey='someprimarykeyvalue';

This select can return only 0 or 1 rows depending if ko row with primary key
'someprimarykeyvalue' exists or not.

Problem:

if there is no searched primary key row in ko database, select should also
return empty row.

To get this result I added right join:

SELECT somecolumns
FROM ko
RIGHT JOIN (SELECT 1) _forceonerow ON true
LEFT JOIN t1 ON t1.primarykey= ko.t1foreignkwey
...
LEFT JOIN tn ON tn.primarykey= ko.tnforeignkwey
WHERE ko.primarykey is null or ko.primarykey='someprimarykeyvalue';

but it still does not return row if primary key row 'someprimarykeyvalue'
does not exist.

How to force this statement to return one row always ?

Andrus.

--
Sent via pgsql-general mailing list (pgsql-general(at)postgresql(dot)org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-general

NIWA is the trading name of the National Institute of Water & Atmospheric Research Ltd.

Browse pgsql-general by date

  From Date Subject
Next Message Brett Mc Bride 2010-06-21 23:23:01 Re: How to force select to return exactly one row
Previous Message Geoffrey 2010-06-21 22:30:22 Re: pgpool