Relationships

Learn about how tables in a database relate to each other through one-to-one, one-to-many, and many-to-many relationships.

Imagine we’re managing the data for our bustling OnlineStore. We have information about customers, the products we sell, and the orders they place. Now, how do we ensure that an order placed by Jane Smith is correctly linked to her account and not John Doe’s? How can we efficiently list all products that fall under the Electronics category? And what if a popular item, like a Laptop, can be sourced from several different suppliers, while each of those suppliers also provides us with many other products? These crucial connections and links between different pieces of information are managed using database relationships. They form the very backbone of a well-structured and reliable relational database. Understanding them is key to managing data effectively.

In this lesson, we will dive deep into the different types of relationships you can define between tables in a database. By the end of this lesson, we will be able to:

  • Understand the fundamental concept of relationships in relational databases.

  • Clearly identify and differentiate between the three main types: one-to-one, one-to-many, and many-to-many relationships.

  • Appreciate why each type of relationship is vital for robust database design.

  • Learn how these relationships are practically implemented in MySQL using tools like primary keys, foreign keys, and special structures called junction tables.

  • Recognize real-world examples of these relationships within our OnlineStore database.

Let’s get started on unraveling how data connects!

Understanding database relationships

Before we explore the specific types, let’s briefly touch upon what database relationships are and why they’re so important. In a relational database, data is stored in tables. Relationships define how these tables are connected.

  • Data integrity: They help ensure the data is accurate and consistent. For instance, we can ensure that an order always belongs to an existing customer.

  • Reduce redundancy: Relationships help us avoid storing the same information multiple times. For example, instead of writing a customer’s full address on every order they place, we store the address once in a Customer table and link orders to it.

  • Efficient querying: Well-defined relationships make retrieving connected data from multiple tables easier and faster.

  • Reflect real-world connections: Databases often model real-world scenarios, and relationships help capture how different entities interact (e.g., a customer places an order, a product belongs to a category).

Now, let’s explore the main types of relationships. 

One-to-one (1:1) relationships

A one-to-one (1:1) relationship exists when a single record in one table is related ...