Our Library is a web of cross-references. A book scroll does not repeat the author's whole biography - instead it points to the catalog number of the scroll describing the creator. In MySQL such a cross-reference is a foreign key.
The
autor_id column in the ksiazki table stores the id of an author from the autorzy table. A foreign key formalizes this relationship and makes the Library ensure that every autor_id points to an existing author.1ALTER TABLE ksiazki ADD FOREIGN KEY (autor_id) REFERENCES autorzy(id);We read it: "The autor_id column in ksiazki refers to the id column in autorzy".
Thanks to the foreign key the database will not allow you to:
autor_id does not exist in autorzy,This is referential integrity - a guarantee that the cross-references in the catalog never lead nowhere.
You can specify what happens to the books when their author disappears:
1ALTER TABLE ksiazki
2ADD FOREIGN KEY (autor_id) REFERENCES autorzy(id)
3ON DELETE CASCADE;autor_id to NULL (the book stays, but with no assigned author).The choice depends on how you want to keep order in the Library. Foreign keys are the guardians of consistency - without them the catalog would soon fill with dead cross-references.