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

Cristian Luca
Cristian Luca
3,798 Points

What's wrong with my code? Thanks a lot!

Challenge Task 2 of 2 In the library database there's a books table. There are id, title, author, genre and first_published columns.

Write a query to count all the unique genres in the books table. Alias it as total_genres.

Steven Parker
Steven Parker
218,692 Points

You repeated the challenge, but forgot to show your code. Add it so we can give you an answer.

Cristian Luca
Cristian Luca
3,798 Points

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

What's wrong with my code? Thanks a lot!

3 Answers

Steven Parker
Steven Parker
218,692 Points

The instructions ask you to "count all the unique genres in the books table". So you only need one column in your result for the count (you won't need the genre). But you were on the right track about using "DISTINCT genre", it just needs to be what you're counting:

SELECT COUNT(DISTINCT genre) AS total_genres FROM books;
Guillermo Gallo
seal-mask
.a{fill-rule:evenodd;}techdegree
Guillermo Gallo
Full Stack JavaScript Techdegree Student 8,490 Points

Hi Cristian Luca

Your code looks good so far, but I think instead of DISTINCT, you should try using a GROUP BY clause in your query. Keep in mind that the GROUP BY clause will go at the end of the query. So try something like this:

SELECT COUNT(*) AS total_genres FROM books GROUP BY genre;

Let me know if that works.