May 16, 2010

MySQL strings and upper case

MySQL strings are compared case insensitively. A field with a value of "something" is equal to "SOMETHING", making it difficult to compare upper and lower case strings. A simple workaround is to use a hashing function to compare them. MD5 is overkill for this, but it works :P

Finding all records with an upper cased field:
SELECT IdField, SomeField 
  FROM DatabaseTable 
  WHERE MD5(SomeField)=MD5(UCASE(SomeField)) 

Converting all field values to pseudo-proper case (first character caps, rest lower case):
UPDATE DatabaseTable 
  SET SomeField = CONCAT(UCASE(MID(SomeField,1,1)), LCASE(MID(SomeField,2))) 
  WHERE MD5(SomeField)=MD5(UCASE(SomeField))

No comments:

Post a Comment