avon_verma
avon_verma

Reputation: 1249

Mysql: difference between intvalue='1' and intvalue=1

On an int column, is there difference between doing..

SELECT .. int = '1' and SELECT .. int = 1, and which would be preferred?

Upvotes: 2

Views: 715

Answers (4)

Stefaan Colman
Stefaan Colman

Reputation: 3705

The first one (int = '1') compares a string to an integer (so mysql automaticly converts this) The seconds one (int = 1) compares an integer to an integer field (no conversion needed).

So the second one is preferred

Upvotes: 0

Nanne
Nanne

Reputation: 64399

One difference is that if your query has a var that can be empty you'll get this

SELECT .... int = ''

versus

SELECT .... int = 

And the last one is invalid SQL. The first one will give you all empty values (maybe nothing if there are none ofcourse). although I agree if one says it should be caught before the query, it is a difference that can byte you :)

Upvotes: 0

Oded
Oded

Reputation: 498992

Not a MySql expert, but I would say that the first one (int = '1') would cause a conversion of the string to an integer before comparison.

So to avoid this conversion, I would always go with the right data type.

Additionally, a conversion is not guaranteed to succeed (or give the correct results).

Upvotes: 1

Daniel
Daniel

Reputation: 28074

Use int = 1, because int = '1' is internally converted to int = cast('1' as int)

Upvotes: 3

Related Questions