views:

205

answers:

2

Oracle PL/SQL won't let users to use aliases in conditions. In most cases it's very practical for me to use aliases instead of long statements. What's the reason for that? What bad would happen if we could use aliases in conditions?

Example case: http://stackoverflow.com/questions/2235166/whats-wrong-with-this-sql-query

+3  A: 

Column aliases work only with order by clause, because order by is performed after select and all others before select, so they do not have any idea about alias.

You can see this page. I believe that Oracle's engine works the same way.

gd047
+5  A: 

I think it's just because that is what the SQL standard specifies. I don't agree with gd047 that the alias couldn't be used: the HAVING clause operates on the (intermediate) results of the query i.e. after aggregation, so it would seem pretty straight-forward for the query parser to use the alias to access that result.

You can of course avoid repeating the SUM like this (using the example from the linked question):

SELECT *
from
( SELECT donem, bolge_adi, sehir_tasra "1=S, 2=T", 
         COUNT(DISTINCT mekankodu) "M.SAYISI",
         SUM(b2b_dagitim + b2b_transfer - b2b_iade) satis
  FROM mps_view2
  WHERE donem IN ('200612','200712','200812','200912')
  AND (ob IS NOT NULL OR b2b_ob IS NOT NULL)
  GROUP BY donem, bolge_adi, sehir_tasra
)
WHERE satis > 0
ORDER BY donem, bolge_adi, sehir_tasra
Tony Andrews
+1 - beat me to it.
APC