mysqlsqlsql-likecase-insensitive

How can I search (case-insensitive) in a column using LIKE wildcard?


I looked around some and didn't find what I was after so here goes.

SELECT * FROM trees WHERE trees.`title` LIKE  '%elm%'

This works fine, but not if the tree is named Elm or ELM etc...

How do I make SQL case insensitive for this wild-card search?

I'm using MySQL 5 and Apache.


Solution

  • SELECT  *
    FROM    trees
    WHERE   trees.`title` COLLATE UTF8_GENERAL_CI LIKE '%elm%'
    

    Actually, if you add COLLATE UTF8_GENERAL_CI to your column's definition, you can just omit all these tricks: it will work automatically.

    ALTER TABLE trees 
     MODIFY COLUMN title VARCHAR(…) CHARACTER 
     SET UTF8 COLLATE UTF8_GENERAL_CI. 
    

    This will also rebuild any indexes on this column so that they could be used for the queries without leading '%'