Skip to content

Index optimizations: covering index, ORDER BY, GROUP BY and more

View as Markdown

An index does more than find rows quickly. Because index entries are sorted and contain the key values, the optimizer can also use an index to avoid reading the table, to avoid sorting, and to stop early in LIMIT queries. This page describes these optimizations. Plans and traces are shown as described in Query plans and profiling; the examples use the e-commerce indexes idx_orders_order_date on orders(order_date), fk_orders_customer_id on orders(customer_id) and the primary key of order_items(order_id, product_id), plus a few indexes created for the purpose.

An index covers a query when it contains every column the query uses from that table: in the SELECT list and in the WHERE, GROUP BY, HAVING and ORDER BY clauses. The query is then answered from the index alone, without reading the table, which saves I/O.

SELECT /*+ RECOMPILE */ order_id, product_id FROM order_items WHERE order_id < 5;
iscan
class: order_items node[0]
index: pk_order_items_order_id_product_id term[0] (covers)
cost: 9 card 1123

(covers) in the plan, or covered: true in a trace, shows that the optimization was used.

  • The optimizer prefers a covering index when one is available. In a join, an index that covers the columns of its table is used for that table.
  • A covering index is only used where an index can be used at all.
  • Adding columns to an index to make it cover more queries makes the index larger and INSERT, UPDATE and DELETE slower; weigh this for each table.
  • The hint NO_COVERING_IDX turns the optimization off for a query.

Index scans return rows in index order. When that is the order requested by ORDER BY, no sort is needed: the plan shows sort: on the index scan and the comment /* ---> skip ORDER BY */ (in a trace, skip order by: true).

SELECT /*+ RECOMPILE */ id, order_date
FROM orders
WHERE order_date >= DATE'2025-12-01'
ORDER BY order_date;
iscan
class: orders node[0]
index: idx_orders_order_date term[0]
sort: 2 asc
cost: 5 card 291
/* ---> skip ORDER BY */

An index can be used for ORDER BY col1, col2 when:

  • The ORDER BY columns are the leading columns of the index, in index order: an index on (col1, col2) or (col1, col2, col3) works, an index on (col1) alone does not;
  • Index columns before or between them are fixed to a constant by the WHERE clause: with WHERE col2 = 5, an index on (col1, col2, col3) can be used for ORDER BY col1, col3;
  • Without any condition on the index, the first index column is NOT NULL (otherwise rows with NULL keys would be missing from the index scan).

If an index can be used both as a covering index and to skip the sort, both optimizations apply. If the covering index is not in the requested order, the rows are read from the index and then sorted (the plan shows temp(order by) above the index scan).

An index can be scanned backwards. For ORDER BY … DESC the optimizer does this on its own, without a separate descending index:

SELECT /*+ RECOMPILE */ id, order_date
FROM orders
WHERE order_date >= DATE'2025-12-01'
ORDER BY order_date DESC
LIMIT 5;
iscan
class: orders node[0]
index: idx_orders_order_date term[0] (desc_index)
sort: 2 desc
cost: 3 card 291
/* ---> skip ORDER BY */

There is therefore no need to create both an ascending and a descending index on the same column, which would also make deadlocks more likely.

Without ORDER BY, the hint USE_DESC_IDX asks for a descending scan, for example to get the most recent rows with LIMIT. The plan shows (desc_index forced):

SELECT /*+ RECOMPILE */ order_date FROM orders WHERE order_date > DATE'2025-01-01' LIMIT 3; -- 2025-01-02, 2025-01-03, 2025-01-04
SELECT /*+ RECOMPILE USE_DESC_IDX */ order_date FROM orders WHERE order_date > DATE'2025-01-01' LIMIT 3; -- 2025-12-31 three times

NO_DESC_IDX prevents descending scans. USE_DESC_IDX has no effect on joins. Relying on scan order without ORDER BY is fragile; prefer ORDER BY … DESC.

Grouping normally requires sorted (or hashed) input. When an index delivers the rows in the order of the GROUP BY columns, no sort is needed and the plan shows /* ---> skip GROUP BY */:

SELECT /*+ RECOMPILE */ order_date, COUNT(*)
FROM orders
WHERE order_date >= DATE'2025-12-01'
GROUP BY order_date;
iscan
class: orders node[0]
index: idx_orders_order_date term[0] (covers)
sort: 1 asc
cost: 5 card 291
/* ---> skip GROUP BY */

The rules are the same as for ORDER BY: the GROUP BY columns must be the leading columns of the index, possibly with constant-fixed columns in between, and without a WHERE condition on the index the first index column must be NOT NULL. Aggregate functions do not prevent the optimization: with an index on (a, b, c), SELECT a, MIN(b), c, MAX(b) FROM t WHERE a > 18 GROUP BY a, b is grouped from the index.

Many queries ask for the top N rows of several key ranges, for example the latest orders of a few customers. Instead of reading all matching rows and sorting them, the multiple key ranges optimization (MRO) scans each range of an index in ORDER BY order and keeps only the best N rows (top-N sort), stopping each range early.

With an index on orders(customer_id, order_date):

CREATE INDEX idx_orders_cust_date ON orders (customer_id, order_date);
SELECT /*+ RECOMPILE */ customer_id, id, order_date
FROM orders
WHERE customer_id IN (440, 812, 444)
ORDER BY order_date DESC
LIMIT 3;
customer_id id order_date
440 1651 2025-12-27
440 462 2025-12-15
812 428 2025-12-10

The trace shows mro: true and topnsort: true. Only 2 index keys are read:

INDEX SCAN (orders.idx_orders_cust_date) (key range: ((orders.customer_id= ?:0 ) or (orders.customer_id= ?:1 ) or (orders.customer_id= ?:2 )), desc_index: true)
...
SCAN (index: orders.idx_orders_cust_date), (btree time: 0, fetch: 9, ioread: 0, readkeys: 2, filteredkeys: 0, rows: 3, mro: true) (lookup time: 0, rows: 3)
ORDERBY (time: 0, topnsort: true)

With the hint NO_MULTI_RANGE_OPT the same query scans idx_orders_order_date backwards and reads 1,387 keys to find the 3 rows.

Conditions on a single table. MRO is considered for queries of this form:

SELECT ...
FROM table
WHERE col_1 = ? AND ... AND col_(j-1) = ?
AND col_j IN (?, ?, ...)
AND col_(j+1) = ? AND ... AND col_(p-1) = ?
AND key_filter_conditions
ORDER BY col_p [ASC|DESC], ..., col_(p+k-1) [ASC|DESC]
LIMIT n;
  • n is at most the system parameter multi_range_optimization_limit (default 100).
  • One index contains all columns used by the WHERE and ORDER BY clauses (no data filter), in this order: the equality columns, the single range (IN) column, further equality columns, then the ORDER BY columns.
  • Columns used in key filters are not ORDER BY columns.
  • Columns compared with a correlated subquery appear in the WHERE clause without a range condition.

Joins. MRO also works in joins if all ORDER BY columns belong to one table (the sort table), that table meets the single-table conditions, and every column of the sort table used in a join condition is in the index and compared without a range condition.

MRO is usually the fastest plan when it applies; NO_MULTI_RANGE_OPT turns it off.

An index can normally be used only if the query has a condition on its first column. Index skip scan (ISS) lifts this restriction when the first column has few distinct values: it searches the index once for each value of the first column, using the condition on the following columns.

order_items.discount_pct has only six values (0, 5, 10, 15, 20 and 25). With an index on (discount_pct, product_id, quantity), the hint INDEX_SS lets a search by product use it:

CREATE INDEX idx_oi_disc_prod ON order_items (discount_pct, product_id, quantity);
SELECT /*+ RECOMPILE INDEX_SS */ order_id, quantity FROM order_items WHERE product_id = 1618;
INDEX SCAN (order_items.idx_oi_disc_prod) (key range: order_items.product_id= ?:0 )
...
SCAN (index: order_items.idx_oi_disc_prod), (btree time: 0, fetch: 30, ioread: 0, readkeys: 10, filteredkeys: 0, rows: 4) (lookup time: 0, rows: 4)

ISS is considered only with the hint INDEX_SS, and only when:

  1. The query's conditions start at the second column of a composite index (WHERE c2 = x AND c3 = y …, or range conditions such as c2 < x);
  2. The index is not a filtered index;
  3. The first index column is not used in a range condition or key filter;
  4. The query is not hierarchical and contains no aggregate function.

/*+ INDEX_SS */ applies to all tables, /*+ INDEX_SS(t1, t2) */ to the listed tables; /*+ INDEX_SS() */ is ignored. NO_INDEX_SS prevents ISS. The optimizer still decides by cost; ISS pays off only when the first column has very few distinct values.

For DISTINCT or GROUP BY on the leading columns of an index (a subkey), a loose index scan jumps from one distinct subkey value to the next instead of reading every index entry. It is worthwhile when the grouped columns have few distinct values compared with the size of the index.

CREATE INDEX idx_oi_disc_prod ON order_items (discount_pct, product_id, quantity);
SELECT /*+ RECOMPILE INDEX_LS */ DISTINCT discount_pct FROM order_items WHERE discount_pct >= 0;
SORT (distinct)
INDEX SCAN (order_items.idx_oi_disc_prod) (key range: (order_items.discount_pct>= ?:0 ), covered: true, loose: true)
...
SCAN (index: order_items.idx_oi_disc_prod), (btree time: 0, fetch: 14, ioread: 0, readkeys: 6, filteredkeys: 0, rows: 6, covered: true, loose: true)

Six keys are read instead of 11,230. A loose index scan is considered only with the hint INDEX_LS (NO_INDEX_LS prevents it), and only when:

  1. The index covers the query;
  2. The query is SELECT DISTINCT, SELECT … GROUP BY, or returns a single row;
  3. All aggregate functions except MIN and MAX take DISTINCT arguments, and COUNT(*) is not used;
  4. The subkey has at most 1/100 of the cardinality of the whole index;
  5. The index has a condition that it can use: either on the grouped column (WHERE discount_pct >= 0 GROUP BY discount_pct) or on a following column (WHERE product_id > 10 GROUP BY discount_pct). Without any condition (SELECT … GROUP BY discount_pct), the subkey cannot be used.

A subkey is a prefix of a composite index: for an index on (a, b, c, d), (a), (a, b) and (a, b, c) are subkeys.

For a query with ORDER BY and LIMIT, CoraDB normally sorts the whole result and then keeps the first rows. With the in-memory sort optimization it keeps only the rows that can still be in the result, in an in-memory heap, and never builds the full sorted result. Traces show it as topnsort: true on the ORDERBY step.

The optimization is applied automatically when:

  • The query has ORDER BY and LIMIT, and no DISTINCT;
  • The rows to keep fit in the sort buffer (sort_buffer_size).

The limit is a size, not a row count: with a 2 MB sort buffer, about 500,000 rows of one INTEGER column fit, but only about 2,000 rows of a CHAR(1024) column.

In a join with ORDER BY and LIMIT, the SORT-LIMIT optimization applies the LIMIT to one table before the join, so that only a few rows are joined. The following query lists the five earliest orders since June 2025 with their customers:

SELECT /*+ RECOMPILE */ o.id, o.order_date, c.company_name
FROM orders o, customer c
WHERE o.customer_id = c.id AND o.order_date >= DATE'2025-06-01'
ORDER BY o.order_date
LIMIT 5;
idx-join (inner join)
outer: temp(sort limit)
subplan: iscan
class: o node[0]
index: idx_orders_order_date term[1]
cost: 3 card 100
cost: 3 card 100
inner: iscan
class: c node[1]
index: pk_customer_id term[0]
cost: 3 card 1000
sort: 2 asc
cost: 6 card 291

temp(sort limit) shows that the five first orders are selected before the customers are looked up. A SORT-LIMIT plan is possible when:

  • All tables in the ORDER BY clause are part of the SORT-LIMIT plan, and each of them is the foreign key side of a foreign key → primary key join (as orders here), the left side of a LEFT JOIN or the right side of a RIGHT JOIN;
  • The LIMIT is below the system parameter sort_limit_max_count (default 1000; 0 disables the optimization);
  • The query joins at least two tables, without cross joins, GROUP BY or DISTINCT;
  • The ORDER BY expressions can be evaluated while scanning: SELECT SUM(o.shipping_cost) … ORDER BY 1 LIMIT 5 cannot use it.

The hint NO_SORT_LIMIT turns the optimization off.