21

I was making some tests, and it was a surprise when i was querying a table, and the query SELECT * FROM table WHERE email=0 returned all rows from the table.

This table has no '0' values and it's populated with regular e-mails.

Why this happens? This can lead to serious security problems.

Is there a way to avoid this without modifying the query?

Am i missing something here?

Thanks.

4 Answers 4

27

This is because it is converting the email field (which I assume is a varchar field) to an integer. Any field without a valid integer will equate to 0. You should make sure that you only compare string fields to string values (same goes for dates, comparing to dates). The query should be as follows.

SELECT * FROM table WHERE email='0';
1
  • 7
    do you think that mysql should be working this way? I think this is the spot where its easy to introduce bugs. I don't get why it needs to do such not making sense conversions like converting any string to 0. Why not better to convert 0 to '0' - it would make much more sense
    – Dariux
    Sep 29, 2014 at 13:22
7

Your email column is a CHAR or VARCHAR type. When you use the condition email = 0, MySQL is casting the contents of the email column to an integer in order to compare them with the 0 you supplied. Had you surrounded your 0 in quotes, the query would work as expected. (email = '0')

Converting a non-numeric string to an integer in MySQL will result in 0.

mysql> SELECT CAST('[email protected]' AS SIGNED);
+-------------------------------------+
| CAST('[email protected]' AS SIGNED) |
+-------------------------------------+
|                                   0 |
+-------------------------------------+

In contrast, if you attempted the same thing with numeric strings, they may cast correctly:

mysql> SELECT CAST('12345' AS SIGNED);
+-------------------------+
| CAST('12345' AS SIGNED) |
+-------------------------+
|                   12345 |
+-------------------------+
3

The email field is probably characters and you are matching numeric values.

Try with,

SELECT * FROM table WHERE email='0';
-1

if you want to get all record in which email column should not be blank or empty, then you can use

SELECT * FROM table WHERE email IS NOT NULL;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.