Resources | Subject Notes | Information Communication Technology ICT
This section covers the fundamental concepts of primary and foreign keys in database design. Understanding these keys is crucial for creating well-structured and efficient databases.
A primary key is a column (or a set of columns) in a database table that uniquely identifies each record (row) in that table. It ensures that no two rows are exactly alike.
Key characteristics of a primary key:
Examples of primary keys:
A foreign key is a column (or set of columns) in one table that refers to the primary key of another table. It establishes a link between the two tables.
Key characteristics of a foreign key:
Example:
Consider a Orders
table and a Customers
table. The Orders
table might have a CustomerID
column. This CustomerID
would be a foreign key referencing the CustomerID
(primary key) in the Customers
table.
Let's illustrate with a simple example of a Customers
and Orders
database schema.
Table | Column | Data Type | Key Type | Description |
---|---|---|---|---|
Customers | CustomerID | INT | Primary Key | Unique identifier for each customer. |
Customers | FirstName | VARCHAR(50) | Customer's first name. | |
Customers | LastName | VARCHAR(50) | Customer's last name. | |
Orders | OrderID | INT | Primary Key | Unique identifier for each order. |
Orders | CustomerID | INT | Foreign Key referencing Customers.CustomerID | Links the order to the customer who placed it. |
Orders | OrderDate | DATE | Date the order was placed. |
Foreign keys are used to define relationships between tables. The type of relationship depends on the database design:
Referential integrity is a constraint that ensures the relationships between tables remain consistent. The DBMS enforces this by preventing actions that would violate the relationships, such as:
The specific behavior when referential integrity is violated can be configured within the database system (e.g., cascade delete, set null).
Primary and foreign keys are essential components of relational database design. They ensure data integrity, facilitate relationships between tables, and enable efficient data retrieval.