Difference between SQL LIKE without percent signs and equal (=) in WHERE clause

前端 未结 2 577
萌比男神i
萌比男神i 2021-01-13 06:53

Are there any differences in the results of these two queries other than performance?

SELECT * FROM pet WHERE name LIKE \'Spot\';
SELECT * FROM pet WHERE nam         


        
2条回答
  •  没有蜡笔的小新
    2021-01-13 07:31

    In practice, LIKE with no wildcards is functionally equivalent to =. However, they are not the same! The obvious difference is that = doesn't treat \, %, and _ in any special way, but LIKE does.

    The documentation is pretty clear on this:

    Per the SQL standard, LIKE performs matching on a per-character basis, thus it can produce results different from the = comparison operator:

    In addition to collation differences, trailing spaces matter:

    In particular, trailing spaces are significant, which is not true for CHAR or VARCHAR comparisons performed with the = operator:

    In practice, the strings being compared usually have the same collation, don't have trailing spaces, and special characters are ignored, so LIKE is sometimes used as a replacement for = (especially because LIKE without wildcards at the beginning of the pattern can also make use of an index).

提交回复
热议问题