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 trialnicolaspeterson
8,569 PointsTotally lost me in this video...
Andrew completely lost me at the HAVING part, like why we need to use it as a conditional instead of WHERE. Sounds like some kind of operation error that SQL can't handle, but I don't know..
3 Answers
Jason Larson
8,359 PointsIf you try to use a WHERE clause when using the SUM aggregate function, it throws an error because the aggregation happens in the Group By clause, and WHERE happens before the Group By. In this case, you have to use HAVING on the Group By to filter on conditions.
Ryan Hartigan
3,425 PointsWhy wouldn't aggregation still be able to happen after the result set is filtered by the WHERE clause? Jason Larson . I'm not exactly sure why it's throwing an error still, and why we need a unique keyword for it. You would think GROUP BY might still be able to run after WHERE filters the available rows, so I'm not sure why it's not able to function like this
Shawn Lindsey
20,952 PointsSo what appears to be happening here is that the WHERE condition is being processed before the GROUP BY. In other words, it's trying to group and filter in an illogical order. It wants to weed things out before they're being grouped, but that defeats the purpose. You want to have your total costs grouped by id before you start filtering out aggregated costs of 250 and less. The root of the problem here seems to be that WHERE commands must come before GROUP BY, so the solution to applying aggregates to groups is the HAVING keyword, which is allowed to come after GROUP BY keywords. HAVING is acting as WHERE, but because it can come after the GROUP BY, it resolves the logical issue and does what you intended.