← Back to Chapters

MySQL Table Relationships

?️ MySQL Table Relationships

? Quick Overview

In MySQL, table relationships define how data in one table is connected to data in another table. Relationships improve data organization, reduce duplication, and enforce consistency using foreign keys.

? Key Concepts

  • Primary Key (PK) – Uniquely identifies each row in a table
  • Foreign Key (FK) – A column that refers to a primary key in another table
  • Referential Integrity – Ensures relationships remain valid
  • Constraints – Rules applied to columns (FOREIGN KEY, UNIQUE, NOT NULL)
  • Normalization – Organizing tables to avoid redundancy

? Syntax / Theory

One-to-One

Each record in Table A relates to one record in Table B.

One-to-Many

One record in Table A can relate to many records in Table B.

Many-to-Many

Records in both tables can be related to multiple records using a junction table.

? Code Example(s)

? View Code Example
// Create parent table (Customers)
CREATE TABLE customers (
id INT PRIMARY KEY,
name VARCHAR(50)
);
// Create child table (Orders) with foreign key
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);
? View Code Example
// Many-to-Many using junction table (students & courses)
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(40)
);
CREATE TABLE courses (
id INT PRIMARY KEY,
title VARCHAR(50)
);
CREATE TABLE enrollments (
student_id INT,
course_id INT,
PRIMARY KEY(student_id, course_id),
FOREIGN KEY(student_id) REFERENCES students(id),
FOREIGN KEY(course_id) REFERENCES courses(id)
);

? Live Output / Explanation

✅ What Happens Here?

  • You cannot insert an order with a non-existing customer.
  • If a student or course is deleted, related enrollments become invalid.
  • MySQL enforces relationships using foreign key rules.

✅ Tips & Best Practices

  • Always define primary keys first.
  • Use meaningful column names for foreign keys.
  • Avoid storing duplicate data across tables.
  • Use indexing on foreign keys for better performance.
  • Plan relationships before creating tables.

? Try It Yourself / Practice Tasks

  1. Create two related tables: departments and employees.
  2. Add a foreign key from employees to departments.
  3. Insert sample records and test invalid foreign key inserts.
  4. Create a many-to-many relationship using a third table.