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 authors: (1, 'Jane Austen'), (2, 'Mark Twain'), (3, 'J.K. Rowling').
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