6

In many programming languages there is the basic equals operator which will see if the text of two strings are equal:

if ("Hi" == "hi") {
  //this code runs
}

But there is also the strict equal to operator:

if ("Hi" === "hi") {
  //this code will never run
}

Is there an equivalent operator for the above code snippet in MySQL? The = operator just doesn't cut it. If I run:

SELECT * FROM users WHERE name = 'john';

MySQL will return rows with a John, with a capital "J".

Thank you for your time.

Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195

2 Answers2

12

You can use the COLLATE operator to convert the column to a case-sensitive collation:

SELECT * FROM users WHERE name LIKE 'john' COLLATE utf8_bin

MySQL documentation on case sensitivity.

Zane Bien
  • 22,685
  • 6
  • 45
  • 57
  • Hmm... my table collation is set to `latin1_swedish_ci`. I'm getting this error when running the above code sample `#1253 - COLLATION 'latin1_general_cs' is not valid for CHARACTER SET 'utf8'` – Oliver Spryn Jun 25 '12 at 17:02
  • Try `utf8_bin` collation then. – ypercubeᵀᴹ Jun 25 '12 at 17:04
  • Yes, I tried those, with no avail. Here is the SQL to create the table I am using `CREATE TABLE IF NOT EXISTS users ( /* Some columns, indexes, and primary keys */ ) ENGINE=MyISAM DEFAULT CHARSET=latin1;` – Oliver Spryn Jun 25 '12 at 17:08
  • There's no way you have latin1_swedish_ci for your UTF8 character set either. It's important to note the difference between LIKE and = here also. When using `=`, it ignores trailing spaces for the comparison, whereas LIKE doesn't ignore trailing spaces. LIKE is more strict and may be what you want. – Marcus Adams Jun 25 '12 at 17:10
2

You can use STRCMP :

SELECT * FROM users WHERE STRCMP(name, 'john') = 0;

Note :

  • 0 = same
  • -1 = first element smaller
  • 1 = first element bigger

You must use COLLATES if you're using MySQL 4.0+ (STRCMP is no longer case sensitive) :

  • COLLATE utf8_general_ci = case insensitive (ci)
  • COLLATE utf8_general_cs = case sensitive (cs)
Lukasz Czerwinski
  • 13,499
  • 10
  • 55
  • 65
zessx
  • 68,042
  • 28
  • 135
  • 158