MySQL WTF: “1, 2″ == “1″

by Kevin Grinberg on Apr 1, 2009

MySQL, how ridiculous you are. But seriously, though – what are you thinking?

I learned today (belatedly perhaps) that joining a VARCHAR field to an INT field does something… interesting. To illustrate, try to follow along:

CREATE TABLE `test` (`col_int` INT, `col_str` varchar(10));
INSERT INTO test(col_int, col_str) VALUES (1, '1'), (2, '1, 2'), (3, '2, 3');
SELECT * FROM test t1, test t2 WHERE t1.col_int = t2.col_str;

A pickier database would probably scream about type incompatibilities. But MySQL… MySQL doesn’t care, and silently truncates “1, 2″ to “1″, which it then casts to an int. And this is how you get the string “1, 2″ being equivalent to the int 1.

Only in MySQL-land.

* PostgreSQL fans: I know, I know. Shut up already.

Tags: ,

About Kevin Grinberg

Kevin Grinberg is a partner and developer at Active Frequency. He's been programming since the MARQUEE tag was frequently seen in the wild, and hopes to one day see lemurs in the wild.

  • http://www.edoburu.nl/ Diederik van der Boor

    wow… is this in any way or shape related to the chosed storage engine, or does this happen all over the board?