foreign key | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

foreign key

What is the purpose of foreign key? Lets say that we have 2 tables author and book: https://code.sololearn.com/ca7a2A3a23a9 Why we need the foreign key in the book table? Wouldn't be easier if we replace the `author_id` foreign key with `author_name` and we don't need the author table anymore? Let say I want to add a new book to the database, first I need to check if the author is in the `author` table if it isn't I have to add it and then add the book.

6th Apr 2021, 8:01 PM
tibi
tibi - avatar
1 Answer
+ 1
If I got your question right, you are asking, why one should use foreign key. Table: user Name Email ... Table: post Text Date Author (=user) If you put table post Author = id, it works fine, but if you want to render the data later on, you would have to query two tables - or 100 tables - to get the data you want to render. (For example you. want to render: post.text and user.email) But if you put a foreignkey you just query one table (post) and then you can access the data like: post.text post.author.email (author = user as foreignkey) (That's what I think, to know about that :))
6th Apr 2021, 8:40 PM
Fu Foy
Fu Foy - avatar