Re: subselect return in where clause

Lists: pgsql-sql
From: Michael Hostbaek <mich(at)the-lab(dot)org>
To: pgsql-sql(at)postgresql(dot)org
Subject: subselect return in where clause
Date: 2003-01-28 11:21:23
Message-ID: 20030128112123.GC67742@mich2.itxmarket.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Lists: pgsql-sql

Group,

Is it possible to use a subselect result in a where statement ? If so,
how ?

Fx.
select some_stuff, more_stuff,
(select other_stuff from other_table where other_table.stuff ilike
stuff.match) as other_stuff from stuff where other_stuff = 'hello'

thanks.
--
Best Regards,
Michael Landin Hostbaek
FreeBSDCluster.org - an International Community

*/ PGP-key available upon request /*


From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Michael Hostbaek <mich(at)the-lab(dot)org>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: subselect return in where clause
Date: 2003-01-28 15:56:28
Message-ID: 13472.1043769388@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Lists: pgsql-sql

Michael Hostbaek <mich(at)the-lab(dot)org> writes:
> select some_stuff, more_stuff,
> (select other_stuff from other_table where other_table.stuff ilike
> stuff.match) as other_stuff from stuff where other_stuff = 'hello'

The above is nonsensical: WHERE cannot refer to values computed in
the SELECT list, because WHERE logically occurs before the SELECT
list is executed (indeed, the SELECT list will not be executed at
all, if WHERE returns false).

You could repeat yourself:

select some_stuff, more_stuff,
(select other_stuff from other_table where other_table.stuff ilike
stuff.match) as other_stuff from stuff
where
(select other_stuff from other_table where other_table.stuff ilike
stuff.match) = 'hello'

or if it really bugs you to write the expression twice, perhaps
use a sub-select:

select * from
(select some_stuff, more_stuff,
(select other_stuff from other_table where other_table.stuff ilike
stuff.match) as other_stuff from stuff) as subselect
where other_stuff = 'hello'

although you shouldn't have any illusions about this being more
efficient than writing the expression twice.

regards, tom lane