select stno from grades where cno = ’cs110’
and grade > all(select avg(grade) from grades
where cno=’cs110’);
111
This returns the table:
STNO
----
2661
3566
5544
The count function can be used in several ways:
• count(A) can be used to determine the number of non-null entries under
the attribute A;
• count(distinct A) computes the number of distinct non-null values that
occur under A;
• count(*) determines how many rows exist in a table.
Note that count(distinct *) cannot be used in SQL.
Example 5.15.4 Here are several examples of the use of the count function.
To find how many students took cs110 in the fall semester of 2002, we write:
select count(cno) from GRADES
where cno = ’cs110’ and
sem = ’Fall’ and
year = 2003;
Since no records exist for any grades given during that semester in cs110, we
obtain the answer:
COUNT(CNO)
----------
0
Observe that this table has a system-supplied column name COUNT(cno). This
happens because we did not provide a name using as.
Let us determine how many students have ever registered for any course. We
have to retrieve this result from GRADES, and we must use distinct to avoid
counting the same student several times (if the student took several courses):
select count(distinct stno) as nost
from GRADES;
This query returns the one-entry table:
NOST
----
8