tags:

views:

146

answers:

5

Sorry if this is a repeat. 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 ect... How do I make SQL case insensitive for this wild-card search?

Again, apologies if this is repeated.

Oh, using MySql 5 on apache.

+1  A: 

I've always solved this using lower:

SELECT * FROM trees WHERE LOWER( trees.title ) LIKE  '%elm%'
Christopher W. Allen-Poole
and spoil index use
Col. Shrapnel
Does MySQL 5 have an ILIKE operator?
Luke Maurer
though for the %% search it doesn't matter anyway :)
Col. Shrapnel
@Luke Mysql don't need it. As it's collation responsibility.
Col. Shrapnel
(Wait, I thought everything in MySQL is case insensitive? Or is string equality case insensitive but matching case sensitive?!)
Luke Maurer
@Luke: depends on collation
Quassnoi
(Ah. Okay, back to things I actually know anything about :-) )
Luke Maurer
@Col. -- Admittedly, this is less than ideal for indexed columns, but it will work for a structure which is already in place. I've also found that case-insensitive searches are more often on columns which are not indexed anyway.
Christopher W. Allen-Poole
perfect! exactly want i wanted, i knew sql would have something like that, just didnt know. many thanks...
David Morrow
Default collation is already CI. So, the real problem not in this particular question. But it's still perfect SO-style answer.
Col. Shrapnel
A: 

You must set up proper encoding and collation for your tables.

Table encoding must reflect the actual data encoding. What is your data encoding?

To see table encoding, you can run a query SHOW CREATE TABLE tablename

Col. Shrapnel
+3  A: 

The case sensitivity is defined in the columns / tables / database collation settings. You can do the query under a specific collation in the following way:

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

for instance.

(Replace utf_general_ci with whatever collation you find useful). The _ci stands for case insensitive.

aioobe
+2  A: 
SELECT  *
FROM    trees
WHERE   trees.`title` COLLATE UTF8_GENERAL_CI LIKE '%elm%'
Quassnoi
that works too, is this more correct way of doing things? there is a possibility this will be localized so is using the encoding better than lower?
David Morrow
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 '%'.
Quassnoi
ALTER TABLE trees MODIFY COLUMN title VARCHAR(…) this seems the best way, thanks much... let sql do the work
David Morrow
A: 

When I want to develop insensitive case searchs, I always convert every string to lower case before do comparasion

Rbacarin