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
Joining on primary key to foreign key
📖 Scenario: You work at a small bookstore. The store keeps two tables: one for authors and one for books. Each book is written by one author. You want to combine information from both tables to see the book titles along with their authors' names.
🎯 Goal: Create two tables, authors and books, with a primary key and a foreign key relationship. Then write a SQL query to join these tables on the author's ID to list each book with its author's name.
📋 What You'll Learn
Create a table called authors with columns author_id (primary key) and author_name.
Create a table called books with columns book_id (primary key), title, and author_id (foreign key referencing authors.author_id).
Insert exactly these books: (101, 'Pride and Prejudice', 1), (102, 'Adventures of Huckleberry Finn', 2), (103, 'Harry Potter and the Sorcerer''s Stone', 3).
Write a SQL query that joins books and authors on author_id to select title and author_name.
💡 Why This Matters
🌍 Real World
Bookstores, libraries, and many businesses use primary key to foreign key joins to combine related data from different tables, like linking books to their authors.
💼 Career
Understanding how to join tables on primary and foreign keys is essential for database querying, data analysis, and backend development roles.
Progress0 / 4 steps
1
Create the authors table and insert data
Write SQL statements to create a table called authors with columns author_id as an integer primary key and author_name as text. Then insert these rows exactly: (1, 'Jane Austen'), (2, 'Mark Twain'), and (3, 'J.K. Rowling').
SQL
Hint
Use CREATE TABLE authors (author_id INTEGER PRIMARY KEY, author_name TEXT); to create the table. Use INSERT INTO authors (author_id, author_name) VALUES (...), (...), (...); to add the rows.
2
Create the books table and insert data
Write SQL statements to create a table called books with columns book_id as an integer primary key, title as text, and author_id as an integer foreign key referencing authors.author_id. Then insert these rows exactly: (101, 'Pride and Prejudice', 1), (102, 'Adventures of Huckleberry Finn', 2), and (103, 'Harry Potter and the Sorcerer''s Stone', 3).
SQL
Hint
Use CREATE TABLE books (book_id INTEGER PRIMARY KEY, title TEXT, author_id INTEGER, FOREIGN KEY (author_id) REFERENCES authors(author_id)); to create the table. Use INSERT INTO books (book_id, title, author_id) VALUES (...), (...), (...); to add the rows.
3
Write a SQL query to join books and authors
Write a SQL SELECT query that joins the books and authors tables on the author_id column. Select the title from books and the author_name from authors.
SQL
Hint
Use SELECT books.title, authors.author_name FROM books JOIN authors ON books.author_id = authors.author_id; to join the tables and select the columns.
4
Complete the project with a comment describing the join
Add a SQL comment above the SELECT query explaining that this query joins the books table to the authors table using the primary key author_id from authors and the foreign key author_id from books.
SQL
Hint
Add a comment line starting with -- before the SELECT query describing the join keys.
Practice
(1/5)
1. What is the main purpose of joining tables on a primary key to a foreign key in SQL?
easy
A. To create a new table with all columns from both tables without conditions
B. To delete duplicate rows from a table
C. To combine related data from two tables based on a unique identifier
D. To update values in one table using values from another unrelated table
Solution
Step 1: Understand primary and foreign keys
A primary key uniquely identifies each record in a table, and a foreign key points to that primary key in another table.
Step 2: Purpose of joining on these keys
Joining on primary key to foreign key connects related records from two tables, combining their data meaningfully.
Final Answer:
To combine related data from two tables based on a unique identifier -> Option C
Quick Check:
Join on primary to foreign key = combine related data [OK]
Hint: Primary key links uniquely; join combines related rows [OK]
Common Mistakes:
Thinking join deletes duplicates
Assuming join creates unrelated combinations
Confusing join with update or delete operations
2. Which of the following SQL JOIN statements correctly joins table Orders with Customers on the primary key CustomerID and foreign key CustomerID?
easy
A. SELECT * FROM Orders JOIN Customers ON Orders.OrderID = Customers.CustomerID;
B. SELECT * FROM Orders JOIN Customers ON Orders.OrderDate = Customers.CustomerID;
C. SELECT * FROM Orders JOIN Customers ON Orders.CustomerID = Customers.OrderID;
D. SELECT * FROM Orders JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Solution
Step 1: Identify correct keys for join
The primary key in Customers is CustomerID, and Orders has CustomerID as foreign key.
Step 2: Match keys in JOIN condition
The join must be ON Orders.CustomerID = Customers.CustomerID to link related records.
Final Answer:
SELECT * FROM Orders JOIN Customers ON Orders.CustomerID = Customers.CustomerID; -> Option D
Quick Check:
Join on matching CustomerID keys = SELECT * FROM Orders JOIN Customers ON Orders.CustomerID = Customers.CustomerID; [OK]
3. Given tables Employees (primary key EmployeeID) and Departments (foreign key ManagerID referencing EmployeeID), what will this query return?
SELECT Employees.Name, Departments.DepartmentName FROM Employees JOIN Departments ON Employees.EmployeeID = Departments.ManagerID;
medium
A. Syntax error due to wrong join condition
B. List of employee names who manage departments with their department names
C. List of departments without any employee names
D. List of all employees with all departments regardless of manager
Solution
Step 1: Understand join condition
The join matches Employees.EmployeeID to Departments.ManagerID, linking managers to their departments.
Step 2: Result of the join
The query returns names of employees who are managers and the names of the departments they manage.
Final Answer:
List of employee names who manage departments with their department names -> Option B
Quick Check:
Join on manager ID returns managers with departments [OK]
Hint: Join foreign key to primary key shows related records [OK]
Common Mistakes:
Thinking it returns all employees regardless of management
Assuming syntax error due to join condition
Expecting departments without managers
4. Consider these tables: Products(ProductID PK, Name) Sales(ProductID FK, Quantity) Why does this query cause an error?
SELECT * FROM Products JOIN Sales ON Products.ID = Sales.ProductID;
medium
A. Column Products.ID does not exist, causing an error
B. Foreign key cannot be used in JOIN condition
C. JOIN syntax is incorrect, missing JOIN type
D. Sales table must be listed first in FROM clause
Solution
Step 1: Check column names in JOIN condition
The Products table has ProductID as primary key, not ID.
Step 2: Identify cause of error
Using Products.ID causes an error because that column does not exist.
Final Answer:
Column Products.ID does not exist, causing an error -> Option A
Quick Check:
Wrong column name in JOIN = error [OK]
Hint: Verify column names exactly before joining [OK]
Common Mistakes:
Using wrong or misspelled column names
Thinking foreign keys can't be joined
Assuming JOIN type is mandatory
5. You have two tables: Authors(AuthorID PK, Name) Books(BookID PK, Title, AuthorID FK) Write a query to list each author with the count of books they wrote, including authors with zero books.
hard
A. SELECT Authors.Name, COUNT(Books.BookID) FROM Authors LEFT JOIN Books ON Authors.AuthorID = Books.AuthorID GROUP BY Authors.Name;
B. SELECT Authors.Name, COUNT(Books.BookID) FROM Authors JOIN Books ON Authors.AuthorID = Books.AuthorID GROUP BY Authors.Name;
C. SELECT Authors.Name, COUNT(*) FROM Books JOIN Authors ON Books.AuthorID = Authors.AuthorID GROUP BY Authors.Name;
D. SELECT Authors.Name, COUNT(Books.BookID) FROM Books LEFT JOIN Authors ON Books.AuthorID = Authors.AuthorID GROUP BY Authors.Name;
Solution
Step 1: Use LEFT JOIN to include all authors
LEFT JOIN keeps all authors even if they have no matching books.
Step 2: Count books per author
COUNT(Books.BookID) counts books; NULLs for authors without books count as zero.
Final Answer:
SELECT Authors.Name, COUNT(Books.BookID) FROM Authors LEFT JOIN Books ON Authors.AuthorID = Books.AuthorID GROUP BY Authors.Name; -> Option A
Quick Check:
LEFT JOIN + COUNT on foreign key = authors with book counts [OK]
Hint: Use LEFT JOIN to include all from primary key table [OK]