Android Academy · Lesson

Queries and Relationships

Query data and relate entities.

Lesson 3 of 413 steps

Queries and Relationships is a free Android Academy lesson on CoddyKit. This is lesson 3 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Android Academy learning path, and your progress syncs across the web and the CoddyKit app. The Android Academy course includes 4 lessons in total.

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(): Int

Defining 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

  • @ForeignKey enforces integrity and cascade rules.
  • @Relation + @Embedded assemble related objects.
  • @Transaction keeps multi-query reads consistent.

Quick Check

Test your understanding of relationships.

Recap

You learned:

  • Parameterize queries with :name and return aggregates.
  • @ForeignKey enforces integrity with onDelete rules.
  • @Relation + @Embedded build related objects; wrap reads in @Transaction.
Free to start

Learn Kotlin with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
36
Lessons
152

Frequently Asked Questions

Is the “Queries and Relationships” lesson free?

Yes — any 3 lessons of the Android Academy learning path, including “Queries and Relationships”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Android Academy course includes 4 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 4.

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

  1. Entities and DAOs
  2. The Room Database Class
  3. Queries and Relationships
  4. Observing Data with Flow
← Back to Android Academy