Primary and foreign keys are a way in which to constrain related data together to ensure data in your database remains consistent and to ensure no redundant data is in the database as a result of deleting a table or row in one table that affects data in other tables that may perhaps rely on that information. It can cause both data integrity problems as well as problems with your application that makes use of such database.
What’s a primary key used for?
A primary key is used to ensure data in the specific column is unique. You can only set constraints with primary keys, by setting a foreign key to another column which creates a relationship with the column that has the primary key set. A prime use of a primary key is in the case of a users table. The id column is likely to be a primary key because is needs to be unique. You may also set this column to auto increment; but the most important component is the primary key.
Why do I need to use a primary key?
Well, even though the column set as a foreign key may have duplicate data in multiple rows, it is still relying on the unique information in the primary key. If there was non-unique rows in the primary key column, there would not be a use for a foreign key because you would be mapping one row in the foreign key to two rows in the primary key. In essence, primary to foreign keys ensure that:
- the data that can be inserted in the table that has the foreign key can only be information thatuniquely exists in the primary key column.
- if a DELETE or UPDATE occurs, the action you specified will be undertaken to ensure data integrity and prevent data redundancy in your database. Two primary actions are CASCADE and RESTRICT. CASCADE means any affected data will be deleted as well (hence, cascading), in the case of an UPDATE execution; in order to keep data consistent and prevent data redundancy.
What’s a foreign key used for?
How do you actually ensure that data stays integral, consistent and updated? You make use of foreign keys. A primary key ensures that data is unique in one column, but the foreign key is what makes the data stay consistent, as that is where the important data lies that needs to stay consistent and integral. It’s inevitable that in most database-driven applications you create, you’ll need to have multiple tables that are for different areas of your application that makes a reference to an id or some unique data in another table. For example, a profile comments table – your application needs to understand what user id the profile comment is for. You can make use of a foreign key here that maps to the primary key that, as well as keeping data consistent, it also means that you can set the foreign key to CASCADE and any DELETE and UPDATE actions will be cascaded down to any affected row (such as the foreign key).