Sub topic 12
Indexing a virtual column instead
This chapter assumes you can create B-tree and function-based indexes, read a basic EXPLAIN PLAN output, and know that a function-based index (FBI) stores the result of an expression for each row. Here you will learn the alternative: define the expression once as a virtual column and index that column.
The problem a virtual column solves
A function-based index on UPPER(email) works, but the expression lives only inside the index definition. Anyone reading the table definition cannot see that the application relies on UPPER(email). Every query author must also retype the expression exactly. If one developer writes UPPER(email) and another writes UPPER(TRIM(email)), only the first can use the index.
A virtual column moves the expression into the table definition. It is a column whose value is computed from other columns of the same row. Oracle does not store the value in the table block. It evaluates the expression when you read the column. If you index the virtual column, the index entries are stored on disk like any other B-tree index, so the lookup cost is the same as for an FBI.
Creating a virtual column and indexing it
The orders table from earlier chapters has an email column. This statement adds a virtual column email_uc that holds the upper-case form:
ALTER TABLE orders ADD (
email_uc VARCHAR2(100) GENERATED ALWAYS AS (UPPER(email)) VIRTUAL
);
CREATE INDEX orders_email_uc_ix ON orders (email_uc);Points about the syntax:
GENERATED ALWAYS AS (...)holds the expression. TheVIRTUALkeyword is optional, but it makes the intent clear.- The data type is optional. If you leave it out, Oracle derives it from the expression. Stating it explicitly documents the column and avoids surprises.
- The expression can refer only to columns of the same table. It cannot refer to other virtual columns that are defined later, and it cannot call a user-defined function unless that function is declared
DETERMINISTIC. - You cannot
INSERTorUPDATEa virtual column. Oracle rejects any attempt to write to it.
Now a query can use the column by name:
SELECT order_id
FROM orders
WHERE email_uc = '[email protected]';The plan should show an index range scan on ORDERS_EMAIL_UC_IX, as it would for a plain column.
Queries that still use the original expression
Developers do not have to change existing queries. Oracle can match a query expression to the virtual column definition. A query such as this one can still use the index on email_uc:
SELECT order_id
FROM orders
WHERE UPPER(email) = '[email protected]';The optimizer sees that UPPER(email) is the definition of email_uc and can rewrite the predicate to use the column. Check the plan to confirm this in your own database. The match depends on the expression being identical in meaning to the one in the column definition, and the matching rules are the same ones that govern a function-based index.
Note that Oracle implements an FBI by creating a hidden virtual column behind the scenes. A virtual column index is therefore close to an FBI in its internals. The difference is that you control the column's name, it is visible in the data dictionary, and other features can use it.
Comparing the two approaches
| Aspect | Function-based index | Index on a virtual column |
|---|---|---|
| Where the expression is defined | Inside the index only | In the table definition |
| Visible in `DESCRIBE` | No | Yes |
| Query can refer to it by name | No, must repeat the expression | Yes, `WHERE email_uc = ...` |
| Table structure change | None | Adds a column |
| Storage in table blocks | None | None (computed on read) |
| Index storage | Index entries | Index entries |
| Other uses of the expression | Only in index lookups | Constraints, partitioning keys, statistics, views |
The last row is the main reason to choose a virtual column. Because it is a real column, you can also do the following with it:
- Put a unique constraint on it, for example to enforce case-insensitive uniqueness of email addresses.
- Gather column statistics, including histograms, directly on the expression's results.
- Use it as a partitioning key.
- Select it in views and reports without repeating the expression.
Here is the unique constraint example:
ALTER TABLE orders
ADD CONSTRAINT orders_email_uc_uk UNIQUE (email_uc);This rejects two rows whose emails differ only in letter case. Be aware that in the sample orders table an email can appear on many orders, so you would apply this to a table where one email identifies one row, such as a customer table.
Requirements and limits
A virtual column must follow these rules:
- The expression must be deterministic. The same input row must always give the same result.
SYSDATEandDBMS_RANDOMare not allowed. - It can refer only to columns in the same table, and not to other virtual columns that would create a circular reference.
- A virtual column cannot be a
LONGorLOBtype in most cases. Check the documentation for your release for the exact list. - You cannot add a virtual column to an index-organized table's overflow in every case, and you cannot define one on an external table in the same way as on a heap table. Test these cases before relying on them.
- Changing the expression later is not a simple edit. In many releases you must drop and re-add the column, which invalidates the index. Plan the expression carefully.
If you use your own PL/SQL function in the expression, mark it DETERMINISTIC and be certain it really is. Oracle trusts the declaration. If the function returns different results over time, the index contents will no longer match what the function returns, and queries can return wrong rows.
CREATE OR REPLACE FUNCTION norm_email (p_email VARCHAR2)
RETURN VARCHAR2 DETERMINISTIC
IS
BEGIN
RETURN LOWER(TRIM(p_email));
END;
/Cost and behavior on DML
The write-side cost matches an FBI. On INSERT, Oracle evaluates the expression and adds an index entry. On UPDATE of a column the expression uses, Oracle recomputes the value and moves the index entry if it changed. On DELETE, it removes the entry. A slow expression, such as a PL/SQL function call, therefore slows every one of these statements, not just the queries.
The virtual column itself adds no storage to the table, but it does add the index. It also means that SELECT * now returns an extra column, which can affect application code that depends on column position. Many teams avoid that by always naming columns in queries. If you want to hide the column from SELECT *, you can mark it INVISIBLE in Oracle 12c and later, though the exact options depend on your version.
Checking that the index is used
Use the same method as in the plan-reading chapter:
EXPLAIN PLAN FOR
SELECT order_id
FROM orders
WHERE email_uc = '[email protected]';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);Look for INDEX RANGE SCAN on ORDERS_EMAIL_UC_IX, followed by TABLE ACCESS BY INDEX ROWID. You can see the virtual column definition in the data dictionary:
SELECT column_name, virtual_column, data_default
FROM user_tab_cols
WHERE table_name = 'ORDERS'
AND virtual_column = 'YES';USER_TAB_COLS is used instead of USER_TAB_COLUMNS because the former also lists hidden columns, including the ones Oracle creates for function-based indexes.
Common errors
- Case mismatch in the value. The column holds upper-case text, so
WHERE email_uc = '[email protected]'finds nothing. Compare against an upper-case literal. - Different expression in the query.
UPPER(TRIM(email))is not the same asUPPER(email). The index is not considered. - Non-deterministic function. Oracle raises an error when you create the column or the index.
- Writing to the column. An
INSERTthat listsemail_ucfails. Leave it out of the column list. - Stale assumptions about the data type. If the expression can grow longer than the declared type, evaluation raises an error at run time.
Choosing between the two
Choose a plain FBI when the expression is used by one or two queries and you do not want to change the table. Choose a virtual column when the expression is a business rule that should be named, shared, constrained, or described by statistics. The index performance is the same, so the decision rests on maintainability.
Exercise
A table customers has a column last_name. Queries search with WHERE UPPER(last_name) = :n. You also want to prevent two customers from having the same last name and first name that differ only by case. Write the statements that add a virtual column on UPPER(last_name) and index it. Then explain why a virtual column suits the uniqueness rule better than an FBI.
Show answer
ALTER TABLE customers ADD (lastnameuc VARCHAR2(100) GENERATED ALWAYS AS (UPPER(lastname)) VIRTUAL); then CREATE INDEX customerslnucix ON customers (lastnameuc); The virtual column is a real column, so it can be named in a constraint such as a unique constraint (for example on first-name and lastnameuc together), and it can carry column statistics. An FBI exists only inside the index and cannot be named in the same way, so it cannot be referenced by constraints you define on the table.
Exercise
Why can a query using WHERE UPPER(email) = '[email protected]' still use an index on the virtual column email_uc, and when would it not?
Show answer
The optimizer can match the expression in the query to the definition of the virtual column and treat the predicate as a predicate on email_uc. It would not match if the query expression differs from the definition, for example UPPER(TRIM(email)), because the two expressions are different computations.