Sometimes there is more than one possible way for the SQL Anywhere database server to execute a query with an ORDER BY clause. You can use indexes to enable the database server to search the tables more efficiently.
An example of a query that can be executed in more than one possible way is one that has both a WHERE clause and an ORDER BY clause.
SELECT * FROM Customers WHERE ID > 300 ORDER BY CompanyName;
In this example, SQL Anywhere must decide between two strategies:
Go through the entire Customers table in order by company name, checking each row to see if the customer ID is greater than 300.
Use the key on the ID column to read only the companies with ID greater than 300. The results would then need to be sorted by company name.
If there are very few ID values greater than 300, the second strategy is better because only a few rows are scanned and quickly sorted. If most of the ID values are greater than 300, the first strategy is much better because no sorting is necessary.
Creating a two-column index on ID and CompanyName could solve the example above. SQL Anywhere can use this index to select rows from the table in the correct order. However, keep in mind that indexes take up space in the database file and involve some overhead to keep up to date. Do not create indexes indiscriminately.
For more information, see Using indexes.