Search code examples
android-roomsql-delete

android Room, how to delete multiple rows in the table by id list


Having a Android Room with three tables timestamp, index, details, and all three have

@PrimaryKey @ColumnInfo(name = "id") var id: Int = 0

having fun clearDataByID(idList: List<Int>) to clear data from all three tables by the id in the idList

Dao as:

@Dao
interface DataDAO {


@Transaction
fun clearDataByID(idList: List<Int>) {
    deleteDataInTimestamp(idList)
    deleteDataIndex(idList)
    deleteDataDetails(idList)
}

@Query("delete from timestamp where id in :idList")
fun deleteDataInTimestamp(idList: List<Int>)

@Query("delete from index where id in :idList")
fun deleteDataIndex(idList: List<Int>)

@Query("delete from details where id in :idList")
fun deleteDataDetails(idList: List<Int>)
}

but it gets compiler error (similar for all three)

error: no viable alternative at input 'delete from timestamp where id in :idList'
public abstract void deleteDataInTimestamp(@org.jetbrains.annotations.NotNull()

if delete by single id it worked.

How to delete by a list of ids?

@Query("delete from timestamp where id = :id")
fun deleteSingleTimestamp(id: Int)

Solution

  • just extending the answer given by @lannyf

    @Query("delete from timestamp where id in (:idList)")
    fun deleteDataInTimestamp(idList: List<Int>) 
    

    this could be written in this way also

    @Query("delete from timestamp where id = :idList")
    fun deleteDataInTimestamp(idList: List<Int>) 
    

    PS: edit queue was full