Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases SQL Reporting by Example Day 3: Getting Good at Grouping Busiest Teachers

Question on the GROUP BY keyword

HERE IS THE CHALLENGE: Which teachers teach a class during all 7 periods?

SELECT * FROM TEACHERS INNER JOIN CLASSES ON CLASSES.TEACHER_ID = TEACHERS.ID GROUP BY TEACHERS.ID;

CONFUSION:

I dont understand how the keyword GROUP BY TEACHERS.ID shows all the teachers teaching 7 periods. When you run the query, the PERIOD_ID COLUMN shows a 7. What does this 7 mean?

1 Answer

Steven Parker
Steven Parker
231,184 Points

It doesn't really mean anything in this query. Since the GROUP BY guarantees only one line per teacher, the value shown in that column is just the period number of the last entry for that teacher in the CLASSES table.

If you watch the entire lesson to the end, you'll see that an aggregate function is added to count up the classes taught by each teacher and then test that with a HAVING filter to be sure each teacher shown has all 7.