Free course · Lesson 3 of 5
Joins & Table Relationships
In this lesson you will
- Link tables with primary and foreign keys
- Combine tables with INNER and LEFT JOIN
Databases use relationships to connect tables via foreign keys. A
JOIN combines rows from two or more tables based on a related column. The most common
type is INNER JOIN, which returns only matching rows. This is how you link students to
their enrolled courses, orders to customers, or projects to teams.
- A primary key (e.g.,
student_id) uniquely identifies each row in a table. - A foreign key (e.g.,
student_idin theenrollmentstable) references the primary key of another table. INNER JOINreturns only rows with matching keys in both tables.LEFT JOINreturns all rows from the left table, even if no match exists on the right.
💡 Practical Skill: Design your database on paper first — draw Entity-Relationship Diagrams (ERDs) using tools like draw.io or MySQL Workbench. A clear schema prevents data duplication and keeps your queries fast.
SQL (MySQL / PostgreSQL)
-- Create a related enrollments tableCREATE TABLE enrollments ( enrollment_id INT PRIMARY KEY AUTO_INCREMENT, student_id INT, course VARCHAR(100), enrollment_date DATE, FOREIGN KEY (student_id) REFERENCES students(id)); -- Insert enrollment dataINSERT INTO enrollments (student_id, course, enrollment_date)VALUES (1, 'Database Management', '2026-01-15'), (1, 'SQL Advanced', '2026-02-01'), (2, 'Web Development', '2026-01-20'), (3, 'Data Science', '2026-01-25'); -- INNER JOIN: show student names with their coursesSELECT s.name, e.course, e.enrollment_dateFROM students sINNER JOIN enrollments e ON s.id = e.student_idORDER BY s.name;-- Output: Grace (Database Management, 2026-01-15)-- Output: Grace (SQL Advanced, 2026-02-01)-- Output: John (Web Development, 2026-01-20)-- Output: Amina (Data Science, 2026-01-25) -- LEFT JOIN: show ALL students even if not enrolledSELECT s.name, e.courseFROM students sLEFT JOIN enrollments e ON s.id = e.student_id;
Practice exercise
With students and payments tables, list every student with their total paid, including students who have paid nothing.
Key takeaways
- Foreign keys connect related tables
- INNER JOIN keeps only matching rows
- LEFT JOIN keeps every row from the left table
Free self-study lesson — no certificate. For the full instructor-led program, see registration options.