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

2

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!

Serinaserine answered 18/12, 2017 at 7:56 Comment(3)
android tag is useless hereRoentgenology
@NorthernPoet It is not actually! Because Room persistent database is used in android!Serinaserine
Agreed, sorry for misunderstandingRoentgenology
S
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

Serinaserine answered 5/1, 2018 at 13:42 Comment(2)
For reference, I believe the thanks is for a comment on this Medium articleKlute
Wow, That was a spot-on! Worked like a charm.Disqualify
R
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.

Roentgenology answered 18/12, 2017 at 7:59 Comment(5)
Can u elaborate the answer please? I am using Room persistent library and it is not allowing me to write this query in my DAO class with @Query annotation!Serinaserine
@NorthernPoet hey, i tried this solution again! And it worked with some spacing efforts and correcting your query with THEN keyword! So thank you so much :)Serinaserine
Glad to know that it helps you. I made little edit to add details and correct from keyword missing for further users.Roentgenology
What if we need 2 counts if Value = 1 and if Value = 2?Headspring
What syntax is this?Notability

© 2022 - 2024 — McMap. All rights reserved.