Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SELECT ... WHERE last_name = 0 returns all rows?

Tags:

sql

mysql

I've got a simple table in MySQL:

create table t_users(
    user_id INT NOT NULL AUTO_INCREMENT,
    first_name VARCHAR(100) NOT NULL,
    last_name  VARCHAR(100) NOT NULL,
PRIMARY KEY(user_id));

I'm puzzled to discover that the following query returns ALL rows:

SELECT first_name, last_name
FROM t_users
WHERE last_name = 0;

Can someone explain that? Thank you!

like image 773
Moshe Kravchik Avatar asked Jun 12 '15 10:06

Moshe Kravchik


1 Answers

In MySQL if you compare a string and a number, the string will be converted to a number which results in 0 for each string. And

0 = 0

is true.

If a string would start with a number - say 123abc then it would result in 123.

SQLFiddle demo

When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. For example, MySQL automatically converts numbers to strings as necessary, and vice versa.

Documentation

like image 84
juergen d Avatar answered Nov 15 '22 09:11

juergen d