In relational database design, ensuring data integrity and enabling efficient data retrieval are paramount. Primary keys and foreign keys are two critical concepts that help achieve these objectives by defining relationships between tables and ensuring uniqueness and consistency across the database.
A primary key is a column or a group of columns used to uniquely identify each row in a table. No two rows in a table can have the same primary key value, and a primary key column cannot contain NULL values. This uniqueness and non-nullability ensure that every record can be uniquely and reliably identified.
Characteristics of Primary Keys:
Example of a Primary Key: Consider a table named Customers
that stores information about customers. A suitable primary key would be CustomerID
because it uniquely identifies each customer.
CREATE TABLE Customers (
CustomerID int NOT NULL,
FirstName varchar(255),
LastName varchar(255),
Email varchar(255),
PRIMARY KEY (CustomerID)
);
A foreign key is a column or group of columns in one table that uniquely identifies a row of another table or the same table. Essentially, a foreign key is used to link two tables together. It is a field (or fields) in one table that references the primary key of another table. The table containing the foreign key is called the child table, and the table containing the candidate key is called the referenced or parent table.
Characteristics of Foreign Keys:
CASCADE
: Automatically delete or update the rows in the child table when the referenced row in the parent table is deleted or updated.SET NULL
: Set the value of the foreign key to NULL if the row in the parent table is deleted or updated.NO ACTION
: Do nothing; however, the action will fail if it violates the foreign key constraint.Example of a Foreign Key: Assuming we have the Customers
table as defined above, and another table called Orders
:
CREATE TABLE Orders (
OrderID int NOT NULL,
OrderDate date NOT NULL,
CustomerID int,
Amount decimal(10, 2),
PRIMARY KEY (OrderID),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
In this example, CustomerID
in the Orders
table is a foreign key that references the CustomerID
in the Customers
table. This setup enforces that orders can only be placed by valid customers existing in the Customers
table.