Introduction
A one-to-many relationship helps connect two sets of data where one item links to many others. It keeps data organized and easy to find.
Jump into concepts and practice - no test required
A one-to-many relationship helps connect two sets of data where one item links to many others. It keeps data organized and easy to find.
CREATE TABLE ParentTable ( id INT PRIMARY KEY, other_columns ... ); CREATE TABLE ChildTable ( id INT PRIMARY KEY, parent_id INT, other_columns ..., FOREIGN KEY (parent_id) REFERENCES ParentTable(id) );
parent_id in the child table links to the id in the parent table.CREATE TABLE Authors ( author_id INT PRIMARY KEY, name VARCHAR(100) ); CREATE TABLE Books ( book_id INT PRIMARY KEY, title VARCHAR(100), author_id INT, FOREIGN KEY (author_id) REFERENCES Authors(author_id) );
CREATE TABLE Departments ( dept_id INT PRIMARY KEY, dept_name VARCHAR(50) ); CREATE TABLE Employees ( emp_id INT PRIMARY KEY, emp_name VARCHAR(100), dept_id INT, FOREIGN KEY (dept_id) REFERENCES Departments(dept_id) );
This example creates customers and their orders. Then it shows which orders belong to which customer.
CREATE TABLE Customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(50) ); CREATE TABLE Orders ( order_id INT PRIMARY KEY, order_date DATE, customer_id INT, FOREIGN KEY (customer_id) REFERENCES Customers(customer_id) ); INSERT INTO Customers VALUES (1, 'Alice'), (2, 'Bob'); INSERT INTO Orders VALUES (101, '2024-06-01', 1), (102, '2024-06-02', 1), (103, '2024-06-03', 2); SELECT c.customer_name, o.order_id, o.order_date FROM Customers c JOIN Orders o ON c.customer_id = o.customer_id ORDER BY c.customer_id, o.order_id;
Always define the foreign key to keep data linked correctly.
Deleting a parent row may affect child rows if not handled carefully.
Use indexes on foreign keys for faster queries.
One-to-many links one record to many records in another table.
Use a foreign key in the 'many' table to connect to the 'one' table.
This design helps keep data organized and easy to query.
Orders to Customers?Customers(CustomerID, Name)Orders(OrderID, CustomerID, Amount)SELECT Customers.Name, COUNT(Orders.OrderID) AS OrderCount FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.Name;
CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));
Authors(AuthorID, Name)Books(BookID, Title, AuthorID)