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!

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


Is there a less repetitive, more elegant way to write this SQL query?

I'm working on the Querying Relational Databases Course, and I'm on the exercise that reads:

-- Generate a report that lists the book titles from both [library] locations and count the total number of books with the same title.

My answer was:

SELECT title, COUNT(title) FROM ( SELECT title, COUNT(title) FROM books_north GROUP BY title UNION ALL SELECT title, COUNT(title) FROM books_south GROUP BY title ) GROUP BY title;

It seems to work (hurrah), but I feel like I'm missing some better, more efficient way to accomplish this task. Any suggestions? Or am I just being too picky?

Thanks for any suggestions you can provide.

1 Answer

Andrew Winkler
Andrew Winkler
37,739 Points

It looks like you're duplicating the GROUP BY and COUNT() fuctions superfluously. Additionally I like to separate things out by putting subqueries on new lines. It works the same.

SELECT title, COUNT(*) AS num FROM (
SELECT title FROM books_north 
UNION ALL SELECT title FROM books_south) 
GROUP BY title;

That makes a lot more sense. Thanks!