Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a count on a union query

I have the following query:

select distinct profile_id from userprofile_...  union  select distinct profile_id from productions_... 

How would I get the count of the total number of results?

like image 499
David542 Avatar asked Jul 31 '12 00:07

David542


People also ask

How do you write a count in SELECT query?

SELECT COUNT(*) FROM table_name; The COUNT(*) function will return the total number of items in that group including NULL values. The FROM clause in SQL specifies which table we want to list. You can also use the ALL keyword in the COUNT function.

How do I do a count in SQL?

COUNT(ALL expression) evaluates expression for each row in a group, and returns the number of nonnull values. COUNT(DISTINCT expression) evaluates expression for each row in a group, and returns the number of unique, nonnull values. For return values exceeding 2^31-1, COUNT returns an error.

How does count (*) work in SQL?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.


2 Answers

If you want a total count for all records, then you would do this:

SELECT COUNT(*) FROM (     select distinct profile_id      from userprofile_...      union all      select distinct profile_id      from productions_... ) x 
like image 103
Taryn Avatar answered Sep 28 '22 05:09

Taryn


you should use Union All if there are equals rows in both tables, because Union makes a distinct

select count(*) from  (select distinct profile_id from userprofile_...  union ALL  select distinct profile_id from productions_...) x 

In this case, if you got a same Profile_Id in both tables (id is probably a number, so it's possible), then if you use Union, if you got Id = 1 in both tables, you will lost one row (it will appear one time instead of two)

like image 38
Gonzalo.- Avatar answered Sep 28 '22 06:09

Gonzalo.-