Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Databases

Your Query Didn't Perform The Correct Count

"In the library database there's a books table. There are id, title, author, genre and first_published columns. Count all the books in each genre. Include the genre column first and the genre_count as the second column of information."

This is what I entered and I do not understand what is wrong.

SELECT genre, COUNT(genre) AS genre_count FROM books GROUP BY genre;

3 Answers

Steven Parker
Steven Parker
216,057 Points

Don't restrict your count.

You're already grouping by genre, so just count the rows ("COUNT(*)" or "COUNT(1)").

Dustin Beaulieu
Dustin Beaulieu
1,278 Points

This worked but I do not understand why the result is different. Can you elaborate on this?

Steven Parker
Steven Parker
216,057 Points

The COUNT function only counts rows that have a NOT NULL value in the field(s) you specify as an argument, so the original query didn't return the right count for the null genre.

Dustin Beaulieu
Dustin Beaulieu
1,278 Points

I am running into the same issue as above, and my code is identical. I believe the issue is that there is a genre that is null, with a count of 0. I then tried the statement below:

SELECT genre, COUNT(genre) AS "genre_count" FROM books WHERE genre IS NOT NULL GROUP BY genre;

This provided the results I wanted!!! .......but it still says it is not correct. UGH!

Steven Parker
Steven Parker
216,057 Points

I believe the challenge wants to see the null genre included, so you need an unrestricted count and no filter ("WHERE" clause).

Dustin Beaulieu
Dustin Beaulieu
1,278 Points

Thank you for the follow up Steven!