Published on

June 17, 2017

Understanding Decimal Precision in SQL Server

It’s time for another puzzle! In this blog post, we will explore a common issue that can occur when working with decimal values in SQL Server. Let’s dive in!

First, let’s set up a table called TestTable with three columns: ID, Price, and Discount. We will populate this table with some sample data.


-- Create table
CREATE TABLE #TestTable (ID INT, Price INT, Discount INT)

-- Populate table
INSERT INTO #TestTable (ID, Price, Discount)
SELECT 1, 1, 5
UNION ALL
SELECT 2, 2, 5
UNION ALL
SELECT 3, 3, 5
UNION ALL
SELECT 4, 4, 5

Now, let’s take a look at the data in our table:


SELECT *
FROM #TestTable

When we run the above script, we will see the following results:

IDPriceDiscount
115
225
335
445

Now, here comes the puzzle! We need to find the total discount value and the final price of each product after applying the discount. However, when we run the following script, we get incorrect results:


-- SELECT statement (Incorrect result)
SELECT ID, CAST((Price*Discount)/100 AS DECIMAL(10,2)) TotalDiscount,
		Price*CAST((Price*Discount)/100 AS DECIMAL(10,2)) FinalPrice
FROM #TestTable

The above script gives us all the answers as 0 (zero), which is incorrect. Can you figure out what went wrong?

The issue lies in the precision of the decimal value. In the script, we are performing calculations using the Price and Discount columns, both of which are integers. When we divide the result by 100, the decimal portion is truncated, resulting in a value of 0.

To fix this issue, we need to ensure that the calculations are performed using decimal values. We can achieve this by casting the Price and Discount columns as decimal before performing the calculations:


-- SELECT statement (Corrected result)
SELECT ID, CAST((CAST(Price AS DECIMAL(10,2))*CAST(Discount AS DECIMAL(10,2)))/100 AS DECIMAL(10,2)) TotalDiscount,
		CAST(Price AS DECIMAL(10,2))*CAST((CAST(Price AS DECIMAL(10,2))*CAST(Discount AS DECIMAL(10,2)))/100 AS DECIMAL(10,2)) FinalPrice
FROM #TestTable

Now, when we run the corrected script, we will get the expected results:

IDTotalDiscountFinalPrice
10.050.05
20.100.20
30.150.45
40.200.80

And there you have it! By ensuring the correct precision in our calculations, we were able to obtain the accurate total discount and final price values.

I hope you enjoyed this puzzle and learned something new about decimal precision in SQL Server. Feel free to share this puzzle with your friends and test their knowledge as well!

Stay tuned for more interesting SQL Server topics in our future blog posts. Happy coding!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.