Get started with Secoda
See why hundreds of industry leaders trust Secoda to unlock their data's full potential.
See why hundreds of industry leaders trust Secoda to unlock their data's full potential.
In relational database design, understanding the roles of primary keys and foreign keys is essential for maintaining data integrity and establishing relationships between tables. These keys serve distinct but complementary functions, each playing a crucial role in organizing and linking data within a database. While a primary key uniquely identifies each record within a table, a foreign key connects records across different tables, ensuring that related data is consistently and accurately represented. Together, they form the backbone of relational databases, enabling efficient data management and retrieval.
Here are some SQL examples that highlight the differences between a primary key and a foreign key:
Example 1: Defining a Primary Key
In this example, the `EmployeeID` column in the `Employees` table is set as the primary key. This ensures that each employee has a unique identifier.
Example 2: Defining a Foreign Key
In this example, the `Orders` table includes a `CustomerID` column, which is set as a foreign key. This foreign key references the `CustomerID` primary key in the `Customers` table, linking each order to a specific customer.
Example 3: Inserting Data with Primary and Foreign Keys
This example shows how primary and foreign keys work together when inserting data. The `CustomerID` in the `Orders` table must match an existing `CustomerID` in the `Customers` table.
Example 4: Foreign Key Constraints
If you try to insert an order with a `CustomerID` that does not exist in the `Customers` table, the database will prevent it, enforcing referential integrity.
Example 5: Cascading Deletes with Foreign Keys
You can set a foreign key to cascade deletes, meaning that if a record in the primary key table is deleted, the related records in the foreign key table are automatically deleted.
In this setup, if you delete a customer from the `Customers` table, all orders associated with that customer will also be deleted automatically.
These examples illustrate how primary keys uniquely identify records within a table, while foreign keys create relationships between tables, enforcing consistency and referential integrity in the database.
In summary, a primary key uniquely identifies records within its own table, while a foreign key establishes a link between two tables, referencing the primary key of another table.