5

My table name students

uid  |  name
-----+-------
10   |  John
11   |  Smith

**Data types : **

uid  int(11)
name varchar(256)

My query :

SELECT name FROM students WHERE uid = '10'

Returns : John

My 2nd query :

SELECT name FROM students WHERE uid = '10someChar'

Returns : John

Why the second query returns John ?

6
  • include create script for your table Commented Aug 20, 2014 at 5:10
  • length for int(11) ??? Commented Aug 20, 2014 at 5:15
  • @phpsessionid include create script for the table students Commented Aug 20, 2014 at 5:19
  • What is create script ? Commented Aug 20, 2014 at 5:20
  • create table students(...).... Commented Aug 20, 2014 at 5:22

2 Answers 2

5

The uid column is integer, and the value you pass in the where clause is first coerced into an integer... and most integer-conversion algorithms just grab the first set of digits they can find in the string (and ignore anything non-matching after it)... thus it finds 10 and ignores the rest

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

4 Comments

I know coercion happens in programming languages, does SQL also works the same way? Its a new info for me.
SQL is a programming language :)
Anyway to avoid coercion so that my second query should return empty rows. Possible?
That's a different question (to which I don't know the answer). I recommend you ask a new question for that.
1

MySQL automatically converts numbers to strings as necessary, and vice versa.

It is also possible to convert a number to a string explicitly using the CAST() function.

Type Conversion

take a read.

MySQL ever tries to return something - even if it's the wrong type, he'll cast automatically.

You should filter at PHP to validate your business rule.

Postgresql should throw a exception

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.