Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select more than one count in mysql

Is it possible in MySQL to do something like this:

SELECT COUNT(*) as totalcount, 
       COUNT(*) WHERE foo IS NULL as conditional_count 
  FROM baz

i.e. get two counts, one of everything, and one of things matching a WHERE clause, in a single select?

like image 946
AmbroseChapel Avatar asked May 30 '11 06:05

AmbroseChapel


People also ask

How do you get multiple counts from a single query?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table. The query to create a table is as follows.

What is select COUNT (*) as COUNT in MySQL?

The COUNT(*) function returns the number of rows in a result set returned by a SELECT statement. The COUNT(*) returns the number of rows including duplicate, non-NULL and NULL rows.

How do I COUNT two items in SQL?

count(*) counts all rows in table to give total count. count(if(product='A',1,null)) as A_count – when we use an IF condition inside count function, it will only count rows where condition is true. Our condition is to match rows where product = A. So MySQL, counts only those rows where product is A.


1 Answers

This would work if your database supports the CASE WHEN statement, otherwise you'll still get the basic idea.

SELECT COUNT(*), 
       SUM(CASE WHEN FOO IS NULL THEN 1 ELSE 0 END) AS COUNT_CONDITIONAL
  FROM baz
like image 194
Johann Blais Avatar answered Nov 05 '22 11:11

Johann Blais