tags:

views:

210

answers:

4

I have a "boolean" column in one of my tables (value is either 0 or 1).

I need to get two counts: The number of rows that have the boolean set to 0 and the number of rows that have it set to 1. Currently I have two queries: One to count the 1's and the other to count the 0's.

Is MySQL traversing the entire table when counting rows with a WHERE condition? I'm wondering if there's a single query that would allow two counters based on different conditions?

Or is there a way to get the total count along side the WHERE conditioned count? This would be enough as I'd only have to subtract one count from the other (due to the boolean nature of the column). There are no NULL values.

Thanks.

+5  A: 

You could group your records by your boolean column and get count for each group.

 SELECT bool_column, COUNT(bool_column) FROM your_table
 WHERE your_conditions
 GROUP BY bool_column

This will obviously work not only for bool columns but also with other data types if you need that.

RaYell
Awesome, thanks! I'm still new to MySQL so I wasn't too familiar with GROUP BY.
Nebs
A: 

If they are all either 0 or 1 and you dont mind 2 rows as result you can group by that field and do a count like so:

select field, count(field)
from table
group by field
Fabian
A: 

A simple group clause should do the trick :

SELECT boolField, COUNT(boolField)
FROM myTable
GROUP BY boolField
Thibault Falise
A: 

Try this one:

SELECT
    SUM(your_field) as positive_count,
    SUM(IF(your_field, 0, 1)) as negative_count
FROM thetable
newtover
Interesting approach. How does the performance of SUM rate against COUNT?
Nebs
@Nebs: SUMming will definitely work faster when the field is not indexed, since GROUP BY implicitly requires sorting by the field. When the column is indexed, I think, the performance will be similar, though one need to check in particular case.
newtover