Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting Sum of the Count From Tables in a DB

Tags:

sql

count

union

I have the following query:

SELECT SUM(count) 
  FROM (SELECT 'artist' AS table_name, COUNT(*) as count FROM artist
        UNION
        SELECT 'persons' AS table_name, COUNT(*) as count FROM persons
        UNION
        SELECT 'track' AS table_name, COUNT(*) as count FROM track)

It works as expected and returns the proper count. But now when I do the following query I get the incorrect count:

SELECT SUM(count) 
  FROM (SELECT COUNT(*) as count FROM artist
        UNION
        SELECT COUNT(*) as count FROM persons
        UNION
        SELECT COUNT(*) as count FROM track)

Why is it the first query gets the proper count and the second one does not?

like image 472
Ian Dallas Avatar asked Jan 30 '26 04:01

Ian Dallas


1 Answers

The UNION eliminates duplicate values, so if two counts happen to be the same, one is eliminated and only one is summed. Try using UNION ALL instead.

SELECT sum(count) FROM
(SELECT COUNT(*) as count FROM artist
UNION ALL
SELECT COUNT(*) as count FROM persons
UNION ALL
SELECT COUNT(*) as count FROM track)
like image 58
Joe Stefanelli Avatar answered Jan 31 '26 20:01

Joe Stefanelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!