Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does SQL Server round off results of dividing two integers?

Tags:

I have a table with a smallint column that contains percentages as whole numbers (i.e., 50, 75, 85, etc.)

When I divide this column by 100, as in

SELECT MY_COLUMN/100 AS PCT_AS_FRACTION FROM MY_TABLE 

the result is rounded to the nearest whole number. For example, for a row that contains the number "50", I get zero as my result.

I can duplicate this with a simple statement:

SELECT 50 / 100 AS TEST_VALUE 

Why is that, and how can I get more precision in my result?

like image 448
JosephStyons Avatar asked Apr 06 '09 21:04

JosephStyons


People also ask

How do you stop rounding in SQL?

You have to specify the number of places to the right of the decimal, like this: decimal(10,2) - ten digits, with two to the right of the decimal point.

Does integer division always round down?

Floor division simplified means that the real number result of the division is always rounded down. For example, 7 divided by 3 would give 1.75 . And using floor division, the result would be 1 because no matter what comes after the decimal point, we would always round down.

Does SQL do integer division?

Integer division in SQL takes place when both the dividend and the divisor are integers. Since they are integers, SQL wants to return an integer result to match the number type. In PostgreSQL and SQL Server, it is integer division. In MySQL and Oracle it is regular division (and the result of 1/4 is 0.25 ).

How do you get the decimal value when dividing in SQL?

Answers. SELECT ( Cast (Col1 AS Float) / Cast (Col2 AS Float) ) AS [Value] FROM ..... SELECT CAST(Col1 as decimal(10,2)) / CAST(col2 as decimal(10,2)) as [Value] FROM ... SELECT ( Cast (Col1 AS Float) / Cast (Col2 AS Float) ) AS [Value] FROM .....


1 Answers

When you do integer division (integer divided by integer) you always get an integer answer. 50/100 = .50, which is 0 in integer-speak.

Have you tried dividing MY_COLUMN by 100.0?

like image 86
Sniggerfardimungus Avatar answered Sep 23 '22 15:09

Sniggerfardimungus