Keys

Some fields in tables are particularly important because they are used to define an individual record. Consider a table housing social security numbers - there should not be any duplicate numbers in there; each key is in there once and once only. In database terms we call this a primary key - you can select out one individual record from thousands by knowing its primary key.

A primary key when used as a field in another table other than its original table, is known as a foreign key. For example, in a WWW messageboard, each message must have the ID number of the person who posted a message (almost certainly the primary key in a members table), as well as the ID number of the messageboard it was posted on (almost certainly the primary key in a messageboards table). In this situation, both member ID and messageboard ID are primary keys in their own tables, but foreign keys in the messages table, because the messages primary key is the unique number of each message.

With foreign keys comes referential integrity, which is where you can delete a record from a table, and any table which references it with a foreign key will also be updated. Primary keys are usually, but not always, unique - that is, you cannot have two values the same in a primary key column.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Referential integrity >>

Previous chapter: Views

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.