views:

192

answers:

1

Hi,

Consider the following query in PostgreSQL:

SELECT 
    a, b, 
   (A VERY LONG AND COMPLICATED SUBQUERY) AS c,
   (ANOTHER VERY LONG AND COMPLICATED SUBQUERY) AS d
FROM table

I want to have c and d in the WHERE clause, like:

WHERE c AND d;

But, as far as I know, I can only do:

WHERE A VERY LONG AND COMPLICATED SUBQUERY) AND 
   (ANOTHER VERY LONG AND COMPLICATED SUBQUERY)

Which is clumsy, code-replicating, breaking the single-choice principle and utterly ugly.

By the way, the same problem applies to the SELECT clause: I can not use abbreviations for previously-defined subqueries.

+5  A: 

You could use a subquery:

SELECT a,b,c,d FROM
    (SELECT 
        a, b, 
        (A VERY LONG AND COMPLICATED SUBQUERY) AS c,
        (ANOTHER VERY LONG AND COMPLICATED SUBQUERY) AS d
        FROM table
    ) AS T1
WHERE c AND d

You could also do this with a CTE.

Mark Byers
Working. Any idea why the more reasonable syntax isn't working in the PostgreSQL environment?
Adam Matan
Evaluation of the WHERE clause logically precedes evaluation of theSELECT list, so it's really quite nonsensical to expect SELECT outputsto be available in WHERE.http://archives.postgresql.org/pgsql-general/2002-11/msg01411.php
Gerard Banasig
@Adam: I added another alternative (CTEs) to my answer. Also you should check out the HAVING clause (it's also mentioned in Gerard's link).
Mark Byers
@Gerard: I think it can be replaced by some preprocessing search-and-replace mechanism. @Mark thanks - looking into it.
Adam Matan