Problem solve Get help with specific problems with your technologies, process and projects.

Why WHERE cannot be used after GROUP BY

Please tell me why "where" can't be used after "group by".

WHERE operates on individual rows, and is used to select which rows will participate in grouping. HAVING operates on groups, and is used to select which groups will be returned. Here's an example:

student	subject	grade
 Bill   English   A
 Bill   French    B
 Bill   History   C
 Bill   Math      D
 Bill   Science   A
 Bill   Spelling  C
 Bob    English   A
 Bob    French    B
 Bob    History   D
 Bob    Math      C
 Bob    Science   C
 Bob    Spelling  F
 Fred   English   A
 Fred   French    A
 Fred   History   C
 Fred   Math      C
 Fred   Science   A
 Fred   Spelling  C
 John   English   C
 John   French    D
 John   History   B
 John   Math      F
 John   Science   A
 John   Spelling  C
 Mary   English   C
 Mary   French    C
 Mary   History   F
 Mary   Math      C
 Mary   Science   C
 Mary   Spelling  C
 Tom    English   D
 Tom    French    A
 Tom    History   B
 Tom    Math      C
 Tom    Science   A
 Tom    Spelling  F

In which subjects did at least three students earn an A?

To find the answer, you have to count the number of students who got an A in each subject. In other words, you need to filter on the grade, selecting only those student subjects where the grade was A. Then you have to look at the count for each subject, and return only those subjects which have at least three selected students in them.

select subject, count(*)
  from studentgrades
 where grade = 'A'
    by subject
having count(*) > 2

The answer:

English  3
Science  4

For More Information

Dig Deeper on Oracle and SQL