Primary and foreign keys help create structure in relational databases.
A primary key ensures unique row identification. This results in faster sorting, searching, and querying operations.
A foreign key creates a link between two tables. It maintains referential integrity between the referencing column and the referenced column.
What Is a Primary Key?
A primary key is a column or a set of columns that uniquely identifies each row in a table. It must obey the UNIQUE and NOT NULL database constraints.
Let’s look at the STUDENT table, which information about the Students.
STUDENT
Student ID | Student Name |
---|---|
1 | Kruti |
2 | Katelyn |
3 | Kat |
The Student ID column is the primary key of the Student table. The column uniquely identifies each row in the Student table; it stores unique values and does not store NULL values.
What Is a Foreign Key?
A foreign key is a column or a set of columns linking one table to another. The column or columns appear in both tables, creating a link between the tables.
Let’s use our Grades table together with the Student table, which stores details about each product.
GRADES - STUDENT
Student ID PK | int | Student ID FK PK | int |
---|---|---|---|
Grade Name | varchar(5) | Student Name | varchar(20) |
The Student ID column is the primary key of the Grades table. It is also the primary and foreign key in the Grades table. The Grades and Student tables are linked via the Student ID column in a one-to-one relationship; each product in the Grades table must have exactly one entry in the Grades table.
Commentaires