Sub topic 12
Conversions in WHERE clauses and index use
This chapter assumes you can read a basic execution plan and know what an index on a column is. It also assumes you know TO_CHAR, TO_DATE, and TO_NUMBER with format models. The question here is where in a WHERE clause a conversion should go, so that a query can still use an index on the column it filters.
Why the position of a conversion matters
A regular B-tree index stores the values of a column in sorted order. Oracle can use it to jump to a value or scan a range of values. The index holds hire_date, not TO_CHAR(hire_date, 'YYYY'). If you wrap the indexed column in a function, the database has to compute the function for every row before it can compare the result. A normal index on the column cannot help with that.
This gives one rule for conversions in filters:
- Convert the constant (or bind variable) side of a comparison.
- Leave the column side bare.
Queries written this way are often called index-friendly. You may also see the term "sargable", short for "search ARGument ABLE".
The rule holds for explicit conversions that you write, and it also holds for implicit ones that Oracle adds for you. Both kinds can end up wrapped around the column.
Explicit conversion on the column
Here is the pattern that causes most problems. A developer wants all employees hired in 2026 and formats the date as text:
-- Avoid: wraps the column in a function, so a normal index on hire_date cannot be used
SELECT * FROM employees WHERE TO_CHAR(hire_date, 'YYYY') = '2026';
-- Prefer: convert the constants and leave the column untouched
SELECT * FROM employees
WHERE hire_date >= TO_DATE('2026-01-01', 'YYYY-MM-DD')
AND hire_date < TO_DATE('2027-01-01', 'YYYY-MM-DD');Both queries return the same rows. The second one compares hire_date directly with two constants, so Oracle can run an index range scan on hire_date. The first one forces a function call on every row, which usually means a full table scan.
The same problem appears with other functions on a date column:
| Index-hostile predicate | Index-friendly rewrite |
|---|---|
| `TO_CHAR(hire_date, 'YYYY') = '2026'` | `hire_date >= DATE '2026-01-01' AND hire_date < DATE '2027-01-01'` |
| `TO_CHAR(hire_date, 'YYYY-MM') = '2026-11'` | `hire_date >= DATE '2026-11-01' AND hire_date < DATE '2026-12-01'` |
| `TRUNC(hire_date) = DATE '2026-11-28'` | `hire_date >= DATE '2026-11-28' AND hire_date < DATE '2026-11-29'` |
| `TO_NUMBER(code_text) = 42` | `code_text = '42'` (only if the stored text is always exactly `42`, with no leading zeros or spaces) |
The last row needs care. TO_NUMBER(code_text) = 42 matches '042' and ' 42', while code_text = '42' does not. A rewrite must return the same rows as the original, not just similar ones.
Why half-open ranges
The rewrites above use >= for the lower bound and < for the next boundary. This is a half-open range. It has two advantages.
First, a DATE in Oracle always carries a time of day. A filter such as hire_date BETWEEN DATE '2026-11-01' AND DATE '2026-11-30' ends at midnight at the start of 30 November. It silently drops every row from 30 November that has a time after 00:00:00. Writing < DATE '2026-12-01' avoids this without having to pick a "last second" such as 23:59:59, which would miss fractional seconds on TIMESTAMP columns.
Second, the upper bound of one period is the lower bound of the next. Adjacent periods then never overlap and never leave gaps.
The same approach works for TIMESTAMP columns:
SELECT *
FROM audit_log
WHERE created_at >= TIMESTAMP '2026-11-28 00:00:00'
AND created_at < TIMESTAMP '2026-11-29 00:00:00';The table audit_log is an example name. Any table with a TIMESTAMP column created_at works the same way.
Implicit conversion on the column
Oracle also adds conversions on its own when the two sides of a comparison have different types. The direction of the conversion decides whether an index can be used.
For a comparison between a character value and a number, Oracle converts the character value to a number. If the column is the character side, the conversion lands on the column:
-- Fails with ORA-01722 if any row of order_ref holds a non-numeric value
SELECT * FROM orders WHERE order_ref = 1001;
-- Explicit and safe: compare as text
SELECT * FROM orders WHERE order_ref = '1001';Suppose order_ref is a VARCHAR2 column. The first query is treated as TO_NUMBER(order_ref) = 1001. This has two consequences:
- A normal index on
order_refcannot be used, for the reason given earlier. - Oracle must convert the stored text of each row it examines. If it reaches a value such as
'A-77', the query stops with ORA-01722 (invalid number). Whether you see the error can depend on the plan and on the order in which rows are read. A query that works today can fail after the optimizer picks a different plan or after one bad row is inserted.
The second query compares text with text. It uses the index and cannot raise a conversion error.
Now take the opposite case. If the column is NUMBER and the literal is a string, as in WHERE order_id = '1001', Oracle converts the string. The column stays bare and the index remains usable. This still has a cost: if the string is ever not a number, the query raises an error. Write the literal as 1001 to compare numbers with numbers.
Dates follow the same logic:
hire_date = '28-NOV-2026'converts the string to a date by using the session'sNLS_DATE_FORMATand language. The column is untouched, so the index works. The query breaks as soon as another session has a different setting.hire_date = DATE '2026-11-28'andhire_date = TO_DATE('2026-11-28', 'YYYY-MM-DD')do not depend on any session setting.
Also remember that a DATE equality such as hire_date = DATE '2026-11-28' matches only rows at exactly midnight. If the column stores times, use a range.
Converting bind variables
Application code usually passes values as bind variables. Convert the bind, not the column:
SELECT employee_id, last_name, hire_date
FROM employees
WHERE hire_date >= TO_DATE(:start_text, 'YYYY-MM-DD')
AND hire_date < TO_DATE(:end_text, 'YYYY-MM-DD') + 1;The + 1 adds one day to a DATE, so the upper bound is the start of the day after :end_text. The user supplies an inclusive end date and the query still uses a half-open range.
A better design in client code is to bind a real date value (for example a java.sql.Timestamp or a Python datetime) and skip text conversion in the SQL entirely.
Checking what Oracle really does
Do not guess whether an index is used. Look at the plan:
EXPLAIN PLAN FOR
SELECT * FROM employees WHERE TO_CHAR(hire_date, 'YYYY') = '2026';
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);In the output, check the Operation column for INDEX RANGE SCAN or TABLE ACCESS FULL. Then read the "Predicate Information" section at the bottom. A predicate listed under access(...) is used to navigate the index. A predicate listed under filter(...) is evaluated row by row. A conversion that Oracle added on its own appears there as well, for example filter(TO_NUMBER("ORDER_REF")=1001). Seeing a function around your column in that section is the sign of the problem.
When you cannot rewrite: function-based indexes
Sometimes the expression on the column is the business rule and cannot be turned into a range. You can then index the expression itself:
CREATE INDEX employees_hire_year_ix
ON employees (TO_CHAR(hire_date, 'YYYY'));After this, WHERE TO_CHAR(hire_date, 'YYYY') = '2026' can use the index, because the stored index key is the function result. Keep these points in mind:
- The query expression must match the indexed expression. A different format model, such as
'yyyy', or a different function can prevent a match. - The function must be deterministic. A format model that depends on session NLS settings, such as month names without a fixed language, can make the expression unsuitable for indexing. Format models made only of numeric elements like
YYYYare safe. - The index costs space and slows down inserts and updates on
hire_date.
Prefer the range rewrite when it is possible. It needs no extra index, and the plain index on hire_date also serves range queries over any period and ORDER BY hire_date.
Summary of the working rules
- Keep the indexed column bare on one side of the comparison.
- Convert constants and binds with explicit format models, not session defaults.
- Use half-open ranges for dates and timestamps:
>= start AND < next_start. - Compare text with text and numbers with numbers. Remember that Oracle turns a character-versus-number comparison into a conversion of the character side.
- Check
DBMS_XPLANoutput foraccessandfilterpredicates instead of assuming. - Use a function-based index only when the expression cannot be moved off the column.
Exercise
A table orders has an index on order_date (a DATE column that also stores the time). A report uses WHERE TO_CHAR(order_date, 'YYYY-MM') = '2026-11'. Rewrite the predicate so the index can be used and the same rows are returned.
Show answer
Use a half-open range on the bare column: WHERE order_date >= DATE '2026-11-01' AND order_date < DATE '2026-12-01'. This returns every row in November, including rows with a time of day on 30 November, and it lets Oracle use an index range scan on order_date.
Exercise
The column order_ref is a VARCHAR2 and has an index. The query SELECT * FROM orders WHERE order_ref = 1001 sometimes raises ORA-01722 and does not use the index. Explain both symptoms and give the fix.
Show answer
Oracle compares a character value with a number by converting the character value to a number, so the predicate behaves like TO_NUMBER(order_ref) = 1001. The function on the column prevents use of the normal index. It also raises ORA-01722 whenever Oracle evaluates a row whose order_ref is not numeric. The fix is to compare text with text: WHERE order_ref = '1001'.
Exercise
You run EXPLAIN PLAN and DBMS_XPLAN.DISPLAY. In the Predicate Information section, you see filter(TO_CHAR(INTERNAL_FUNCTION("HIRE_DATE"),'YYYY')='2026'). What does this tell you, and what are your two options?
Show answer
The hire_date column is wrapped in a conversion and the condition is applied as a row-by-row filter, so a normal index on hire_date is not used for it. The options are to rewrite the predicate as a half-open range on the bare column, or to create a function-based index on TO_CHAR(hire_date, 'YYYY'). The rewrite is usually preferred.