17

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!

Priyanka Alachiya
  • 1,707
  • 2
  • 20
  • 31

2 Answers2

44

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

Priyanka Alachiya
  • 1,707
  • 2
  • 20
  • 31
  • 2
    For reference, I believe the thanks is for [a comment](https://medium.com/@alachiyapriyanka/hi-maam-do-you-know-how-can-i-get-total-number-of-rows-in-a-table-using-room-database-without-643dbdb63998) on [this Medium article](https://medium.com/google-developers/7-steps-to-room-27a5fe5f99b2) – methodsignature Jan 09 '18 at 13:13
  • 1
    Wow, That was a spot-on! Worked like a charm. – sud007 Feb 26 '19 at 18:32
0

Using aggregate function sum may help you:

select
    sum(
        case
            when t.VALUE = 1 then
                1
            else
                0
        end
    )
from
    table t

Please note, SQLite engine will read entire table, if no indexed by aggregating field. It's no problem if there only few records in the table, otherwise it's better to consider using from keyword of indexed fields.

Northern Poet
  • 1,955
  • 1
  • 12
  • 17