Use temporary tables to reduce sorting scope
You can use a temporary, ordered subset of a table to increase the speed of a query. The temporary table can also simplify the work of the query optimizer, cause the optimizer to avoid multiple-sort operations, and simplify the work of the optimizer in other ways.
SELECT cust.name, rcvbles.balance, ...other columns...
FROM cust, rcvbles
WHERE cust.customer_id = rcvbles.customer_id
AND rcvbls.balance > 0
AND cust.postcode LIKE '98_ _ _'
ORDER BY cust.name
This query reads the entire cust table. For every row with the specified postal code, the database server searches the index on rcvbles.customer_id and performs a nonsequential disk access for every match. The rows are written to a temporary file and sorted. For more information about temporary files, see Configure dbspaces for temporary tables and sort files.
This procedure is acceptable if the query is performed only once, but this example includes a series of queries, each incurring the same amount of work.
SELECT cust.name, rcvbles.balance, ...other columns...
FROM cust, rcvbles
WHERE cust.customer_id = rcvbles.customer_id
AND cvbls.balance > 0
INTO TEMP cust_with_balance
SELECT *
FROM cust_with_balance
WHERE postcode LIKE '98_ _ _'
ORDER BY cust.name
Each query reads the temporary table sequentially, but the table has fewer rows than the primary table.