AVG function returns wrong average I have a simple table with a column of type REAL. 

There are 2 rows in the table and the values are 0.23 and 0.24. If I run the following:

SELECT AVG(MyColumn) FROM dbo.MyTable


I would expect to get a result of 0.235 but actually I get 0.2349999901234.

Can somebody please tell me why?
Stop using REAL and use DECIMAL instead. REAL and FLOAT are approximate data types and can't represent all numbers in the nice, rounded way you are used to. Compare these:

DECLARE @a REAL = 0.23, @b REAL = 0.24;
SELECT AVG(r) FROM (SELECT r = @a UNION SELECT r = @b) AS x;


Result:

0.234999999403954


Now using DECIMAL instead:

DECLARE @a DECIMAL(10,4) = 0.23, @b DECIMAL(10,4) = 0.24;
SELECT AVG(r) FROM (SELECT r = @a UNION SELECT r = @b) AS x;


Result:

0.235000


Some related reading:


http://web.archive.org/web/20130205023610/http://classicasp.aspfaq.com/general/why-does-3-2-1-5-4-7000000000000002.html
http://web.archive.org/web/20120208202619/http://databases.aspfaq.com/database/what-datatype-should-i-use-for-numeric-columns.html
https://sqlblog.org/2009/10/12/bad-habits-to-kick-choosing-the-wrong-data-type


Decimal is not perfect, either; you can lose precision if you need more decimal places than supported, for example. But for most applications this is not an issue.