Working with Foreign Key Constraints
In this final step, we'll explore how foreign key constraints help maintain data integrity between related tables. Foreign key constraints ensure that relationships between tables remain valid by preventing operations that would create orphaned records.
Let's try to understand how foreign key constraints work through some examples:
First, let's try to add a book with an invalid author_id:
-- This will fail due to foreign key constraint
INSERT INTO books (title, author_id, publisher_id, publication_year, price)
VALUES ('Failed Book', 999, 1, 2023, 29.99);
You'll see an error message because author_id 999 doesn't exist in the authors table:
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`bookstore`.`books`, CONSTRAINT `books_ibfk_1` FOREIGN KEY (`author_id`) REFERENCES `authors` (`author_id`))```
Similarly, we can't delete an author who has published books without first dealing with their books:
```sql
-- This will fail due to foreign key constraint
DELETE FROM authors WHERE author_id = 1;
To safely delete an author and their books, we need to either:
- Delete the books first, then the author
- Use CASCADE DELETE (which we'll explore in advanced labs)
Let's see how to properly remove a book and its author:
-- First, delete the books by this author
DELETE FROM books WHERE author_id = 1;
-- Now we can safely delete the author
DELETE FROM authors WHERE author_id = 1;