TSO-ISPF JCL COBOL VSAM DB2 CICS Tools Articles Job Portal Forum Quiz Interview Q&A

DB2 - SQL COUNT(), AVG() and SUM() Functions


SQL COUNT(), AVG() and SUM() Functions

The COUNT() function returns the number of rows that matches a specified criterion.

The AVG() function returns the average value of a numeric column.

The SUM() function returns the total sum of a numeric column.

Let us see the syntax for each function below.

Syntax: COUNT()

SELECT COUNT(column_name)
  FROM table_name
  WHERE condition;

Syntax: AVG()

SELECT AVG(column_name)
  FROM table_name
  WHERE condition;

Syntax: SUM()

SELECT SUM(column_name)
  FROM table_name
  WHERE condition;

DB2 Database:

Below is a selection from the "Product" table in the DB2 database.

ProductIDProductNameCategoryPriceQtyOnHandTotalValue
7001MouseAccessories75.00
7002Harddrive65.00201,300
7003KeyboardAccessories36.00331,118.00
7004RAMComponents23.5016376.00
7005HondaBikes1,200
7006PEN7.451074.50
7007CddriveAccessories75.00
7008SpeakerAccessories75.00

Example 1: Count Function

The following SQL statement finds the number of products in the "Product" table. NULL values are not counted.

SELECT COUNT(ProductID)
  FROM Products;
Result:
COUNT(ProductID)
8

Example 2: Avg Function

The following SQL statement finds the average price of all products in the "Product" table. NULL values are ignored.

SELECT AVG(Price)
  FROM Products;
Result:
AVG(Price)
194.61875

Example 3: Sum Function

The following SQL statement finds the sum of the "QtyOnHand" fields in the "Product" table. NULL values are ignored.

SELECT SUM(QtyOnHand)
  FROM Products;
Result:
SUM(QtyOnHand)
79


If you have any doubts or queries related to this chapter, get them clarified from our Mainframe experts on ibmmainframer Community!

Are you looking for Job Change? Job Portal