This
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%';
is slower than this
SELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value';
but what about this?
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value';
My testing indicates the second and third examples are exactly the same. If that's true, my question is, why ever use "=" ?
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.
Using '=' operator is faster than the LIKE operator in comparing strings because '=' operator compares the entire string but the LIKE keyword compares by each character of the string.
The Oracle "with" clause will help performance in situations where your query contains several identical sub queries. Instead of re-computing the repeating sub queries, it will query or aggregate once, assign a name to the resulting data and refer to it.
There is a clear difference when you use bind variables, which you should be using in Oracle for anything other than data warehousing or other bulk data operations.
Take the case of:
SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE :b1
Oracle cannot know that the value of :b1 is '%some_value%', or 'some_value' etc. until execution time, so it will make an estimation of the cardinality of the result based on heuristics and come up with an appropriate plan that either may or may not be suitable for various values of :b, such as '%A','%', 'A' etc.
Similar issues can apply with an equality predicate but the range of cardinalities that might result is much more easily estimated based on column statistics or the presence of a unique constraint, for example.
So, personally I wouldn't start using LIKE as a replacement for =. The optimizer is pretty easy to fool sometimes.
Check out the EXPLAIN PLAN for both. They generate the same execution plan, so to the database, they're the same thing.
You would use = to test for equality, not similarity. If you're controlling the comparison value as well, then it doesn't make much of a difference. If that's being submitted by a user, then 'apple' and 'apple%' would give you much different results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With