# Re: SQL Division Conundrum

 Subject: Re: SQL Division Conundrum From: Joe Pluta Date: Sun, 17 Mar 2013 20:35:15 -0500 List-archive: List-help: List-id: Midrange Systems Technical Discussion List-post: List-subscribe: , List-unsubscribe: ,

Welcome to the evils of implied decimal precision in SQL. One of the many ways in which SQL isn't a business language.

There are rules. You begin to run into some of these rules in larger RPG expressions as well, but RPG makes better assumptions (IMO). Anyway, here are the rules for SQL Server 2000. They're quite simple:

http://msdn.microsoft.com/en-us/library/aa258274.aspx

</sarc>

Joe

Boss was trying to sum two decimal fields and get the percentage of the
sums. It looked easy, but the percentage always came out as zero.

I did some experimentation and here's a simulation that anyone can run:

select sum(CDTDUE) CDTDUE, sum(BALDUE) BALDUE,
(sum(CDTDUE) / sum(BALDUE)) *100 pct
from qiws/QCUSTCDT

The first two sum statements clearly show that the fields are numeric
with 2 decimal places.

The PCT field is zero, because it apparently is resulting as an integer.

If I force the first sum in the division to be decimal, like this:

select sum(CDTDUE) CDTDUE, sum(BALDUE) BALDUE,
(decimal(sum(CDTDUE),11,2) / sum(BALDUE)) *100 pct
from qiws/QCUSTCDT

then pct comes out to 2.29787594861576292000.

If I instead force the second sum in the division to decimal, like this:

select sum(CDTDUE) CDTDUE, sum(BALDUE) BALDUE,
(sum(CDTDUE) / decimal(sum(BALDUE),11,2) ) *100 pct
from qiws/QCUSTCDT

then pct comes out as zero, again apparently an integer.

So, apparently we are missing something in the SQL rules of arithmetic.
Does anyone know what?

Thanks, Sam

On V7R1, cume from around October. But I see the same results on V5R3.