1

The query executed should match the story_id with the provided string but when I execute the query it's giving me a wrong result. Please refer to the screenshot.

enter image description here

1
  • 1
    you can show your sample table for it Commented Nov 29, 2018 at 8:06

2 Answers 2

8

story_id column in your case is of INT (or numeric) datatype.

MySQL does automatic typecasting in this case. So, 5bff82... gets typecasted to 5 and thus you get the row corresponding to story_id = 5

Type Conversion in Expression Evaluation

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 strings to numbers as necessary, and vice versa.

Now, ideally your application code should be robust enough to handle this input. If you expect the input to be numeric only, then your application code can use validation operations on the data (to ensure that it is only a number, without typecasting) before sending it to MySQL server.

Another way would be to explicitly typecast story_id as string datatype and then perform the comparison. However this is not recommended approach as this would not be able to utilize Indexing.

SELECT * FROM story
WHERE (CAST story_id AS CHAR(12)) = '5bff82...'

If you run the above query, you would get no results.

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

Comments

0

you can also use smth like this:

SELECT * FROM story
WHERE regexp_like(story_id,'^[1-5]{1}(.*)$');

for any story_ids starting with any number and matching any no of charatcers after that it wont match with story_id=5; AND if you explicitly want to match it with a string;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.