1

I have a table name workspaces with id has data type = bigint(20) unsigned I'm trying to query my database as the following:

  1. SELECT * FROM workspaces WHERE id = 1;

  2. SELECT * FROM workspaces WHERE id = '1.a';

Both of them are returns the correct result. But I think the (2) statement is wrong, why sql still return correct value right? What is the reason? Could you help me to understand why? Thank you so much.

Here is test case on db<>fiddle.

3
  • Table definition? Commented Mar 16, 2020 at 7:31
  • @APC MySQL copes with this by just taking the first leading characters which can form a number (read: first leading digits), and then doing the comparison based on that. Evil. It should fail, which is what would happen on Oracle. Commented Mar 16, 2020 at 7:40
  • @TimBiegeleisen - yes, I was reminded of how JavaScript fails silently when I coded a data type mismatch. Commented Mar 16, 2020 at 7:41

3 Answers 3

1

MySQL has complex casting rules for what happens when you try to compare a string literal (e.g. 1.a) against an integer column (id). What is happening here is that MySQL is taking the leading numbers from the string and then forming a number based on that. As a result, the check becomes 1 = 1, which is true for that particular record which is being returned.

On most other databases, your second query would not even execute, which is generally all the better for you. You should not mix numeric and non numeric types in the same comparison.

Sign up to request clarification or add additional context in comments.

Comments

0

It extracts the number from string.

For example "1.a"=1

I hope it helps.

1 Comment

In my database I insert 2 records data sample only are: id = 1 and id =2 to test above query. And when I execute both of the statements, mySQL always returns result id =1
0

In a situation where the sides of a comparison operator (= in this case) don't match, the database will do its best to convert one side the other's type. If there's absolutely no way of doing it, it will throw an error, but it still won't be a syntax error (since the query itself has a valid form), but some error about type conversion.

MySQL, specifically, notoriously plays fast and loose with type conversions. In the case of converting a character literal to a numeric type, if the string starts with a digit, it will convert the starting sequence of digits to a number and ignore anything after it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.