COUNT
The COUNT function counts only non-null values. Therefore, the data type of the result of the COUNT function always has the NOT NULL attribute.
There are two uses of COUNT:
- COUNT with the DISTINCT keyword, which has two forms:
- COUNT(DISTINCT colname)
Counts rows returned in which there is a non-null value in a named column. It eliminates duplicates from the count.
This format must be used with a column name; it cannot be used with an expression. An example of this form of the COUNT function is shown below:SELECT COUNT(DISTINCT DIVISION) FROM Q.ORG
The result is 4.
- COUNT(DISTINCT expression)
Returns distinct values for columns within a group. For example, the following query returns the number of distinct education levels of the job applicants in the Q.APPLICANT table as well as the average number of years of education the applicants have.
SELECT COUNT(DISTINCT EDLEVEL), AVG(EDLEVEL) FROM Q.APPLICANT
- COUNT(DISTINCT colname)
- COUNT(*)
Counts rows returned regardless of the value of any column. This format is not used with a column name. For example:
SELECT SUM(SALARY), MIN(SALARY), AVG(SALARY), MAX(SALARY), COUNT(*) FROM Q.STAFF WHERE DEPT = 10
This example includes more than one column function in the SELECT statement. It calculates and displays, for Department 10, the sum of employee salaries; the minimum, average, and maximum salary; and the number of employees (COUNT) in the department. It produces the following report:COL1 COL2 COL3 COL4 COL5 ------------------ ---------- ------------------ ---------- ----------- 83463.45 19260.25 20865.8625000000 22959.20 4