Sub topic 14
Using index order for ORDER BY and top-N queries
This chapter assumes you can read an execution plan with DBMS_XPLAN, and that you know how a composite index is searched from its leading column. It also assumes you know that a B-tree index stores its entries sorted. Here you will use that sort order to avoid sorting, and to stop reading early when a query wants only the first few rows.
Why index order matters
A B-tree index keeps its entries sorted by the indexed columns. If a query asks for rows in that same order, Oracle can read the index entries in sequence and skip the sort step. That has two effects:
- The plan has no
SORT ORDER BYstep, so no sort memory or temporary space is used. - The first rows come back immediately, because Oracle does not have to read and sort everything before returning anything.
The second effect is the larger one for top-N queries. Oracle can read ten index entries and stop. Without a suitable index it must read and sort every qualifying row, then discard all but ten.
Setting up an example
The examples use the orders table from earlier chapters. This script creates a version you can run and gathers statistics.
CREATE TABLE orders (
order_id NUMBER PRIMARY KEY,
customer_id NUMBER NOT NULL,
order_date DATE NOT NULL,
status VARCHAR2(10) NOT NULL
);
INSERT INTO orders
SELECT level,
MOD(level, 1000),
DATE '2026-01-01' + MOD(level, 300),
CASE WHEN MOD(level, 50) = 0 THEN 'OPEN' ELSE 'CLOSED' END
FROM dual
CONNECT BY level <= 100000;
COMMIT;
CREATE INDEX orders_date_ix ON orders (order_date);
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(USER, 'ORDERS');
END;
/Top-N with a matching index
This query asks for the ten most recent orders.
EXPLAIN PLAN FOR
SELECT order_id, order_date
FROM orders
ORDER BY order_date DESC
FETCH FIRST 10 ROWS ONLY;
SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);The plan should look like this. Costs and row counts will differ on your system.
-----------------------------------------------------------------------
| Id | Operation | Name | Rows | Cost |
-----------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 10 | 4 |
|* 1 | COUNT STOPKEY | | | |
| 2 | TABLE ACCESS BY INDEX ROWID | ORDERS | 10 | 4 |
| 3 | INDEX FULL SCAN DESCENDING | ORDERS_DATE_IX | | 3 |
-----------------------------------------------------------------------Two things in this plan show the optimization is working:
INDEX FULL SCAN DESCENDINGwalks the index from its high end. One ascending index serves bothASCandDESCrequests.COUNT STOPKEYstops the scan after ten rows. There is noSORT ORDER BYstep.
If you see SORT ORDER BY STOPKEY over a TABLE ACCESS FULL, Oracle is reading and sorting the whole table. That is the plan you are trying to avoid.
The NULL condition
The first row of the diagram's second test is the one people miss. A B-tree index omits rows whose indexed columns are all NULL. If order_date allowed NULL, the index would not contain every row, so reading it in order could silently drop rows. Oracle will not do that and falls back to a full scan plus sort.
In the example above, order_date is NOT NULL, which is why the plan works.
Composite indexes: equality first, then the sort column
A composite index is ordered by its first column, then by the second within each first-column value, and so on. Rows for one customer_id are therefore sorted by order_date inside the index.
CREATE INDEX orders_cust_date_ix
ON orders (customer_id, order_date);
-- No sort: customer_id is fixed, so entries come out in order_date order
SELECT order_id, order_date
FROM orders
WHERE customer_id = 42
ORDER BY order_date DESC
FETCH FIRST 10 ROWS ONLY;The rule is that the index columns, minus those pinned by equality conditions, must match the ORDER BY columns in order. The table shows the result for the index (customer_id, order_date).
| Query shape | Sort needed? | Reason |
|---|---|---|
| `WHERE customer_id = 42 ORDER BY order_date` | No | The equality fixes the leading column. |
| `WHERE customer_id = 42 ORDER BY order_date DESC` | No | The index can be scanned backwards. |
| `WHERE customer_id > 40 ORDER BY order_date` | Yes | Several customers match, so dates restart for each one. |
| `WHERE customer_id IN (1, 2) ORDER BY order_date` | Yes | Each list value is a separate scan, and results are not merged in date order. |
| `ORDER BY order_date` with no filter | Yes | `customer_id` leads the index, so entries are not in date order overall. |
| `WHERE customer_id = 42 ORDER BY order_date, order_id` | Yes | `order_id` is not in the index. |
Putting the equality column before the sort column is the main design rule for filtered top-N queries. This is the same principle as the column-order chapter, applied to sorting.
Mixed sort directions and expressions
An index can be scanned forwards or backwards, but only as a whole. ORDER BY a ASC, b ASC and ORDER BY a DESC, b DESC both work with an index on (a, b). ORDER BY a ASC, b DESC does not. For that, create the index with the same directions.
CREATE INDEX orders_cust_date_mixed_ix
ON orders (customer_id ASC, order_date DESC);Oracle implements a DESC column in a composite index as a hidden expression, so it behaves like a function-based index. Use it only when a query needs mixed directions.
The same logic applies to expressions. ORDER BY UPPER(last_name) needs a function-based index on UPPER(last_name), as in the earlier chapter.
Filters that are not in the index
A top-N query can still be slow when it filters on a column that is missing from the index. Consider this query with only orders_date_ix available.
SELECT order_id, order_date
FROM orders
WHERE status = 'OPEN'
ORDER BY order_date DESC
FETCH FIRST 10 ROWS ONLY;Oracle walks the date index from the newest entry, fetches each table row, and checks status. It stops after ten matches. If OPEN rows are rare or sit in old data, it reads many rows before finding ten. An index on (status, order_date) turns status into an access predicate and removes that wasted work.
Ties and deterministic results
If many rows share the same order_date, the ten rows returned are not defined unless the sort is unique. Add a unique tie-breaker to both the query and the index.
CREATE INDEX orders_date_id_ix ON orders (order_date, order_id);
SELECT order_id, order_date
FROM orders
ORDER BY order_date DESC, order_id DESC
FETCH FIRST 10 ROWS ONLY;This gives the same rows on every run, which pagination needs.
Pagination and large offsets
OFFSET 10000 ROWS FETCH NEXT 10 ROWS ONLY still reads and discards the first 10,000 entries, so each later page costs more than the one before. For deep paging, use a seek condition that starts after the last row of the previous page.
SELECT order_id, order_date
FROM orders
WHERE order_date < :last_date
OR (order_date = :last_date AND order_id < :last_id)
ORDER BY order_date DESC, order_id DESC
FETCH FIRST 10 ROWS ONLY;Check the plan before relying on this. The OR can stop Oracle from using the index as a single range, and then the benefit is lost.
Common mistakes
- Applying a function to the sort column, such as
ORDER BY TRUNC(order_date), when the index stores the raw column. - Forgetting the
NULLrule on a nullable sort column. - Reading
INDEX FAST FULL SCANas ordered. It reads blocks in physical order and does not return rows sorted, so aSORT ORDER BYstill appears. - Expecting
INlists or range filters on a leading column to keep the sort column ordered. - Assuming the optimizer will always pick the index. For a top-N query it estimates cost for the first N rows only, but poor statistics can still lead it to a full scan.
Exercise
A table tickets has an index on (project_id, created_at). Both columns are NOT NULL. Which of these queries needs a SORT ORDER BY step, and why? (a) WHERE project_id = 7 ORDER BY created_at DESC FETCH FIRST 20 ROWS ONLY (b) WHERE project_id IN (7, 8) ORDER BY created_at FETCH FIRST 20 ROWS ONLY
Show answer
Query (b) needs a sort. With an IN list, each projectid is a separate index scan and the results are not merged in createdat order. Query (a) fixes projectid with an equality, so the entries for project 7 are already sorted by createdat. Oracle scans that range backwards and stops after 20 rows with COUNT STOPKEY.
Exercise
You run a top-N query ordered by last_login on a nullable column with a single-column index, and the plan shows SORT ORDER BY. Give two ways to let Oracle use the index order.
Show answer
Declare the column NOT NULL if the data allows it, or add WHERE last_login IS NOT NULL to the query. Either way, Oracle knows that no wanted row is missing from the B-tree index, which omits rows whose indexed columns are all NULL.