Calculating... until our next FREE Code-Along Session. Secure your spot now

How To Create Many-to-Many Relationships in SQL

Avatar photo
Dominik Keller
Oct 12th, 2023
Blog

Learn How to Implement Many-To-Many Relationships With an Easy Example

Relational database systems, such as MySQL, PostgreSQL, or SQLite make storing and retrieving data quick and efficient. The underlying principle of a relational database is to store data in related tables, which avoids data redundancy. Tables can be related in several ways: in a one-to-one relationship, a one-to-many relationship, or in a many-to-many relationship.

Of these three, only the many-to-many relationship requires an extra table, called a join table, junction table, intersection table, or cross-reference table.

Let’s figure out how to create many-to-many relationships in SQL.


Implement a Many-to-Many Relationship in a Web Application

Learn how to implement many-to-many relationships by building a web application on a MySQL database in Five’s database app builder.


Build a Custom Web App With a Many-To-Many Relationship
Sign Up For Free Access to Five's Database App Builder






Understanding Many-to-Many Relationships

The real world is full of many-to-many relationships. Consequently, implementing this relationship in a database design is a common task for database administrators or anyone working with databases.

For example, let’s say we have been given the task to build an Event Management System. The system is supposed to let us store data about events and participants:

  1. Events have an event name, location, and date, and
  2. Participants have names, email addresses, and a company.

This is a classic example of a many-to-many or N:N relationship: one event can have many participants. And one participant can attend many events. Our hypothetical participant John Doe, who likes to party, attended both Coachella and Burning Man. And so did his wife, Jane Doe. Each participant (John and Jane) attended many events. And each event had many participants.

How do we implement this in our database schema? Let’s get started by thinking about our tables and entity relationship diagram.


Implementing a Many-to-Many Relationship in SQL

To implement a many-to-many relationship we need something called a join table.

A join table has exactly one purpose: it joins the two tables that have a many-to-many relationship. It stores all of the information describing the many-to-many relationship. In our case, it keeps track of every event and participant by referencing each event’s and participant’s primary keys.


Many-to-Many Relationships (6-min video)

Watch the video below to create a many-to-many relationship, using Five, a SQL-based low-code development environment that lets you rapidly develop and deploy database applications.


If you don’t feel like watching the video, follow the steps below to create a many-to-many relationship between two tables. Let’s begin and create our database.

Step 1: Creating the Event and Participant Tables

First, create your Event and Participant table. As described above, an event has a name, location, and date. A participant has a name, email, and company.

Here’s what our tables look like:

Five.Co - The Event and Participant Table

What’s the most important field in each one of these tables?

It’s the Primary Key, which in our database schema is marked by the little key icon. A primary key is a unique identifier of each record inside your table. In the Event table, the primary key is the EventKey. In the Participant table, it’s the ParticipantKey.

The primary key is what we’re referencing in our join table, which we will create in the next steps. And if you require, here’s the SQL statement to create the two tables above:

-- Create a new database (if it doesn't exist)
CREATE DATABASE IF NOT EXISTS YourDatabaseName;

-- Use the newly created database
USE YourDatabaseName;

-- Create the Event table
CREATE TABLE IF NOT EXISTS Event (
    EventKey INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255),
    date DATE,
    location VARCHAR(255)
);

-- Create the Participant table
CREATE TABLE IF NOT EXISTS Participant (
    ParticipantKey INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255),
    company VARCHAR(255),
    email VARCHAR(255)
);

Step 2: Creating the EventParticipant Join Table

Now, let’s create our join table. The join table has exactly three fields: its own primary key, and the EventKey and ParticipantKey as foreign keys from our Event and Participant table.

Here’s what our database schema will look like with the join table established:

Five.Co - For a many-to-many relationship a join table is required

Note that our join table has the name EventParticipant: this is easy to understand and descriptive. Usually, join tables follow this naming convention of using the names of the two tables represented in it.

Secondly, our join table has a one-to-many relationship to both Participant and Event. This ensures that whenever a participant joins an event, a new record is created in our join table. In this way, the table keeps track of all events and their participants. A many-to-many relationship is effectively just two one-to-many relationships.

Lastly, also note that the join table does not store any redundant information. It only stores what it needs to know: the primary keys of participants and events. Now, if you would like to write a query such as “Which events did John Doe participate in?”, you can

  1. identify John through his ParticipantKey in your Participant table,
  2. identify all events that John participated in from the EventParticipant table. This will enable you to get access to each event’s EventKey, and
  3. get additional information about each event from the Event table using the EventKey.

To create this table and its relationships, use this SQL statement:

-- Create the Join Table to establish a many-to-many relationship
CREATE TABLE EventParticipant (
    PRIMARY KEY (EventID, ParticipantID),
    FOREIGN KEY (EventID) REFERENCES Event(EventKey),
    FOREIGN KEY (ParticipantID) REFERENCES Participant(ParticipantKey)
);

You’re already done: to implement your many-to-many relationship, you have created three tables that each store unique records: one in relation to your events, one in relation to your participants, and one that puts them all together by storing the Primary Keys of Participants and Events in a join table.

The logic behind setting up a many-to-many relationship in this way is pretty simple: we can now retrieve from our join table a record. Said record will guide us toward our participant table via the ParticipantKey. And it will also guide us toward our event table using the EventKey. In short, the join table gives us just the right amount of information to match participants with events and vice versa.


Using Five to Create MySQL Databases

Five is an easy-to-use database application builder that comes with a graphical interface for creating a MySQL database. For free access, sign up here.

Five makes it easy to create a MySQL database because of its powerful, visual database features.

Creating the three tables to create a database with a many-to-many relationship can accomplished in Five with just a few clicks!


1. Visually Create Tables in Five

Five lets users create database tables visually and without writing SQL. Simply download Five, create a new app, and go to Data > Table Wizard.

Using Five’s Table Wizard, creating the Event table, is as easy as adding fields and defining their data type. Five supports all standard SQL data types, from binary to boolean to string.

In short, Five’s visual table wizard replaces the tedious task of having to write out everything in SQL. It replaces CREATE statements with an intuitive table designer that covers all common SQL data types.

Here’s what creating the Event table looks like in Five. We are adding three fields to the table: Name, Date, and Location.

Five lets users create database tables visually

2. Let Five Auto-Generate Primary Keys

Note how in the screenshot above, there are only three fields being added to my Event table. But where’s our fourth field, the primary key?

Five will automatically add a primary key to a newly created table. You don’t have to worry about doing so yourself. Given the importance of primary keys for database design, this is a great time saver for developers.

Primary keys generated by Five are GUIDs, and the chance of ever having two primary keys being the same is virtually zero.


3. Use Five to Create Table Relationships

Creating relationships between tables is also really easy in Five.

When creating a new table using the Table Wizard just mentioned, Five will ask you whether you’d like to establish any relationships between tables.

Simply select the tables that your new table is related to, and Five will insert a Foreign Key for you. This comes in very handy when creating a join table, which has two one-to-many relations!


4. Visually Inspect Your Database Schema

Your Entity-Relationship Diagram can be viewed in Five, using Five’s visual database modeler.

This feature gives you a visual representation of your database, its tables, and relationships. If you’re ever in doubt about your database structure, Five’s database modeler is a handy tool to figure out how different tables are related to each other.

All of the screenshots shown above of the Event, Participant, and EventParticipant join table were created using Five’s database modeler.

Five.Co - Database Modeler

Overall, Five makes SQL simple, easy, and accessible: you don’t need to struggle with queries, complicated setups, or credentials.

Sign up for a free trial now and create your database, its tables, and their relationships visually.


Expansion: Build a Web App on a MySQL Database

Learn how to build an entire web app on a SQL database by following our step-by-step app development guide.

The guide starts with the creation of a database from scratch and finishes with a web app that contains a chart, PDF reports, and forms for users to interact with your data. You will learn how to combine all these front-end elements with your back-end database.

Best of all: it’s free to follow!


Recap: How to Implement Many-to-Many Relationships in SQL

Here’s our recap: many-to-many relationships are part and parcel of good relational database design. To implement a many-to-many relationship between two tables, create a new table containing the primary key of each table. Remember: many-to-many relationships are just two one-to-many relationships!


Start developing your first application!

Get Started For Free Today

Sign Up Free Book a demo
Develop your first application with Five now. Start Free

Thank you for your message!

Our friendly staff will contact you shortly.

CLOSE