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

Bruce McMinn
Bruce McMinn
10,030 Points

UNION vs UNION ALL

I get different results for patron_id 3 in this query if I use UNION (COUNT of 4) or a UNION ALL (count of 8)

SELECT patron_id, COUNT(*) FROM loans_north
WHERE returned_on IS NULL
GROUP BY patron_id
UNION--or UNION ALL
SELECT patron_id, COUNT(*) FROM loans_south
WHERE returned_on IS NULL
GROUP BY patron_id
ORDER BY patron_id;

But in this query I get basically the same count either way.

SELECT * FROM loans_south
  WHERE returned_on IS NULL
  AND patron_id = 3
UNION--or UNION ALL
SELECT * FROM loans_north
  WHERE returned_on IS NULL
  AND patron_id = 3

It's late and I'm stumped. Any clues? Greg Kaleka, you out there?

1 Answer

Steven Parker
Steven Parker
231,248 Points

By itself, UNION works like it has a built-in DISTINCT. It only returns unique rows based on the columns selected. But UNION ALL returns all rows from both queries, unique or not.

Whether these return different result sets depends on the data being selected. It's entirely possible for the row count to be different when only a few columns are displayed, but the same when all columns are displayed.