Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Alias In When Portion of a Case Statement in Oracle SQL

I've been trying to look up for awhile now if it's possible to use an alias stated earlier in the select statement if it can be used in a case later in the case statement for Oracle SQL. Most results I find are about how to make an Alias based on a case statement which isn't the same problem. A quick example would be something like:

Select TABLEA.SomeIDNumber AS "Id",
       case ID
          when 3
          then 'foo'
          else 'bar'
       end AS "Results"
FROM OMEGA.TABLEA

It's really not that simple in the SQL Statement I'm creating (it's actually created based on a previous case statement and requires some joins on various tables to do the full other pats of the query, but it wouldn't really make sense without knowing more of the database which I can't share).

I'm just wondering if it's possible to use an alias in a case statement later in the select statement for Oracle (I know such things can be done with Access kinda "SQL"). Or is it better for me to do some reworking of the select to make it nested select statements? Probably doable, just a bit more of a pain.

like image 877
The God Emperor Avatar asked Jul 11 '13 11:07

The God Emperor


Video Answer


1 Answers

No, you can't refer to the alias elsewhere in the same level of select, other than in the order by clause, because of when Oracle assigns it internally.

From the documentation (emphasis added):

You can use a column alias, c_alias, to label the immediately preceding expression in the select list so that the column is displayed with a new heading. The alias effectively renames the select list item for the duration of the query. The alias can be used in the ORDER BY clause, but not other clauses in the query.

You would need to use an inner query, something like:

select "Id",
    case "Id"
        when 3
        then 'foo'
        else 'bar'
    end AS "Results"
from (
    select TABLEA.SomeIDNumber AS "Id",
    from TABLEA
);
like image 154
Alex Poole Avatar answered Sep 19 '22 01:09

Alex Poole