Why SELECT 1/5
result is 0
instead of 0.2
in SQL server Transact SQL?
IF i use SELECT 1.0/5
result is 0.200000
Why SELECT 1/5
result is 0
instead of 0.2
in SQL server Transact SQL?
IF i use SELECT 1.0/5
result is 0.200000
I'm not sure why you would expect anything else here. If you have 2 values of the same data type and do something (that isn't explicitly or implicitly casting the data type) with them why would you expect to get a different data type back? This is standard behaviour across every language, not just T-SQL or even SQL as a whole.
As I mentioned in the comment, if you had 2 varchar
values and concatenated them, you wouldn't expect to get an nvarchar
or perhaps a char
back; you'd expect to get a varchar
back. If you subtracted a datetime
from a datetime
(which as much as I hate, you can do) you wouldn't expect a time
or perhaps a int
value back.
Just because you're doing division doesn't change that; by providing int
values you are, by definition, stating you want a int
value back.
For the latter statement, SELECT 1.0/5
, you have 2 different data types, a decimal(2,1)
and an int
respectively. When dealing with data of differing types one of the data types has to be implicitly converted to the data type of the other; which is determined by Data Type Precedence. decimal
has a higher precedence that int
, so that int
is converted first, and then the division completed.