Monday, November 14, 2016

DB2 Aggregate function behavior with Null Values in Table

Aggregate functions are very useful in getting meaningful information from a group. 
Here we are looking at what will happen if the table has NULL values. Aggregate functions will ignore the Null values in the column. 

Consider a Table TEMP1 with two columns
C1 - CHAR(1)
C2 - Integer

The Values in the table are 

C1 C2
A 100
B NULL
A 200
B 100
B 400
C NULL
C NULL

SELECT C1, SUM(C2) SUM_C2,     
           MIN(C2) MIN_C2,     
           MAX(C2) MAX_C2,     
           AVG(C2) AVG_C2,     
           COUNT(*) COUNT_STAR,
           COUNT(C2) COUNT_C2  
  FROM SESSION.TEMP1           
  GROUP BY C1;   

Result will be 

C1       SUM_C2       MIN_C2       MAX_C2       AVG_C2   COUNT_STAR     COUNT_C2
---------+---------+---------+---------+---------+---------+---------+---------+
A           300          100          200          150            2            2
B           500          100          400          250            3            2
C   -----------  -----------  -----------  -----------            2            0


As you can see only Count(*) considers the rows with the Null values. Rest all functions ignore the Null Values.
Hope this helps you guys out there.