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

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,737 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!