Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use column alias in same select [duplicate]

Tags:

sql

oracle

How can I use a column alias somewhere else in the same query? Is it possible in Oracle?

Example using EMP_ID:

SELECT
    t1.DATE, t2.NAME, t1.ID,
    TO_NUMBER( SUBSTR( t1.NUMBER_ID, - 6)
      || TRIM( TO_CHAR( SUBSTR(EMP_ID, 3, 2), '00' ) ), '999999999999') AS CONTRACT,
    t2.ADDRESS,
    CASE WHEN SUBSTR(t2.COD_EMP, 0, 2) != 'PG' THEN 'PG00'
      || t2.COD_EMP ELSE t2.COD_EMP END AS EMP_ID
FROM
    TABLE_01 t1
    INNER JOIN TABLE_02 t2 .....
like image 606
LozanoMatheus Avatar asked Jan 06 '16 15:01

LozanoMatheus


2 Answers

Per standard SQL: All columns in any particular SELECT clause are computed "as if" they're all being computed in parallel (to allow some implementation to do precisely that).

As such, you're not allowed to depend on another column defined within the same SELECT clause since it's value has not yet been computed.

like image 88
Damien_The_Unbeliever Avatar answered Oct 14 '22 00:10

Damien_The_Unbeliever


If you check the documentation, you will see that you are only allowed to use it in the order by clause:

Specify an alias for the column expression. Oracle Database will use this alias in the column heading of the result set. The AS keyword is optional. 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.

like image 33
Gergely Bacso Avatar answered Oct 14 '22 02:10

Gergely Bacso