MySQL: unique case sensitive varchar
MySQL is case insensitive by default and normally it is more than enough. However one of my recent projects required a case sensitive varchar column with unique index. Latter would immediately trigger ‘Duplicate entry … for key …’ error for “the same” strings.
CREATE TABLE file ( id INT AUTO_INCREMENT, name VARCHAR(100) NOT NULL, PRIMARY KEY(id), UNIQUE(name) ); INSERT INTO file (name) VALUES ('test.txt'), ('test.TXT'); |
For example in the query above the second insert fails returning that error.
A way to address this is just to use a case sensitive collation (e.g. utf8_bin).
CREATE TABLE file ( id INT AUTO_INCREMENT, name VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, PRIMARY KEY(id), UNIQUE(name) ); |
Exactly what I was looking for! Another search result mentions utf8_cs, which did not work with my version of msyql
Perfect, this worked for me where changing the table collation did not! Thanks
I ran into this same problem, thanks for the fix!