How can i get count of number of rows that have boolean value true(or 1) in Room persistent database without using SELECT query?

Priyanka Alachiya picture Priyanka Alachiya · Dec 18, 2017 · Viewed 13.8k times · Source

I am working with Room persistent database in my project. I have a table in which there is a column for Boolean values as in 0 or 1, now i want the count of all Boolean values whose value is true (or 1).

I know that i can achieve this using select query by getting the count of all selected rows using where clause!

But i don't want to use Select query with where clause for this because it will load all the rows and then i will get the count, but i want the count without loading any rows! Suggest other simple solutions please! Thank you!

Answer

Priyanka Alachiya picture Priyanka Alachiya · Jan 5, 2018

Finally I got the perfect solution! Just add this method in the DAO class as follows:

@Query("SELECT COUNT(is_checked) FROM table WHERE is_checked = 1")
int getNumberOfRows();

All thanks to Florina Muntenescu at https://medium.com/@florina.muntenescu