-1

I am having a simple table users with 'userid' and 'username' fields. Please check commands as follow:

Select * from users where userid = '5'; --returns me 1 result - Right

Select * from users where userid = '5 shiv'; --returns me 1 result - Wrong

Why second query still returns me one result. What could be the problem? Is this a problem with the engine or MySQL itself?

halfer
  • 19,824
  • 17
  • 99
  • 186
shivshankar
  • 691
  • 2
  • 14
  • 31

2 Answers2

0

'5 shiv' evaluates to 5 and skips your String part after 5.And you have record with userid as 5.

Edit : Cast your expression to varchar

Select * from users where CAST (userid as varchar(10)) = '5 shiv';

Refer here for more

Community
  • 1
  • 1
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
0

The problem here is that MySQL is doing an implicit conversion from the string to an int when doing the comparison. For example :

SELECT * FROM cloths WHERE id = "5 shiv"

making the conversion explicit, this is what MySQL is doing:

SELECT * FROM cloths WHERE id = CAST("5 shiv" as int)

Instead, what you want to do is cast the id to a string, and compare that way. The solution is simply to:

SELECT * FROM cloths WHERE CAST (id as varchar(10)) = "5 shiv"

You can also check by Refer the link: Doc link

Community
  • 1
  • 1
Aman Aggarwal
  • 17,619
  • 9
  • 53
  • 81