How Two Tables Are Connected in an Android Room App
When we build a Room database, we are basically creating a tiny version of a real SQL database inside our app.
In Lab 2, we use two tables:
A student belongs to a course.
A course can have many students.
This is called a relationship.
⭐ 1. What does it mean when two tables are “connected”?
It does not mean the tables physically store each other.
Instead:
The Student table stores the ID of the course the student belongs to. Example:
The Course table contains:
So:
Alice → courseId = 1 → Computer Science Maria → courseId = 2 → Mathematics This is called a foreign key relationship.
2. How Room “connects” the tables
Room does not magically “merge” the tables.
Instead, you connect them by including the foreign key in the entity.
In our app, the connection is made by including:
inside the Student entity.
This tiny field is the entire relationship.
3. Why this works
When you later want to find:
“All students in Course #1” “What course does Bob belong to?” Room can answer those questions because:
The Student row carries the courseId The Course table has that courseId as a primary key It’s like a matching tag or label that exists in both tables.
4. What the app actually does with these IDs
In our Lab 2 app:
When you add a student, we hard-code courseId = 1 That means every new student belongs to Course #1 This keeps things simple for your first multi-table app.
Later in the course, you could:
Let the user choose the course with a spinner Filter students by course Build a Course List screen Build a “Students in this Course” screen But the connection always comes back to the same thing:
👉 A student carries the courseId field
👉 That value tells Room which course this student belongs to
5. What students should understand at this level
By the end of this lab, students should know:
✔ A database can have more than one table
✔ Tables are connected by matching IDs (foreign keys)
✔ We connect tables in Room simply by adding a field in an Entity
✔ When we save a student, we also save a courseId
✔ This lets us query the database in more interesting ways later
Nothing more complicated than this is needed at this stage.
6. The “real world” analogy
Think of:
courseId = department number Every employee record stores:
The department table says:
That’s the entire relationship.
Room works exactly the same way.
⭐ Final Summary
Two tables in Room are connected simply because one table stores the primary key of the other table.
Room doesn't need anything fancy.
It just needs those matching numbers to relate records across tables.
This is the foundation of all relational databases — and now your students have learned it.