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

why do we have to use Distinct keyword when the Group by can count and report the different set of data?

Teamtreehouse assessment question - 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.?

My code -

select genre, count(*) as total_genres from books Group by genre;

Error - Bummer! You're missing the DISTINCT keyword.

5 Answers

Saiteja Vemula
Saiteja Vemula
7,162 Points

COUNT(*) will gives you the count of all the rows in the table including duplicate rows.

In the question, he asked you to write a query to find all the unique genres in books table.

The query should be :

SELECT DISTINCT COUNT(genre) AS total_genres FROM books;

Thanks!!

so this is my code and it says the count is incorrect at 19

SELECT DISTINCT COUNT(genre) AS total_genres FROM books;

any thoughts?

My code below actually gives the total genres. but it says "Bummer! Your query didn't perform the correct count."

select distinct count(genre) as total_genres from books group by genre;

I get a table with total_genres as the column head, and entries of how many books are in each genre, but it's still saying I'm wrong. Maybe I'm just not understanding the question.

Imtanan Raja
Imtanan Raja
6,713 Points
SELECT COUNT(DISTINCT genre) AS "total_genres" FROM books; 

This should work, we are getting distinct genres and counting them but not from a where clause because no condition is given