Tuesday, July 08, 2014

Dividing 2 numbers in sql result in either Integer, float, decimal

Dividing 2 numbers in sql gives different results based on their datatypes
When an integer is divided by another integer then result will be integer
When a float is divided by another integer or vice verse or 
a float number is divided by another float number then result will be float.
The following queries shows the differences:
 
SELECT 5   / 10   AS INTQTY --0
SELECT 5   / 10.0 AS DECQTY --0.500000
SELECT 5.0 / 10   AS DECQTY --0.500000
SELECT 5.0 / 10.0 AS DECQTY --0.500000
 
SELECT CONVERT(DECIMAL(16, 2), 5   / 10  ) AS INTQTY --0.00
SELECT CONVERT(DECIMAL(16, 2), 5   / 10.0) AS INTQTY --0.50
SELECT CONVERT(DECIMAL(16, 2), 5.0 / 10  ) AS INTQTY --0.50
SELECT CONVERT(DECIMAL(16, 2), 5.0 / 10.0) AS INTQTY --0.50
 
SELECT CAST(5   / 10   AS DECIMAL(16, 2)) AS INTQTY --0.00
SELECT CAST(5   / 10.0 AS DECIMAL(16, 2)) AS INTQTY --0.50
SELECT CAST(5.0 / 10   AS DECIMAL(16, 2)) AS INTQTY --0.50
SELECT CAST(5.0 / 10.0 AS DECIMAL(16, 2)) AS INTQTY --0.50