mluebke
mluebke

Reputation: 8829

Using LIKE vs. = for exact string match

First off, I recognize the differences between the two:
- Like makes available the wildcards % and _
- significant trailing whitespace
- colation issues

All other things being equal, for an exact string match which is more efficient:

SELECT field WHERE 'a' = 'a';

Or:

SELECT field WHERE 'a' LIKE 'a';

Or: Is the difference so insignificant that it doesn't matter?

Upvotes: 34

Views: 55528

Answers (2)

paxdiablo
paxdiablo

Reputation: 882756

In a decent DBMS, the DB engine would recognise that there were no wildcard characters in the string and implicitly turn it into a pure equality (not necessarily the same as =). So, you'd only get a small performance hit at the start, usually negligible for any decent-sized query.

However, the MySQL = operator doesn't necessarily act the way you'd expect (as a pure equality check). Specifically, it doesn't by default take into account trailing spaces for CHAR and VARCHAR data, meaning that:

SELECT age WHERE name = 'pax'

will give you rows for 'pax', 'pax<one space>' and 'pax<a hundred spaces>'.

If you want to do a proper equality check, you use the binary keyword:

SELECT field WHERE name = binary 'pax'

You can test this with something like:

mysql> create table people (name varchar(10));

mysql> insert into people value ('pax');
mysql> insert into people value ('pax ');
mysql> insert into people value ('pax  ');
mysql> insert into people value ('pax   ');
mysql> insert into people value ('notpax');

mysql> select count(*) from people where name like 'pax';
1

mysql> select count(*) from people where name = 'pax';
4

mysql> select count(*) from people where name = binary 'pax';
1

Upvotes: 10

Suroot
Suroot

Reputation: 4423

I would say that the = comparator would be faster. The lexical doesn't send the comparison to another lexical system to do general matches. Instead the engine is able to just match or move on. Our db at work has millions of rows and an = is always faster.

Upvotes: 34

Related Questions