What I\'am doing :
create table sample (id INT(10) PRIMARY KEY AUTO_INCREMENT,name varchar(255),marks INT(10));
insert into sample (name,marks) VALUES(\'sam
This is the correct behavior, because NULL is not the same as the number 0.
Conceptually, NULL refers to an “unknown value” and as such it is treated differently from other values. That is why aggregate functions like AVG() ignore NULLs.
AVG() calculates the average over all "known" values only. (= that are not NULL)
From the MySQL docs:
Unless otherwise stated, group functions ignore NULL values.
Also, read about the concept of NULLs in Section "3.3.4.6 Working with NULL Values" of the MySQL manual.
To get what you want, you might do
SELECT AVG(IFNULL(marks, 0))
FROM sample
GROUP BY name;
IFNULL() returns the second argument for calculations if the value is NULL or passes through the value otherwise.
There are more common misunderstandings regarding the concept of NULL. These are also explained in Section "5.5.3 Problems with NULL" of the manual:
- In SQL, the
NULLvalue is never true in comparison to any other value, evenNULL. An expression that containsNULLalways produces aNULLvalue unless otherwise indicated in the documentation for the operators and functions involved in the expression.
i.e.:NULL == 0results in NULL instead oftrue. AlsoNULL == NULLresults in NULL, instead of true.- To search for column values that are
NULL, you cannot use anexpr = NULLtest. To look forNULLvalues, you must use theIS NULLtest.- When using
DISTINCT,GROUP BY, orORDER BY, allNULLvalues are regarded as equal.- When using
ORDER BY,NULLvalues are presented first, or last if you specifyDESCto sort in descending order.- For some data types, MySQL handles NULL values specially. If you insert
NULLinto aTIMESTAMPcolumn, the current date and time is inserted.- If you insert
NULLinto an integer or floating-point column that has theAUTO_INCREMENTattribute, the next number in the sequence is inserted.- A column that has a
UNIQUEkey defined can still contain multipleNULLvalues.