Room Database Interview Questions

DATA › Storage

What is Room, and what are its main components?

What a strong answer covers: Room is Jetpack's SQLite abstraction. @Entity classes define tables, @Dao interfaces define queries with @Query, @Insert, @Update, @Delete and @Upsert, and a @Database abstract class ties them together. SQL queries are checked at compile time, results map to Kotlin objects, and DAOs support suspend functions and Flow.

Why does Room not allow database access on the main thread, and how do suspend and Flow in DAOs help?

What a strong answer covers: Database work is disk I/O and can block the main thread, causing jank or ANRs, so Room throws unless you allow it. suspend DAO functions run on Room's background executor, and Flow-returning queries run off the main thread and re-emit whenever the queried tables change, so the UI stays up to date automatically.

How do you model relationships in Room, like one-to-many?

What a strong answer covers: Room doesn't support object references between entities. Use a foreign key column in the child entity, and a data class with @Embedded parent and @Relation(parentColumn, entityColumn) children, returned from a @Transaction query. For many-to-many, use a cross-reference entity with @Junction. Add indexes on foreign key columns.

How do Room migrations work, and how do you test them?

What a strong answer covers: When the schema changes, increase the version and provide a Migration(from, to) with SQL like ALTER TABLE, or use auto-migrations with @AutoMigration and specs for renames and deletions. exportSchema saves schema JSON files to version control. MigrationTestHelper creates the old version, runs the migration, and validates the result. fallbackToDestructiveMigration wipes data, so only use it for caches.

What are the performance pitfalls with Room, and how do you write a large batch of rows efficiently?

What a strong answer covers: Pitfalls: missing indexes on columns used in WHERE or JOIN, SELECT * on wide tables, N+1 queries from relations, observing huge result sets with Flow (re-queried on every table change), and many separate inserts. For a batch, insert a list in one @Transaction, which avoids a disk sync per row; chunk very large imports; use WAL mode (default); and consider Paging for large reads. Profile with Database Inspector and EXPLAIN QUERY PLAN.

Back to Room Database