Re: How to force select to return exactly one row

From: Dean Rasheed <dean(dot)a(dot)rasheed(at)gmail(dot)com>
To: Andrus <kobruleht2(at)hot(dot)ee>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: How to force select to return exactly one row
Date: 2010-06-22 11:28:32
Message-ID: AANLkTimx0c_RpvWn9cwaMZ-O55oGHFq5NbamLUOdweUk@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

2010/6/21 Andrus <kobruleht2(at)hot(dot)ee>:
> 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';
>

The reason this won't return a row if there is no matching PK is that
the WHERE clause is applied after all the joins to filter the overall
result set.

So to get what you want, you would need to re-arrange that to something like:

SELECT original_query.* FROM
( Original query including WHERE clause ) AS original_query
RIGHT JOIN (SELECT 1) AS one_row ON true;

Regards,
Dean

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Shoaib Mir 2010-06-22 11:33:33 Re: Hot Standby switchover
Previous Message Geoffrey 2010-06-22 11:07:33 Re: pgpool