Difference and use between Primary Key and Foreign Key

Asked

Viewed 1,898 times

1

I did a database modeling relating some tables and at the end of everything I was told that I was wrong for not having PK and FK keys. The question is, how do I differentiate a Primary Key from a Foreign Key? What are the two for?

1 answer

6


To primary key is the data you need to control the access to the tables' rows. It must be unique and therefore it cannot have null value (theoretically it could have a null key, but it doesn’t make much sense). It gives the identity to the line, it is through it that you can trust that it will always be used for direct access to the desired line. It is common for a sequential numeric identifier to be used for this. See more in Surrogate Key and Natural Key.

To foreign key is used for relationships with another table. In most cases it will be the primary key of another table. So it can be null (no relationship) or duplicate (more than one item in a table relates to the same item in another table).

In general modeling depends on experience. And experience depends on having learning ability. Experience in no way is the time one does that or how many times one has done it. That would be quantitative experience, which has no value, the experience that counts is qualitative, the one you do once, someone or the consequences show you with the time you were wrong and should do better. More and more we see people choosing, for their whole life, only to follow what others do, to see superficially how it is done, then one never becomes experienced. Even to gain experience it is necessary to acquire experience. You have to break the vicious circle to begin to evolve.

The primary key with this basic knowledge (including the link above) you can already understand the need for it and in most cases the choice is simple and obvious, it is a sequential numerical substitute key.

The foreigner is more complicated, not always that she is a beginner sees clearly what she needs to relate one data to another, but it is also not so difficult. Think of it as a word you need to know to search in a dictionary. The other related table is your dictionary for that case.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.