Using LIKE vs. = for exact string match

后端 未结 2 1301
轮回少年
轮回少年 2020-12-14 15:15

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

相关标签:
2条回答
  • 2020-12-14 15:52

    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
    
    0 讨论(0)
  • 2020-12-14 15:53

    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.

    0 讨论(0)
提交回复
热议问题