Search code examples
sqloracle-databaseplsqlora-00904

Use a calculated field in the where clause


Is there a way to use a calculated field in the where clause?

I want to do something like

SELECT a, b, a+b as TOTAL FROM (
   select 7 as a, 8 as b FROM DUAL
   UNION ALL
   select 8 as a, 8 as b FROM DUAL
   UNION ALL
   select 0 as a, 0 as b FROM DUAL
)
WHERE TOTAL <> 0
;

but I get ORA-00904: "TOTAL": invalid identifier.

So I have to use

SELECT a, b, a+b as TOTAL FROM (
   select 7 as a, 8 as b FROM DUAL
   UNION ALL
   select 8 as a, 8 as b FROM DUAL
   UNION ALL
   select 0 as a, 0 as b FROM DUAL
)
WHERE a+b <> 0
;

Solution

  • Logically, the select clause is one of the last parts of a query evaluated, so the aliases and derived columns are not available. (Except to order by, which logically happens last.)

    Using a derived table is away around this:

    select * 
    from (SELECT a, b, a+b as TOTAL FROM ( 
               select 7 as a, 8 as b FROM DUAL 
               UNION ALL 
               select 8 as a, 8 as b FROM DUAL 
               UNION ALL 
               select 0 as a, 0 as b FROM DUAL) 
        )
    WHERE TOTAL <> 0 
    ;