Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Query - the Clause `where (varchar)` returns items starting with a number only. Why?

Tags:

sql

mysql

I have an interesting result and don't understand why.

SELECT * 
  FROM items im
 WHERE ItemNumber

ItemNumber is a varchar(50).

The results of this query is returning all items that the ItemNumber starts with a number. If the ItemNumber begins with a letter, it is excluded.

Does anyone have an explanation why the query interacts in this way?

like image 947
chafnan Avatar asked Jul 12 '12 13:07

chafnan


1 Answers

This is MySQL's strategy to be clever and assuming that it knows what you mean (as opposed to do what you write).

Any expression that evaluates to non-zero is considered true. Those items that start with a letter cannot (implicitely) be converted to a number thus it's considered zero and therfor "false". I would think that items that have the (character) value '0' are also excluded.

The following statement for example will happily delete all rows in your table:

DELETE FROM foobar
WHERE 42;

You cannot turn this behaviour off. Not even in ANSI mode will MySQL throw a syntax expression.

like image 123
a_horse_with_no_name Avatar answered Sep 22 '22 03:09

a_horse_with_no_name