The Wayback Machine - https://web.archive.org/web/20240826184205/https://www.geeksforgeeks.org/one-to-many-relationship-example/
Open In App

One-To-Many Relationship Example

Last Updated : 01 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

One-To-Many Relationship signifies connection between two entities where one entity is associated with multiple instances of the other entity but each instance of second entity is associated with only one instance of first entity. Depending on how we look at it, a one-to-many relationship is also called many-to-one relationship. It is implemented using the concept of foreign keys.

1-t-m-

Here are some examples of one-to-many relationship:

  • A car maker makes many different models, but only one car maker builds a particular model.
  • One customer may make several purchases, but each purchase is made by a single customer.
  • A company can have many phone numbers, but a phone number belongs to one company.

A one-to-many relationship is not a property of the data, but rather of the relationship itself. It is also called a foreign key constraint, which is important to keep data from being duplicated and have relationships within the database stay reliable as more information is needed. For example, a customer has many orders, but each order can have only one customer.

eg

Main Concept and Syntax

In a one-to-many relationship in a database management system (DBMS), one record in the first table can be associated with one or more records in the second table. This is a fundamental concept in relational database design. In SQL, a one-to-many relationship is established using foreign keys.

Main Concept

  • One-to-many relationships are characterized by one entity (or record) in a table having multiple related entities (or records) in another table.
  • This relationship is established using foreign keys, where the primary key of the “one” table is referenced as a foreign key in the “many” table.
  • It allow us for efficient data organization and ensuring data integrity and reducing redundancy.

Syntax

CREATE TABLE ParentTable (
ParentID INT PRIMARY KEY,
ParentAttribute DataType
);

CREATE TABLE ChildTable (
ChildID INT PRIMARY KEY,
ChildAttribute DataType,
ParentID INT,
FOREIGN KEY (ParentID) REFERENCES ParentTable(ParentID)
);

Examples

Example 1: Customers and Orders

Consider a case where each customer can place multiple orders, but each order is associated with only one customer. This is the example of one-to-many relationship. Here’s how one-to-many relationship is implemented:

CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
Name VARCHAR(50)
);

CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

-- Inserting sample data for Customers
INSERT INTO Customers (CustomerID, Name) VALUES
(1, 'Shivansh Mahajan'),
(2, 'Rakesh Kumar'),
(3, 'Vikram kumar');

-- Inserting sample data for Orders
INSERT INTO Orders (OrderID, CustomerID, OrderDate) VALUES
(101, 1, '2024-04-09'),
(102, 1, '2024-04-08'),
(103, 2, '2024-04-07'),
(104, 3, '2024-04-06');

Select * from Customers;

Select * from Orders;

Customers table

customers-table

Orders table

orders-table

Visualizing the one-to-many relationship using left join as

Select * from Customers 
left join Orders
on Customers.CustomerID = Orders.CustomerID;

o-to-m-using-left-join-

In this example, ‘Customers’ table is parent table with ‘CustomerID’ as primary key and ‘Orders’ table is the child table where ‘CustomerID’ is a foreign key referencing the ‘CustomerID’ column in the ‘Customers’ table.

Example 2: Department and Employees

Another example is the relation between department and employees in an organization. Each department can have multiple employees, but each employee can belong only to one department.

CREATE TABLE Departments (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50)
);

CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
EmpName VARCHAR(50),
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Departments(DeptID)
);

-- Inserting sample data for Departments
INSERT INTO Departments (DeptID, DeptName) VALUES
(101, 'Engineering'),
(102, 'Sales'),
(103, 'Marketing');

-- Inserting sample data for Employees
INSERT INTO Employees (EmpID, EmpName, DeptID) VALUES
(201, 'Shivansh Mahajan', 101),
(202, 'Rupesh Kumar', 101),
(203, 'Kunal Kumar', 102),
(204, 'Mamta kumari', 102),
(205, 'Priya Mehta', 103);


Select * from Departments;

Select * from Employees;

Department table

Department-

Employees table

employee-new-

Visualizing the one-to-many relationship with help left join as

Select * from Departments 
left join Employees
On Departments.DeptID = Employees.DeptId;

to-o-to-m-relationship-

Here, the ‘Departments’ table acts as the parent table, and the ‘Employees’ table is the child table. The ‘DeptID’ column in the ‘Employees’ table serves as a foreign key referencing the ‘DeptID’ column in the ‘Departments’ table.

Conclusion

Learning about the one-to-many relationship helps in organizing the data in databases effectively. It’s like knowing how different things are connected. For example, how each customer can make several orders, but each order belongs to only one customer. By setting up these connections correctly using the concept of foreign keys, we ensure that our data stays organized. So, whether it’s tracking orders for customers or assigning employees to departments, understanding and using one-to-many relationships helps keep our data neat and usable.

Frequently asked questions on One to Many Relationship – FAQs

What is the purpose of a foreign key in a one-to-many relationship?

The purpose of a foreign key in a one-to-many relationship is to enforce referential integrity between the parent and child tables. It ensures that each record in the child table corresponds to a valid record in the parent table. By defining a foreign key constraint, database systems prevent orphaned records in the child table, maintaining the integrity of the relationship and data consistency.

What is a one-to-many relationship in databases?

A one-to-many relationship signifies a connection between two entities where one entity is associated with multiple instances of the other entity, but each instance of the second entity is associated with only one instance of the first entity. It is the fundamental concept in database design, often implemented using the concept of foreign keys to maintain data integrity and data organization.

What happens if a foreign key value in the child table does not match any primary key value in the parent table?

If foreign key value in the child table does not match with any primary key value in the parent table then it voilets the referential integrity. In most of the relational database management systems (RDBMS), this voilation triggers the error or constraint voilation and preventing the operation (suchb as INSERT or UPDATE) from completing successfully. The database ensures data consistency by enforcing the relationship between databases.

Are one-to-many relationships always uni-directional?

No, One-to-many can be bidirectional. While in many cases it is clear which entity is parent of which is the child, there are cases where relationship can be viewed from either direction.



Similar Reads

One-To-Many Relationship In Database
A one-to-many relationship signifies the relationship or connection between two entities where one entity is associated with multiple instances of the other entity but each instance of the second entity is associated with only one instance of the first entity. Depending on how we look at it, a one-to-many relationship is also called many-to-one rel
6 min read
Neo4j Create Relationship
In Neo4j to create relationship between nodes you have to use the CREATE statement like we used to create nodes. lets create relation between two already created nodes. Example: Already created nodes: Query to create relation:$ MATCH (a:GeeksforGeeks), (b:W3School) WHERE a.Name = "A Computer Science Portal" AND b.Name = "We are the Learner" CREATE
1 min read
What is Relationship Set in DBMS?
Relationship set in a Database Management System (DBMS) is essential as it provides the ability to store, recover, and oversee endless sums of information effectively in cutting-edge data administration, hence making a difference in organizations. In a Relational database, relationship sets are built up by utilizing keys, such as primary and foreig
4 min read
What is Relationship in DBMS?
A database is a structured data set that is usually electronically written in a computer system and stored as data. With their primary purpose being to maintain, keep, and extract data correctly, databases are important. In many practical situations, data is never an isolated file, and its correlations may be hidden. The occurrence of patterns in d
5 min read
What is Relationship Type in DBMS?
In DBMS (database management system) relationships are important concept that tells us how data is structured, stored and accessed, Just like in real life where relationships connect people (like relationship between parent and child) in same way DBMS link different data sets in a meaningful way. In this article we will study about different types
6 min read
Types of Relationship in Database
A database is a structured data set that is usually electronically written in a computer system and stored as data. With their primary purpose being to maintain, keep, and extract data correctly, databases are important. In many practical situations, data is never an isolated file, and its correlations may be hidden. The occurrence of patterns in d
5 min read
Example Queries on Relational Algebra
Given below are a few examples of a database and a few queries based on that. (1). Suppose there is a banking database which comprises following tables : Customer(Cust_name, Cust_street, Cust_city) Branch(Branch_name, Branch_city, Assets) Account (Branch_name, Account_number, Balance) Loan(Branch_name, Loan_number, Amount) Depositor(Cust_name, Acco
1 min read
Query By Example (QBE)
If we talk about normal queries we fire on the database they should be correct and in a well-defined structure which means they should follow a proper syntax if the syntax or query is wrong definitely we will get an error and due to that our application or calculation definitely going to stop. So to overcome this problem QBE was introduced. QBE sta
2 min read
What is NULL ? Give an example to illustrate testing for NULL in SQL. What is dangling tuple problem ?
What is NULL ?In Structured Query Language Null Or NULL is a special type of marker which is used to tell us about that a data value does not present in the database. In Structured Query Language (SQL) Null is a predefined word which is used to identity this marker. It is very important to understand that a NULL value is totally different than a ze
3 min read
DBMS Tutorial – Learn Database Management System
Database Management System is a software or technology used to manage data from a database. Some popular databases are MySQL, Oracle, MongoDB, etc. DBMS provides many operations e.g. creating a database, Storing in the database, updating an existing database, delete from the database. DBMS is a system that enables you to store, modify and retrieve
7 min read
SQL Query Interview Questions
SQL or Structured Query Language is a standard language for relational databases. SQL queries are powerful tools used to, manipulate, and manage data stored in these databases like MySQL, Oracle, PostgreSQL, etc. Whether you're fetching specific data points, performing complex analyses, or modifying database structures, SQL queries provide a standa
10 min read
Data Models in DBMS
A Data Model in Database Management System (DBMS)  is the concept of tools that are developed to summarize the description of the database. Data Models provide us with a transparent picture of data which helps us in creating an actual database. It shows us from the design of the data to its proper implementation of data. Types of Relational ModelsC
8 min read
Difference between File System and DBMS
The file system is basically a way of arranging the files in a storage medium like a hard disk. The file system organizes the files and helps in the retrieval of files when they are required. File systems consist of different files which are grouped into directories. The directories further contain other folders and files. The file system performs
4 min read
What is Database?
A database is an organized collection of data stored in a computer system and usually controlled by a database management system (DBMS). The data in common databases is modeled in tables, making querying and processing efficient. Structured query language (SQL) is commonly used for data querying and writing. The Database is an essential part of our
7 min read
SQL Trigger | Student Database
A trigger is a stored procedure in a database that automatically invokes whenever a special event in the database occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when specific table columns are updated. In simple words, a trigger is a collection of SQL statements with particular names that are stored i
7 min read
CTE in SQL
The Common Table Expressions (CTE) were introduced into standard SQL in order to simplify various classes of SQL Queries for which a derived table was just unsuitable. CTE was introduced in SQL Server 2005, the common table expression (CTE) is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement.
6 min read
SQL | WITH Clause
The SQL WITH clause, also known as Common Table Expressions (CTEs), was introduced by Oracle in the Oracle 9i release 2 database. The SQL WITH clause allows you to give a sub-query block a name (a process also called sub-query refactoring), which can be referenced in several places within the main SQL query.  What is the SQL WITH Clause?The clause
3 min read
SQL Interview Questions
SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM Computer Scientists in the 1970s. By executing queries, SQL can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that
15+ min read
SQL CREATE TABLE
CREATE TABLE command creates a new table in the database in SQL. In this article, we will learn about CREATE TABLE in SQL with examples and syntax. SQL CREATE TABLE StatementSQL CREATE TABLE Statement is used to create a new table in a database. Users can define the table structure by specifying the column's name and data type in the CREATE TABLE c
3 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL Join operation combines data or rows from two or more tables based on a common field between them. In this article, we will learn about Joins in SQL, covering JOIN types, syntax, and examples. SQL JOINSQL JOIN clause is used to query and access data from multiple tables by establishing logical relationships between them. It can access data from
5 min read
Types of Keys in Relational Model (Candidate, Super, Primary, Alternate and Foreign)
Keys are one of the basic requirements of a relational database model. It is widely used to identify the tuples(rows) uniquely in the table. We also use keys to set up relations amongst various columns and tables of a relational database. Different Types of Database KeysCandidate KeyPrimary KeySuper KeyAlternate KeyForeign KeyComposite KeyCandidate
6 min read
Introduction of DBMS (Database Management System) - Set 1
A Database Management System (DBMS) is a software system that is designed to manage and organize data in a structured manner. It allows users to create, modify, and query a database, as well as manage the security and access controls for that database. DBMS provides an environment to store and retrieve the data in convenient and efficient manner. K
9 min read
DBMS Architecture 1-level, 2-Level, 3-Level
A Database stores a lot of critical information to access data quickly and securely. Hence it is important to select the correct architecture for efficient data management. DBMS Architecture helps users to get their requests done while connecting to the database. We choose database architecture depending on several factors like the size of the data
4 min read
ACID Properties in DBMS
A transaction is a single logical unit of work that accesses and possibly modifies the contents of a database. Transactions access data using read and write operations. In order to maintain consistency in a database, before and after the transaction, certain properties are followed. These are called ACID properties. For those looking to master thes
6 min read
Introduction of ER Model
Peter Chen developed the ER diagram in 1976. The ER model was created to provide a simple and understandable model for representing the structure and logic of databases. It has since evolved into variations such as the Enhanced ER Model and the Object Relationship Model The Entity Relational Model is a model for identifying entities to be represent
10 min read
SQL Query to Find Second Highest Salary
There are a lot of real-world scenarios where a query for finding the nth salary will be really useful. Considering finding the second-highest salary in SQL, we have one sample table. Finding Second Highest SalaryConsider below simple table: Name Salary Aman100000Shubham1000000Naveen 40000Nishant500000How to find the employee whose salary is the se
3 min read
Normal Forms in DBMS
Normalization is the process of minimizing redundancy from a relation or set of relations. Redundancy in relation may cause insertion, deletion, and update anomalies. So, it helps to minimize the redundancy in relations. Normal forms are used to eliminate or reduce redundancy in database tables. Normalization of DBMSIn database management systems (
12 min read
Introduction of Relational Algebra in DBMS
Pre-Requisite: Relational Model in DBMS Relational Algebra is a procedural query language. Relational algebra mainly provides a theoretical foundation for relational databases and SQL. The main purpose of using Relational Algebra is to define operators that transform one or more input relations into an output relation. Given that these operators ac
4 min read
Commonly asked DBMS interview questions
1. What are the advantages of DBMS over traditional file-based systems? Database management systems were developed to handle the following difficulties of typical File-processing systems supported by conventional operating systems. 1. Data redundancy and inconsistency 2. Difficulty in accessing data 3. Data isolation – multiple files and formats 4.
15+ min read
Introduction of B-Tree
The limitations of traditional binary search trees can be frustrating. Meet the B-Tree, the multi-talented data structure that can handle massive amounts of data with ease. When it comes to storing and searching large amounts of data, traditional binary search trees can become impractical due to their poor performance and high memory usage. B-Trees
15+ min read
Article Tags :