Search code examples
sqloracleoracle11g

Oracle virtual column referencing another table


I have a table TABLE1 with column COL_TAB1.

select * from TABLE1:
 COL_TAB1
|    1   |
|    2   |
|    3   |

And another table TABLE2 with COL_TAB2 and references the first column COL_TAB1

select * from TABLE2:
 COL_TAB2  |  COL_TAB1
| val1     |     1
| val2     |     2
| val2     |     3

Is it possible to add a virtual column on table1 so i would get the same result as the following query:

select 
    t1.COL_TAB1, 
    (select t2.COL_TAB2 from TABLE2 t2 where t2.COL_TAB1 = t1.COL_TAB1)
from TABLE1 t1

I tried :

alter table TABLE1 add (
    SOME_COL_NAME as (select t2.COL_TAB2 from TABLE2 t2 where t2.COL_TAB1 = COL_TAB1)
)

But it gives me ORA-00936: missing expression


Solution

  • Oracle's documentation on virtual columns states it rather clearly, you can only reference columns in the same table;

    The expression used in the virtual column definition has the following restrictions:

    • It cannot refer to another virtual column by name.
    • It can only refer to columns defined in the same table.
    • If it refers to a deterministic user-defined function, it cannot be used as a partitioning key column.
    • The output of the expression must be a scalar value. It cannot return an Oracle supplied datatype, a user-defined type, or LOB or LONG RAW.

    As @JoeStefanelli states, your best bet to do what you want is to create a view.