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

Common Table Expression Question about the diff btween: GROUP BY CategoryName ORDER BY unique_product_count

WITH product_details AS( SELECT ProductName, CategoryName, UnitPrice, UnitsInStock FROM Products JOIN Categories ON Products.CategoryID = Categories.Id WHERE Products.Discontinued=0 ) SELECT CategoryName, COUNT(*) AS unique_product_count, SUM(UnitsInStock) AS stock_count FROM product_details GROUP BY CategoryName ORDER BY unique_product_count

I have this code here that shows me unique_product_count filtered in ASCENDING order..

I read that we can only use GROUP BY with aggregate functions… Can someone explain to me why we are grouping by CategoryName here?

I notice that it is not grouping CategoryName alphabetically.. so can someone tell me what is the purpose of GROUP BY in this example?

1 Answer

Gabriel Plackey
Gabriel Plackey
11,064 Points

It's grouping all the same CategoryName's together. Versus Order by orders the table by whatever, in this case unnique_product_count. I don't know why you're grouping it by CategoryName here, I am not familiar with where this code is coming from, but I imagine it's to keep all the same Category's together to easily find or for increased readability or view-ability.