help: forcing key index sort
Posted in 1996
Topics: Performance & Tuning, SQL Development & Query Writing, Connectivity: ESQL/C, 4GL & Embedded SQL
I want to force use of the primary key index on the
following embedded sql query:
SELECT a, b, ... and other stuff ...
FROM tbl_name
WHERE a >= ?
AND b > ?;
The primary key is a + b.
The problem is that as shown the optimizer elects to
ignore the index because the number of records is very
small (less than 10). In production, the number of
rows will be much larger. The rows are in more or
less random order. The concept is to OPEN a cursor
for the above SELECT, then fetch a fixed number of
rows. After completing the last fetch, the last row
is saved and used as input for the next OPEN of the
same cursor which will occur after some other actions
which may include a COMMIT which will invalidate the
cursor. The theory is that the WHERE clause will
require the use of the index. EXPLAIN shows that a
SEQUENTIAL SCAN is performed rather than an indexed
search. I believe this will occur when the table is
large, but the optimizer is over riding the index when
the table is small.
I have found that I can force the correct result by
using SELECT DISTINCT, but I am suspicious that this
may result in a full table scan when the cursor is
opened BEFORE any rows are returned. This is not
acceptable. EXPLAIN reports that SEQUENTIAL ACCESS is
used even when DISTINCT is present. If the use of
DISTINCT in this case simply uses the index on a large
table and sorts the results on a small table, it will
be OK.
There ought to be a way to force the optimizer to use
the index for a query such as this. I think in ORACLE
the WHERE clause would force the index regardless of
the size of the table. I have not been able to find
anything in the SQL ANSI standard or the Informix
manuals to indicate how to force an index.