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

Cristian Luca
Cristian Luca
4,102 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
231,248 Points

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

Cristian Luca
Cristian Luca
4,102 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
231,248 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,518 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.