Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Optimization, "like" vs "="

Tags:

mysql

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"
like image 458
NinjaCat Avatar asked Aug 26 '10 15:08

NinjaCat


People also ask

Is like faster than in SQL?

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.

Why is SQL like slow?

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.

What can I use instead of like in SQL?

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 .


2 Answers

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.

like image 143
raveren Avatar answered Sep 18 '22 12:09

raveren


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.

like image 22
Sarfraz Avatar answered Sep 19 '22 12:09

Sarfraz