Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is substr or LIKE faster in Oracle?

Tags:

sql

oracle

Would

WHERE substr(my_field,1,6) = 'search' 

or

WHERE my_field LIKE 'search%' 

be faster in Oracle, or would there be no difference?

like image 775
Brian Ramsay Avatar asked Jul 28 '09 22:07

Brian Ramsay


People also ask

Which is faster substring or like?

I would profile both. But I would guess the 'LIKE' would be much faster, because it uses the binary search on the index (if the field is indexed). If you use the SUBSTR method, you will end up with a full table scan, as Oracle has to process row by row the function.

Which one is faster in Oracle?

Answers. Exist is more faster than IN because IN doesn't use indexes at the time of fetching but Exist uses Index at the time of fetching.

Which is faster decode or case in Oracle?

There is very little performance difference between CASE and DECODE on the same platform. One has to run 100's of 1000's of iterations to see a difference, and even then it is debatable of whether that difference is just due to the CASE vs DECODE.

How many arguments does substr () will take?

The SUBSTRING function requires two arguments and can take a third.


2 Answers

Assuming maximum performance is the goal, I would ideally choose SUBSTR(my_field,1,6) and create a function-based index to support the query.

CREATE INDEX my_substr_idx     ON my_table( substr( my_field,1,6 ) ); 

As others point out, SUBSTR(my_field,1,6) would not be able to use a regular index on MY_FIELD. The LIKE version might use the index, but the optimizer's cardinality estimates in that case are generally rather poor so it is quite likely to either not use an index when it would be helpful or to use an index when a table scan would be preferable. Indexing the actual expression will give the optimizer far more information to work with so it is much more likely to pick the index correctly. Someone smarter than I am may be able to suggest a way to use statistics on virtual columns in 11g to give the optimizer better information for the LIKE query.

If 6 is a variable (i.e. you sometimes want to search the first 6 characters and sometimes want to search a different number), you probably won't be able to come up with a function-based index to support that query. In that case, you're probably better off with the vagaries of the optimizer's decisions with the LIKE formulation.

like image 182
Justin Cave Avatar answered Oct 02 '22 11:10

Justin Cave


Of the two options provided, definitely LIKE. The substring method will have to be executed against all rows in the table. Using LIKE will allow the use of indexes.

To check my answer, just profile the results. It should be clear as day.

like image 22
beach Avatar answered Oct 02 '22 10:10

beach