|
|
![]() |
|
|
|
|
||
|
Performance of the SQL LIKE Predicate Hey, Ted: I have heard that SQL's LIKE predicate cannot take advantage of indexes. Can I use indexes to speed up a query that uses LIKE?
-- Jim LIKE has long had the reputation of being a poor performer, probably because of the way it has been implemented on various platforms. In some cases, using LIKE in a query guarantees a database scan (e.g., reading the entire table). If the expression begins with a wildcard character--an underscore ( _ ) to represent a single character, a percent sign (%) to represent multiple characters--then the query will require a database scan in order to select the correct records. However, if the expression begins with some other character, and there is an index on the field that is being tested, then the query governor may be able to use the index. The process of speeding up a query containing LIKE is no different from the process of speeding up any query. One method is to use Visual Explain, which is part of the iSeries Navigator (formerly known as Operations Navigator), to tell you what steps the query engine has to take to retrieve the data. Another method is to run the SQL query interactively in debug. Then take a look at the job log. If you see messages like the following, you may be able to speed up the query. Access path built for file MYFILE. Access path suggestion for file MYFILE. The first message tells you that the query engine built an access path to fulfill the query. The second message indicates that you may be able to improve performance of the query by building a certain access path. Press F1 on the message to see the second-level text. That's where the recommendation will be. If you see the following message, then the query engine has used an access path. Access path of file MYFILE2 was used by query. To get back to your original question, I know that the query engine will use an access path to answer a LIKE condition because I used such a query when working up this example, and the job log messages shown above came from the test session. In my test, the LIKE predicate was "WHERE MYFIELD LIKE '5%'. When I changed the literal from 5% to %5%, however, the job log showed the following messages: All access paths were considered for file RANDATA. Access path built for file RANDATA. This is a good technique to learn because it works with SQL, Query, Open Query File (OPNQRYF) command, and anything else (including non-IBM software) that uses the query engine. Visual Explain is good, but it only works with SQL queries. -- Ted
|
Editors
Contact the Editors |
|
Last Updated: 12/06/02 Copyright © 1996-2008 Guild Companies, Inc. All Rights Reserved. |