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

This was last published in November 2002

Dig Deeper on Oracle and SQL

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.