I have a table with columns like this:
| Country.Number | CountryName |
| US.01 | USA |
| US.02 | USA |
I'd like to modify this to:
| Country | Number | CountryName |
| US | 01 | USA |
| US | 02 | USA |
Regarding optimization, is there a difference in performance if I use:
select * from mytable where country.number like "US.%"
or
select * from mytable where country = "US"
1 Answer. 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 SQL LIKE operator very often causes unexpected performance behavior because some search terms prevent efficient index usage. That means that there are search terms that can be indexed very well, but others can not. It is the position of the wild card characters that makes all the difference.
You may come across the situation, where you need alternate to “like” keyword of SQL, that is to search for sub-string in columns of the table. The one way to achieve it to use instr() function, instr() function takes 3 parameters in account .
The performance difference will most likely be miniscule in this particular case, as mysql uses an index on "US.%"
. The performance degradation is mostly felt when searching for something like "%.US"
(the wildcard is in front). As it then does a tablescan without using indices.
EDIT: you can look at it like this:
MySql internally stores varchar
indices like trees with first symbol being the root and branching to each next letter.
So when searching for = "US"
it looks for U
, then goes one step down for S
and then another to make sure that is the end of the value. That's three steps.
Searching for LIKE "US.%"
it looks again for U
, then S
, then .
and then stops searching and displays the results - that's also three steps only as it cares not whether the value terminated there.
EDIT2: I'm in no way promoting such database denormalization, I just wanted to attract your attention that this matter may not be as straightforward as it seems at first glance.
The later query:
select * from mytable where country = "US"
should be much faster because mySQL does not have to look for wildcards patterns unlike LIKE
query. It just looks for the value that has been equalized.
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