Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate Sum of Count(*) in Mysql

Tags:

sql

mysql

I have two tables that I count rows of them. For example;

Select count(*) FROM tbl_Events

Select count(*) FROM tbl_Events2

I need total count. How can I sum the result with a single statement?

like image 840
Barış Velioğlu Avatar asked Jul 22 '11 15:07

Barış Velioğlu


People also ask

What is COUNT (*) in MySQL?

MySQL COUNT() Function The COUNT() function returns the number of records returned by a select query.

How do I get the sum and COUNT in SQL query?

SQL SUM() and COUNT() using variable SUM of values of a field or column of a SQL table, generated using SQL SUM() function can be stored in a variable or temporary column referred as alias. The same approach can be used with SQL COUNT() function too.

How do I COUNT the sum of a column in SQL?

In the Microsoft SQL server, the DESC command is not an SQL command, it is used in Oracle. SELECT count(*) as No_of_Column FROM information_schema. columns WHERE table_name ='geeksforgeeks'; Here, COUNT(*) counts the number of columns returned by the INFORMATION_SCHEMA .


2 Answers

select sum(cnt) from (
    select count(*) as cnt from tbl_events
    union all
    select count(*) as cnt from tbl_events2
) as x
like image 198
Marc B Avatar answered Sep 28 '22 22:09

Marc B


Try this:

SELECT (Select count(*) FROM tbl_Events) + (Select count(*) FROM tbl_Events2)

Or (tested in MSSQL), this:

SELECT COUNT(*) 
FROM (SELECT * FROM tbl_Events 
      UNION ALL 
      SELECT * FROM tbl_Events2) AS AllEvents

I'd guess the first will lead to better performance because it has more obvious index options. Test to be sure, though.

like image 24
Michael Haren Avatar answered Sep 28 '22 22:09

Michael Haren