Read more

In MySQL, a zero number equals any string

Andreas Robecke
February 21, 2012Software engineer

In MySQL comparing zero to a string 0 = "any string" is always true!

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

So when you want to compare a string with a value of an integer column, you have to cast your integer value into a string like follows:

SELECT * from posts WHERE CAST(posts.comments_count AS CHAR) = '200' 

Of course this is usually not what you want to use for selecting your data as this might cause some expensive database operations. No indexes can be used and a full table scan will always be triggered.

If possible, cast the compared value in your application to avoid rewriting all lines in the database. ActiveRecord does that automagically, for example.

PostgreSQL is not affected

PostgreSQL will throw an error when you compare an integer with a string without explicit casting.

In authentication, this behavior may be used to match rows without knowing a secret token:

Posted by Andreas Robecke to makandra dev (2012-02-21 16:14)