Ordering optimization

 

This section describes how DB2 Universal Databaseā„¢ for iSeriesā„¢ implements ordering techniques, and how optimization choices are made by the query optimizer. The query optimizer can use either index ordering or a sort to implement ordering.

 

Sort Ordering implementation

The sort algorithm reads the rows into a sort space and sorts the rows based on the specified ordering keys. The rows are then returned to the user from the ordered sort space.

 

Index Ordering implementation

The index ordering implementation requires an index that contains all of the ordering columns as contiguous leftmost key columns. The database manager accesses the individual rows through the index in index order, which results in the rows being returned in order to the requester.

This implementation can be beneficial if an application does not need to retrieve all of the ordered results, or if an index already exists that matches the ordering columns. When the ordering is implemented with an index, and a permanent index does not already exist that satisfies ordering columns, a temporary index is created. The ordering columns specified within the query are used as the key columns for this index.

 

Optimizing ordering by eliminating ordering columns

All of the ordering columns are evaluated to determine if they can be removed from the list of ordering columns. Only those ordering columns that have isolatable selection predicates with an equal operator specified can be considered. This guarantees that the column can match only a single value, and will not help determine in the order. This processing is done to allow the optimizer to consider more indexes as it implements the query, and to reduce the number of columns that will be added as key columns to a temporary index. The following SQL example illustrates a query where the optimizer might eliminate an ordering column.

DECLARE DEPTEMP CURSOR FOR 
  SELECT EMPNO, LASTNAME, WORKDEPT 
  FROM CORPDATA.EMPLOYEE 
  WHERE EMPNO = '000190' 
  ORDER BY EMPNO, LASTNAME, WORKDEPT

 

Optimizing ordering by adding additional ordering columns

The same logic that is applied to removing ordering columns can also be used to add additional grouping columns to the query. This is done only when you are trying to determine if an index can be used to implement the ordering. The following example illustrates a query where the optimizer might add an additional ordering column.

CREATE INDEX X1 ON EMPLOYEE (LASTNAME, EMPNO, WORKDEPT)


DECLARE DEPTEMP CURSOR FOR SELECT LASTNAME, WORKDEPT FROM CORPDATA.EMPLOYEE WHERE EMPNO = '000190' ORDER BY LASTNAME, WORKDEPT

For this query request, the optimizer can add EMPNO as an additional ordering column when considering X1 for the query.

 

Parent topic:

Processing queries: Overview