Bird
Raised Fist0
SQLquery~5 mins

One-to-many relationship design in SQL

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

When you have customers and each customer can place many orders.
When a blog has many posts, but each post belongs to one author.
When a school has many students, but each student belongs to one class.
When a company has many employees, but each employee works in one department.
Syntax
SQL
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)
);
The parent_id in the child table links to the id in the parent table.
This setup ensures each child row belongs to one parent row.
Examples
Each book is linked to one author, but one author can have many books.
SQL
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)
);
Each employee belongs to one department, but a department can have many employees.
SQL
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)
);
Sample Program

This example creates customers and their orders. Then it shows which orders belong to which customer.

SQL
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;
OutputSuccess
Important Notes

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.

Summary

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.

Practice

(1/5)
1. What does a one-to-many relationship in a database mean?
easy
A. One record in a table relates to many records in another table
B. Many records in a table relate to one record in the same table
C. One record relates to exactly one record in another table
D. Many records relate to many records in another table

Solution

  1. Step 1: Understand relationship types

    A one-to-many relationship means one record in a table connects to multiple records in another table.
  2. Step 2: Match definition to options

    One record in a table relates to many records in another table correctly describes this as one record relating to many records in another table.
  3. Final Answer:

    One record in a table relates to many records in another table -> Option A
  4. Quick Check:

    One-to-many = one record to many records [OK]
Hint: One-to-many means one record links to many records [OK]
Common Mistakes:
  • Confusing one-to-many with many-to-many
  • Thinking one-to-many means one record links to one record
  • Mixing up the direction of the relationship
2. Which SQL statement correctly creates a foreign key for a one-to-many relationship from Orders to Customers?
easy
A. ALTER TABLE Customers ADD FOREIGN KEY (OrderID) REFERENCES Orders(OrderID);
B. ALTER TABLE Customers ADD FOREIGN KEY (CustomerID) REFERENCES Orders(OrderID);
C. ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID);
D. ALTER TABLE Orders ADD FOREIGN KEY (OrderID) REFERENCES Customers(CustomerID);

Solution

  1. Step 1: Identify the 'many' and 'one' tables

    Orders is the 'many' side, Customers is the 'one' side in a one-to-many relationship.
  2. Step 2: Add foreign key in 'many' table referencing 'one' table

    The foreign key should be in Orders referencing Customers, so ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); is correct.
  3. Final Answer:

    ALTER TABLE Orders ADD FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID); -> Option C
  4. Quick Check:

    Foreign key in 'many' table references 'one' table [OK]
Hint: Foreign key goes in 'many' table pointing to 'one' table [OK]
Common Mistakes:
  • Placing foreign key in the 'one' table instead of 'many'
  • Referencing wrong columns between tables
  • Mixing table names in foreign key definition
3. Given these tables:
Customers(CustomerID, Name)
Orders(OrderID, CustomerID, Amount)
What will this query return?
SELECT Customers.Name, COUNT(Orders.OrderID) AS OrderCount FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Customers.Name;
medium
A. List of customers who have placed at least one order
B. List of customers with total amount spent on orders
C. List of orders with customer names repeated for each order
D. List of customers with the number of orders each placed, including customers with zero orders

Solution

  1. Step 1: Understand the LEFT JOIN usage

    LEFT JOIN keeps all customers, even those without matching orders.
  2. Step 2: COUNT(Orders.OrderID) counts orders per customer

    Grouping by customer name counts how many orders each customer has, zero if none.
  3. Final Answer:

    List of customers with the number of orders each placed, including customers with zero orders -> Option D
  4. Quick Check:

    LEFT JOIN + COUNT = all customers with order counts [OK]
Hint: LEFT JOIN + COUNT counts all, including zero matches [OK]
Common Mistakes:
  • Thinking COUNT counts total amount spent
  • Assuming only customers with orders appear
  • Confusing JOIN types and their effects
4. You wrote this SQL to create a one-to-many relationship:
CREATE TABLE Orders (OrderID INT PRIMARY KEY, CustomerID INT, FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));

But you get an error. What is the most likely cause?
medium
A. OrderID should not be primary key in Orders
B. Customers table does not exist or CustomerID is not a primary key
C. Foreign key should be in Customers table, not Orders
D. CustomerID column type must be VARCHAR, not INT

Solution

  1. Step 1: Check foreign key reference validity

    Foreign key must reference an existing table and a primary or unique key column.
  2. Step 2: Verify Customers table and CustomerID key

    If Customers table or CustomerID primary key is missing, error occurs.
  3. Final Answer:

    Customers table does not exist or CustomerID is not a primary key -> Option B
  4. Quick Check:

    Foreign key references must exist and be keys [OK]
Hint: Foreign key target must exist and be primary/unique key [OK]
Common Mistakes:
  • Assuming foreign key can reference non-key columns
  • Placing foreign key in wrong table
  • Mismatching data types between foreign key and referenced key
5. You have two tables:
Authors(AuthorID, Name)
Books(BookID, Title, AuthorID)
You want to find authors who have written more than 3 books. Which query is correct?
hard
A. SELECT Name FROM Authors JOIN Books ON Authors.AuthorID = Books.AuthorID GROUP BY Name HAVING COUNT(BookID) > 3;
B. SELECT Name FROM Authors LEFT JOIN Books ON Authors.AuthorID = Books.AuthorID WHERE COUNT(BookID) > 3;
C. SELECT Name FROM Books GROUP BY AuthorID HAVING COUNT(BookID) > 3;
D. SELECT Name FROM Authors WHERE AuthorID IN (SELECT AuthorID FROM Books WHERE COUNT(BookID) > 3);

Solution

  1. Step 1: Join Authors and Books on AuthorID

    We join to connect authors with their books.
  2. Step 2: Group by author name and filter by book count

    Use GROUP BY Name and HAVING COUNT(BookID) > 3 to find authors with more than 3 books.
  3. Final Answer:

    SELECT Name FROM Authors JOIN Books ON Authors.AuthorID = Books.AuthorID GROUP BY Name HAVING COUNT(BookID) > 3; -> Option A
  4. Quick Check:

    JOIN + GROUP BY + HAVING filters authors by book count [OK]
Hint: Use GROUP BY and HAVING to filter by count in one-to-many [OK]
Common Mistakes:
  • Using WHERE with aggregate functions instead of HAVING
  • Missing GROUP BY clause
  • Using LEFT JOIN but filtering with WHERE on aggregate