
Compare strings exactly in MySQL
To reliably compare the exact value of two fields you can use the md5
for comparison. This might be helpful if you are comparing two strings that have different case, or perhaps some hidden characters you can’t see.
For example typically in MySQL the following comparison of blog vs Blog will give you a match despite a difference in case because most servers use a case insensitive collation _ci
.
select case
when 'blog' = 'Blog'
then 'match'
else 'no match'
end as result;Result: match
Yes you could play around with collations in the session for this to work but a far simpler approach is using md5
:
select case
when md5('blog') = md5('Blog')
then 'match'
else 'no match'
end as result;Result: no match
This can be applied for other non-printable/hidden characters in the column ensuring you do have an exact match on two values (or not).