I am looking for a way for Oracle to use an index for sorting even if it contains a column of type VARCHAR2.
For example, if I have the following table:
CREATE TABLE test
(
id NUMBER,
t VARCHAR2(24 CHAR),
n NUMBER
);
with the following indices:
CREATE INDEX ix_test1
ON test(n, id);
CREATE INDEX ix_test2
ON test(t, id);
Then the following SELECT statement
SELECT *
FROM test
WHERE n = 0
AND id > 100
ORDER BY n, id;
has the following execution plan:
------------------------------------------------
| Id | Operation | Name |
------------------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | TABLE ACCESS BY INDEX ROWID| TEST |
|* 2 | INDEX RANGE SCAN | IX_TEST1 |
------------------------------------------------
Since the columns in the index IX_TEST1 correspond to the columns in the ORDER BY clause, there's no sort operation.
But, the following statement
SELECT *
FROM test
WHERE t = 'X'
AND id > 100
ORDER BY t, id;
has this execution plan
-------------------------------------------------
| Id | Operation | Name |
-------------------------------------------------
| 0 | SELECT STATEMENT | |
| 1 | SORT ORDER BY | |
| 2 | TABLE ACCESS BY INDEX ROWID| TEST |
|* 3 | INDEX RANGE SCAN | IX_TEST2 |
-------------------------------------------------
As you can see, there is an explicit sorting here.
This is logical in that the storage of the values for column T in the index is binary (AFAIK), while the sorting depends on the currently set value for NLS_SORT.
Is there a possibility to define the index differently or to formulate the ORDER BY clause differently, so that also in this case the explicit sorting is omitted.
Edit: There's no sample data in the test table and I'm using Oracle 12.1.