Wednesday, January 12, 2011

Virtual columns in Oracle 11g R1

Virtual columns are normal columns in a table but their values are derived rather than being stored on disc. The syntax is given below.
column_name [datatype] [GENERATED ALWAYS] AS (expression) [VIRTUAL]
datatype is optional, it will automatically determine based on the result of the expression. GENERATED ALWAYS and VIRTUAL keywords are for clarity only.
Below is an example for creating a simple virtual column.
CREATE
TABLE T
( a NUMBER,
b NUMBER,
c AS (a+b),

d NUMBER GENERATED ALWAYS AS (a*b) VIRTUAL
);

INSERT INTO T(a,b) VALUES(30,20);
INSERT INTO T(a,b) VALUES(10,10);
COMMIT;
SELECT * FROM t;
a b c d
-------------------
30 20 50 600
10 10 20 100
2 rows selected.

To see the virual columns in a table, use the below query.
SELECT * FROM user_tab_cols WHERE table_name='T' AND virtual_column='YES';

Notes about virtual columns:
1. Can be indexed but equivalent to function based index.
2. Cannot perform any DML operations on virtual column.
3. Cannot be based on other virtual columns. It should be based on columns defined on the same table.
4. Can be constrained.
5. Eligible for result caching.
6. Virtual columns can be used in the partition key. That means virtual column can be partitioned.
7. Virtual columns are not supported under external, object, cluster, temporary, or index organized tables.
8. Functions in expressions must be deterministic at the time of table creation, but can subsequently be recompiled and made non-deterministic without invalidating the virtual column. In such cases the following steps must be taken after the function is recompiled:
-Constraint on the virtual column must be disabled and re-enabled.
-Indexes on the virtual column must be rebuilt.
-Materialized views that access the virtual column must be fully refreshed.
-The result cache must be flushed if cached queries have accessed the virtual column.
-Table statistics must be regathered.

See my notes about virtual column partitioning.

No comments:

Post a Comment