Room: how to check whether row exists
You can use EXISTS
operator and return just Boolean
:
@Query("SELECT EXISTS(SELECT * FROM table)")
fun hasItem(): Boolean
Use EXISTS
operator, and return 1 means true
and 0 means false
.
If you want to check some specific row and some condition, do this trick:
@Query("SELECT EXISTS(SELECT * FROM tableName WHERE id = :id)")
fun isRowIsExist(id : Int) : Boolean
Or simple use this:
@Query("SELECT EXISTS(SELECT * FROM tableName)")
fun isExists(): Boolean
As ADM suggested, you might get lucky using COUNT()
to count the actual rows in a table.
However, I would recommend just fetching the data anyway - if none exists Room will simply return an empty list, and this should not be less efficient than asking for the row count (if it's 0
anyway).
As a plus you will have less code to write to get the functionality you want! :-)