Ask the Expert

Why WHERE cannot be used after GROUP BY

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

    Requires Free Membership to View

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 first published in November 2002

There are Comments. Add yours.

TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
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
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: