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 Reporting with SQL Aggregate and Numeric Functions Counting Groups

Why is the a NULL genre value complicating this challenge and howto solve it elegantly?

So this was my query to find the count of all unique genres in books:

SELECT COUNT(*) AS 'total_genres' FROM (SELECT DISTINCT genre FROM books) G;

Now this returned 7 which i figured eventually was one more than the actual number because of NULL values in some rows for genre... So this worked:

SELECT COUNT(*)-1 AS 'total_genres' FROM (SELECT DISTINCT genre FROM books) G;

But this seems like a recreational solution... Is there a nicer more robust way to solve this?

I am not sure about this one, but have you already tried SELECT COUNT(*) AS 'total_genres' FROM (SELECT DISTINCT genre FROM books WHERE genre IS NOT NULL)?

Thanks Egarat! This seems to be one better way to solve this! I am not sure how I can comment under your answer or mark it as best answer but maybe theydo not have this option anymore...

1 Answer

Hey Gleb,

I was too lazy to scroll down and put the answer in the corresponding field and just used the comment field instead (that's why you could not mark it as the correct solution)... :-) I am glad to be of help, if you don't know the reason why this works - just let me know.

But here is the solution again:

SELECT COUNT(*) AS 'total_genres' FROM (SELECT DISTINCT genre FROM books WHERE genre IS NOT NULL)

Happy coding!