Resources | Subject Notes | Computer Science | Lesson Plan
A database is an organized collection of data. To efficiently manage and retrieve data, databases use tables. Each table consists of rows (records) and columns (fields). A crucial concept in database design is the primary key.
A primary key is a field (or a set of fields) in a table that uniquely identifies each record in that table. It's the most important field for identifying individual entries. A primary key must satisfy the following conditions:
Primary keys are essential for:
When designing a database, it's important to choose appropriate primary keys. Here's a guide to help you identify suitable primary keys:
Let's look at some examples to illustrate how to identify primary keys:
Consider a table to store information about students:
Field Name | Data Type | Primary Key? |
---|---|---|
Student ID | Integer | Yes - Natural Key (assumed to be unique) |
First Name | Text | No |
Last Name | Text | No |
Date of Birth | Date | No |
Email Address | Text | Potentially - if guaranteed unique |
In this case, Student ID is the most suitable primary key because it's likely to be unique for each student and is not null.
Consider a table to store information about products:
Field Name | Data Type | Primary Key? |
---|---|---|
Product Code | Text | Yes - Natural Key (assumed to be unique) |
Product Name | Text | No |
Price | Decimal | No |
Stock Quantity | Integer | No |
Here, Product Code is the best primary key as it's designed to be unique for each product.
Consider a table to store information about orders:
Field Name | Data Type | Primary Key? |
---|---|---|
Order ID | Integer | Yes - Artificial Key (automatically generated) |
Customer ID | Integer | No - Foreign Key (links to Customer Table) |
Order Date | Date | No |
Total Amount | Decimal | No |
In this example, Order ID is the primary key. It's an artificial key, designed specifically to uniquely identify each order.
Sometimes, a single field is not sufficient to uniquely identify a record. In such cases, a composite key is used. A composite key consists of two or more fields that, when combined, uniquely identify a record.
For example, in a table of student enrollments, a composite key might be (Student ID, Course ID) to ensure that a student is only enrolled in a particular course once.
A foreign key is a field in one table that refers to the primary key of another table. Foreign keys are used to establish relationships between tables. They help maintain data integrity by ensuring that relationships between tables are valid.
For instance, the Customer ID field in the Orders table would be a foreign key referencing the Customer ID (primary key) in the Customers table.