Queries and Relationships
Query data and relate entities.
Queries and Relationships is a free Android Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Beyond a Single Table
Real apps have related data: a user has many posts, an order has many items. Room models these with foreign keys and the @Relation annotation.
Parameterized Queries
Pass arguments into a @Query with a colon prefix.
@Query("SELECT * FROM users WHERE name LIKE :search")
suspend fun search(search: String): List<User>Returning Aggregates
Queries can return scalar values like counts.
@Query("SELECT COUNT(*) FROM users")
suspend fun count(): IntDefining a Foreign Key
A child entity references its parent with @ForeignKey. This enforces referential integrity at the database level.
@Entity(
foreignKeys = [ForeignKey(
entity = User::class,
parentColumns = ["id"],
childColumns = ["userId"]
)]
)
data class Post(
@PrimaryKey val id: Int,
val userId: Int,
val title: String
)Indexing Foreign Keys
Room recommends indexing foreign key columns for query performance. Add an @Index.
@Entity(
indices = [Index("userId")]
)
data class Post(/* ... */ val userId: Int)onDelete Behavior
Decide what happens to children when a parent is deleted, e.g. CASCADE to delete them too.
ForeignKey(
entity = User::class,
parentColumns = ["id"],
childColumns = ["userId"],
onDelete = ForeignKey.CASCADE
)Modeling a One-to-Many Relation
Create a class that combines a parent with its children using @Embedded and @Relation.
data class UserWithPosts(
@Embedded val user: User,
@Relation(
parentColumn = "id",
entityColumn = "userId"
)
val posts: List<Post>
)Querying the Relation
Return the combined class from a DAO. Room runs the extra query and stitches the objects together.
@Transaction
@Query("SELECT * FROM users")
suspend fun getUsersWithPosts(): List<UserWithPosts>Why @Transaction Here
Because Room executes two queries (parents, then children), wrapping the method in @Transaction ensures a consistent snapshot with no interleaved writes.
Many-to-Many with a Junction
For many-to-many (students and courses), use a junction table and the associateBy parameter of @Relation.
@Relation(
parentColumn = "studentId",
entityColumn = "courseId",
associateBy = Junction(Enrollment::class)
)
val courses: List<Course>Relations Summary
@ForeignKeyenforces integrity and cascade rules.@Relation+@Embeddedassemble related objects.@Transactionkeeps multi-query reads consistent.
Quick Check
Test your understanding of relationships.
Recap
You learned:
- Parameterize queries with
:nameand return aggregates. @ForeignKeyenforces integrity withonDeleterules.@Relation+@Embeddedbuild related objects; wrap reads in@Transaction.
Frequently asked questions
Is the “Queries and Relationships” lesson free?
Yes — the full text of “Queries and Relationships” is free to read here on the web, and the Android Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Android Academy course, upgrade to CoddyKit PRO.
What will I learn in “Queries and Relationships”?
Query data and relate entities. You practise Android Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Android Academy?
No prior experience is required. Android Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Queries and Relationships” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Android Academy lesson?
Yes. Every Android Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Entities and DAOs
- The Room Database Class
- Queries and Relationships
- Observing Data with Flow