Pick the fix
SELECT * FROM messages WHERE chatId = ? ORDER BY sentAt DESC LIMIT 50 takes 300 ms with 500,000 rows. Best first fix?
Hint 1 of 1
What does the WHERE and ORDER BY need?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Add a composite index on (chatId, sentAt)
Correct. SQLite can find the chat's rows and read them already sorted.
Why not the others?
- B Add separate indexes on chatId and sentAt. SQLite usually uses one index per table here; the composite fits the query.
- C Move the query to Dispatchers.IO. It's already off main if it's a suspend DAO call; it's still slow.
- D Cache all messages in memory. Uses lots of memory and still slow to build.