Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Combine Select count(*) from multiple tables

How do you combine multiple select count(*) from different table into one return?

I have a similar sitiuation as this post

but I want one return.

I tried Union all but it spit back 3 separate rows of count. How do you combine them into one?

select count(*) from foo1 where ID = '00123244552000258' union all  select count(*) from foo2 where ID = '00123244552000258' union all select count(*) from foo3 where ID = '00123244552000258' 

edit: I'm on MS SQL 2005

like image 615
Jack Avatar asked Aug 14 '09 18:08

Jack


People also ask

How do I combine counts in SQL?

SQL SUM() and COUNT() with inner join The data from a subquery can be stored in a temporary table or alias. The data of these temporary tables can be used to manipulate data of another table. These two tables can be joined by themselves and to return a result.

Can we use count in joins in SQL?

Conclusion. In this short tutorial, you have seen how the COUNT/GROUP BY/JOIN combination can be used in SQL to aggregate entries across multiple tables. While a GROUP BY query can accomplish this simply enough when working with just one table, the situation can become more complex when working across multiple tables.

Are count (*) and count () the same function?

Since it doesn't matter which value you put in the parentheses, it follows that COUNT(*) and COUNT(1) are precisely the same. They are precisely the same because the value in the COUNT() parentheses serves only to tell the query what it will count.

How get count from multiple tables in SQL?

To achieve this for multiple tables, use the UNION ALL. select sum(variableName. aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName; Let us implement the above syntax.


2 Answers

SELECT  (select count(*) from foo1 where ID = '00123244552000258') + (select count(*) from foo2 where ID = '00123244552000258') + (select count(*) from foo3 where ID = '00123244552000258') 

This is an easy way.

like image 52
Chris J Avatar answered Sep 22 '22 00:09

Chris J


I'm surprised no one has suggested this variation:

SELECT SUM(c) FROM (   SELECT COUNT(*) AS c FROM foo1 WHERE ID = '00123244552000258'   UNION ALL   SELECT COUNT(*) FROM foo2 WHERE ID = '00123244552000258'   UNION ALL   SELECT COUNT(*) FROM foo3 WHERE ID = '00123244552000258' ); 
like image 36
Bill Karwin Avatar answered Sep 22 '22 00:09

Bill Karwin