Question

Since i can't use expression result in the WHERE clause, i need to repeat the expression. but since i also use it above, as a column - it seems like a waste of resources.

Can it be avoided?

some code:

SELECT field1,
       (SELECT some_field
        FROM   another_table) AS field2
FROM   table_1
WHERE  NOT field2 IS NULL  
# won't work

SELECT field1,
       (SELECT some_field
        FROM   another_table) AS field2
FROM   table_1
WHERE  NOT (SELECT some_field FROM   another_table) IS NULL  
# will work
Was it helpful?

Solution

Move the predicate from the WHERE clause to a HAVING clause, and you can reference field2 by it's alias:

In that first query, just change WHERE to HAVING. That will work.

(The HAVING clause operates on the resultset after it's prepared; the WHERE clause is evaluated much earlier in the processing, that determines which rows get included in the resultset, and can filter out a lot of rows, which makes things more efficient.


NOTE: your query may not be the most efficient approach to getting the resultset you want; but there's not enough information to make a recommendation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top