A Guide to Relationships in SQL: One-to-One, One-to-Many, and Many-to-Many
By Mukesh Kumar
Updated on Apr 21, 2025 | 22 min read | 1.2k views
Share:
For working professionals
For fresh graduates
More
By Mukesh Kumar
Updated on Apr 21, 2025 | 22 min read | 1.2k views
Share:
Did you know? An online store with a one-to-many relationship between customers and orders can easily track millions of transactions. A many-to-many relationship can help social networks like Facebook efficiently manage user interactions, such as likes and comments, without duplicating data.
In SQL, relationships between tables are essential for organizing and linking data in a meaningful way. Understanding the types of relationships helps you design efficient databases that maintain data integrity and streamline queries.
For instance, when you’re building a school management system. You have a Students table and a Courses table. In a one-to-many relationship, each student can enroll in multiple courses, but each course is only assigned to one student. However, when students can enroll in multiple courses and each course can have many students, you’re dealing with a many-to-many relationship. Understanding these relationships allows you to manage complex data interactions effectively.
In this guide, you’ll learn about these relationships, how they work, and how to implement them in your SQL database to ensure smooth and scalable data management.
In SQL, relationships are how tables in a relational database are connected. These connections ensure that data is organized in a structured and efficient way, preventing redundancy and maintaining consistency across your database.
For example, consider a Customers table and an Orders table. The Customers table contains information about each customer, such as their name and contact details.
The Orders table contains details about each order, such as the order ID, the product purchased, and the customer who made the purchase. The table would have a CustomerID field, which is a foreign key linking back to the Customers table.
Referential Integrity: These relationships are crucial for referential integrity, which ensures that data remains accurate across tables. For instance, let’s say a customer is deleted from the Customers table.
The referential integrity prevents orphaned orders from existing in the Orders table (i.e., orders that no longer have an associated customer).
Normalization: This structure also supports normalization, which is the process of organizing data to reduce redundancy and improve data integrity. By breaking data into related tables, you avoid storing the same information in multiple places.
In short, relationships in SQL help maintain data consistency and reduce redundancy, ensuring your database is both efficient and reliable.
Relationships play a crucial role in maintaining data integrity, which means ensuring your data is accurate, consistent, and reliable. Without proper relationships, you might end up with duplicate data or missing connections between tables.
Example 1: Customer and Orders
In a customer-orders database, if there's no relationship between the Customers and Orders tables, customer info might be repeated in each order, causing redundancy. By linking these tables with a CustomerID, you store customer info once, reducing duplication.
Example 2: School Database
In a school database, a student can enroll in many classes, and each class can have many students. Without a relationship, you risk duplicating student data in each class. A junction table (like StudentClass) references both tables, keeping the data organized and minimizing redundancy.
Normalization helps eliminate redundancy by storing data in the correct tables and linking them with relationships (e.g., foreign keys). In our Customer-Order example, customer data is stored once, while orders simply reference the customer, reducing repeated data.
Pro Tip: When designing your database, always think about how tables relate to each other before adding data. A well-defined relationship in your database schema saves you time and effort when scaling or maintaining your system.
Want to learn how to use SQL for efficiently managing databases? Join upGrad’s Online Software Development Courses and work on hands-on projects that simulate real industry scenarios. With a focus on trending programming languages and the latest technologies, you’ll be equipped for success in your career.
Also Read: Top 27 SQL Projects in 2025 With Source Code: For All Levels
Primary and foreign keys are the core of relational database relationships. Let’s dive deeper into their roles and how they maintain referential integrity between tables.
1. Primary Key: A Primary Key is a column (or set of columns) that uniquely identifies each record in a table. It ensures that no two rows in a table have the same value for the primary key.
Example Code: In the Customers table, the CustomerID is the primary key.
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(100)
);
Example Data:
CustomerID is set as the primary key, meaning no two customers can share the same ID. This guarantees that every customer has a unique identifier.
INSERT INTO Customers (CustomerID, CustomerName)
VALUES (1, 'Athri'), (2, 'Rahul');
Expected Output:
Query to select customers:
SELECT * FROM Customers;
CustomerID |
CustomerName |
1 | Athri |
2 | Rahul |
2. Foreign Key: It creates a link between two tables by referencing the primary key in another table. It ensures that the data in the referencing table corresponds to valid data in the referenced table.
Example Code: In the Orders table, the CustomerID column is a foreign key referencing the CustomerID in the Customers table.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
The CustomerID in the Orders table is a foreign key that references the CustomerID in the Customers table. This ensures that each order is linked to a valid customer.
Example Data:
INSERT INTO Orders (OrderID, OrderDate, CustomerID)
VALUES (101, '2025-04-01', 1), (102, '2025-04-02', 2);
Expected Output: Query to retrieve orders and their customer details:
SELECT OrderID, OrderDate, CustomerName
FROM Orders
JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
OrderID |
OrderDate |
CustomerName |
101 | 2025-04-01 | Athri |
102 | 2025-04-02 | Rahul |
Understanding how primary and foreign keys define relationships is essential for building efficient SQL databases. Whether you're designing one-to-many, many-to-many, or one-to-one relationships, using the right keys helps maintain data integrity and simplifies querying.
When you’re well-versed with SQL, pairing your expertise with one of upGrad’s DBA programs from world-class B-Schools can help you move into C-Suite roles in technology. Along with earning a doctorate, you’ll publish original research and collaborate with industry leaders, building the foundation of an excellent career.
Also Read: MySQL vs. MongoDB: Difference Between SQL & MongoDB
Now that you’re familiar with relationships in SQL, let’s look at its different types in more detail.
Understanding the different types of relationship in SQL is crucial for designing a well-structured database. These relationships dictate how tables are linked and how data flows between them.
Let's break down the most common types of relationship in SQL you’ll encounter.
A One-to-One relationship occurs when one record in a table is related to exactly one record in another table. This is used in cases where each record in both tables should have a unique counterpart.
Example: Let’s say you are creating a Users table, where each user has a UserProfile. The UserProfile is unique to the user, and you want to store it in a separate table.
SQL Setup:
CREATE TABLE Users (
UserID INT PRIMARY KEY,
UserName VARCHAR(100)
);
CREATE TABLE UserProfiles (
ProfileID INT PRIMARY KEY,
UserID INT UNIQUE,
ProfileDetails VARCHAR(255),
FOREIGN KEY (UserID) REFERENCES Users(UserID)
);
Users table holds the unique information of users. UserProfiles table holds the detailed user profile but has a foreign key (UserID) that references the Users table. UserID is marked as UNIQUE to ensure a one-to-one relationship.
Example Data:
INSERT INTO Users (UserID, UserName) VALUES (1, 'Rohan');
INSERT INTO UserProfiles (ProfileID, UserID, ProfileDetails) VALUES (1, 1, 'Profile details of Rohan');
Expected Output: Query to retrieve user profile:
SELECT UserName, ProfileDetails FROM Users
JOIN UserProfiles ON Users.UserID = UserProfiles.UserID;
Result:
UserName |
ProfileDetails |
Rohan | Profile details of Rohan |
In a One-to-Many relationship, one record in the first table is related to multiple records in the second table. This is the most common relationship in SQL databases.
Example: Let’s consider a Customers table and an Orders table. Each customer can place multiple orders, but each order is linked to one customer.
SQL Setup:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(100)
);
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
OrderDate DATE,
CustomerID INT,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
Customers table stores customer information. Orders table stores order information, and each order references a customer through the CustomerID foreign key.
Example Data:
INSERT INTO Customers (CustomerID, CustomerName) VALUES (1, 'Athri'), (2, 'Rahul');
INSERT INTO Orders (OrderID, OrderDate, CustomerID) VALUES (101, '2025-04-01', 1), (102, '2025-04-02', 1), (103, '2025-04-03', 2);
Expected Output: Query to list all orders and their associated customer names:
SELECT CustomerName, OrderID, OrderDate FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID;
Result:
CustomerName |
OrderID |
OrderDate |
Athri | 101 | 2025-04-01 |
Athri | 102 | 2025-04-02 |
Rahul | 103 | 2025-04-03 |
A Many-to-Many relationship occurs when multiple records in one table are related to multiple records in another table. This relationship requires a join table to store the associations.
Example: Imagine a Students table and a Courses table. A student can enroll in multiple courses, and a course can have many students.
SQL Setup:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
StudentName VARCHAR(100)
);
CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100)
);
CREATE TABLE StudentCourses (
StudentID INT,
CourseID INT,
PRIMARY KEY (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
The Students table stores student information. The Courses table stores course information. The StudentCourses join table links students to courses, using two foreign keys.
Example Data:
INSERT INTO Students (StudentID, StudentName) VALUES (1, 'Rohan'), (2, 'Reshma');
INSERT INTO Courses (CourseID, CourseName) VALUES (1, 'Math'), (2, 'Science');
INSERT INTO StudentCourses (StudentID, CourseID) VALUES (1, 1), (1, 2), (2, 1);
Expected Output: Query to get the list of students and their courses:
SELECT StudentName, CourseName FROM Students
JOIN StudentCourses ON Students.StudentID = StudentCourses.StudentID
JOIN Courses ON StudentCourses.CourseID = Courses.CourseID;
Result:
StudentName |
CourseName |
Rohan | Math |
Rohan | Science |
Reshma | Math |
A self-referencing relationship happens when rows within the same table are related to each other. This is useful for representing hierarchical data, such as employees and their managers.
What is a Self-Join? A self-join allows you to join a table with itself to represent relationships among its own rows.
Example: Consider an Employees table where each employee reports to a manager, and the manager is also an employee in the same table.
SQL Setup
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
EmployeeName VARCHAR(100),
ManagerID INT,
FOREIGN KEY (ManagerID) REFERENCES Employees(EmployeeID)
);
The Employees table stores employee information and their manager’s EmployeeID (self-referencing).
Example Data:
INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID) VALUES (1, 'Athri', NULL), (2, 'Rahul', 1), (3, 'Sourab', 1);
Expected Output: Query to list employees and their managers:
SELECT E.EmployeeName AS Employee, M.EmployeeName AS Manager
FROM Employees E
LEFT JOIN Employees M ON E.ManagerID = M.EmployeeID;
Result:
Employee |
Manager |
Athri | NULL |
Rahul | Alice |
Sourab | Alice |
Now that you know how and when to implement these SQL relationships, you can design efficient, scalable, and normalized databases.
Also Read: Top Data Modeling Tools for Effective Database Design in 2025
Next, let’s look at how you can view relationships in SQL.
In SQL Server, understanding and visualizing the relationships between tables is essential for efficient database management. These relationships help you maintain data integrity and query your data effectively.
You can view these relationships through graphical tools like SQL Server Management Studio (SSMS) or by directly querying system tables.
Let’s walk through how to do both and show the expected outputs.
SQL Server Management Studio (SSMS) allows you to visualize the relationships between tables in your database using Database Diagrams.
Steps:
Example: In the diagram, you will see lines connecting tables like Customers and Orders where CustomerID from the Orders table is linked to CustomerID in the Customers table.
If you prefer to query the database directly, SQL Server provides system tables that allow you to view foreign key relationships.
Example Code: To find all foreign key relationships in your database, you can query the system catalog views sys.foreign_keys and sys.tables.
SELECT
fk.name AS FK_name,
tp.name AS parent_table,
ref.name AS referenced_table
FROM
sys.foreign_keys fk
INNER JOIN sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN sys.tables ref ON fk.referenced_object_id = ref.object_id;
sys.foreign_keys: Contains information about foreign keys. sys.tables: Contains information about the tables involved in the foreign key relationship.
Expected Output: This query will return a list of foreign keys along with their associated parent and referenced tables. Here’s what the result might look like:
FK_name |
parent_table |
referenced_table |
FK_Orders | Orders | Customers |
FK_OrderLine | OrderLines | Orders |
In this case:
Want to learn how to use the data in your database for better decision-making? upGrad’s Introduction to Data Analysis using Excel. Learn to clean, analyze & visualize data using pivot tables, formulas & more. Ideal for beginners, this certification boosts analytical skills.
Also Read: DBMS vs. RDBMS: Understanding the Key Differences, Features, and Career Opportunities
Now that you know how to view table relationships in SQL, let’s understand how you can choose the right relationship for your database.
Let’s dive deeper into the different types of relationships in SQL, exploring how they function and why they are crucial for your database design. Understanding these relationships isn’t just about connecting tables. It's about structuring your data for optimal performance, integrity, and scalability.
Whether you’re building a simple application or a complex, data-driven system, these relationships will enable you to design a database that’s both efficient and flexible.
Your data requirements will be the driving force behind your decision on which relationship to use. Consider the data flow and how the entities are connected.
Here's a breakdown of how the data’s structure will influence the relationship you choose:
1. One-to-One is useful for data that’s conceptually one-to-one but needs to be stored separately for organizational reasons (e.g., User Profiles linked to Users).
2. One-to-Many is ideal when one entity can have multiple associated records in another table. For example, Customers placing multiple Orders—where a customer can have multiple orders, but each order is linked to one customer.
3. Many-to-Many is useful when both entities in the relationship can have multiple associations. A good example is a “Students” and “Courses” table, where students can enroll in multiple courses, and each course can have many students.
If your goal is to minimize redundancy and improve data integrity, normalizing your database structure is the way to go. This usually involves using One-to-Many relationships or One-to-One relationships where possible.
Normalization is key when you need to keep your dataConsistent and reduce the risk of anomalies in updates, deletes, or inserts.
If your system needs fast queries, particularly in reporting or analytics, denormalization might be the better approach. In such cases, you might opt for a Many-to-Many relationship where multiple records in both tables are linked, often using a join table.
This is common in applications where performance (e.g., for complex reports) outweighs the need for strict data consistency.
Also Read: SQL Interview Questions & Answers from Beginner to Expert Guide
Let’s look at some practical scenarios with example use cases where different SQL relationships are preferred.
1. One-to-One: Use this when each record in one table corresponds to a unique record in another table, and you want to keep them separate for organizational or scalability reasons.
Example Use Cases:
Why Choose One-to-One? It’s simple, effective, and ideal for cases where data should be isolated to avoid complexity but still needs to be tightly linked to a single record.
2. One-to-Many: Use this when one entity is associated with many others, but the reverse isn’t true. This is the most common relationship and works best for situations where one piece of data can relate to multiple other pieces of data.
Example Use Cases:
Why Choose One-to-Many? This is the most common scenario in relational databases. It’s ideal for applications like e-commerce, blogging platforms, and CRMs where a single entity (like a customer or post) has many related records (like orders or comments).
3. Many-to-Many: Use this when both tables can have multiple associations. For example, when many records in one table relate to many records in another table.
Example Use Cases:
Why Choose Many-to-Many? This relationship is ideal when the entities involved are inherently linked in multiple ways. For example, Students and Courses can’t be easily simplified into one-to-one or one-to-many because a student’s courses can change over time, and a course can have many students.
When choosing a relationship type, consider performance:
Here are some best practices for each relationship:
Choosing the right SQL relationship type boils down to understanding your data and how it connects. Each decision has a significant impact on your database performance, data integrity, and scalability.
Also Read: Is SQL Hard to Learn? Breaking Down the Challenges and Solutions
With a solid understanding of Relationships in SQL, the next step is advancing your career in database management. Let’s explore how upGrad can help you deepen your knowledge and enhance your expertise in SQL.
Understanding and properly implementing one-to-one, one-to-many, and many-to-many relationships is key to maintaining a well-structured database. To efficiently use these relationships in SQL, hands-on practice through courses and tutorials is essential. You can learn how to create and manage these relationships step-by-step by working on real-world database projects.
Platforms like upGrad offer courses that dive deep into SQL fundamentals, including how to establish and manage relationships. With structured lessons and interactive tutorials, upGrad helps bridge the gap between theory and real-world application.
Courses worth checking out:
It’s your journey, but you don’t have to figure it all out alone. Connect with upGrad’s career counseling for personalized guidance. You can also visit a nearby upGrad center to upskill and improve your career opportunities!
Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.
Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.
Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources