A foreign key must match a primary key or be null in order to maintain referential integrity. In other words, every column in a base table that is declared a foreign key can only contain null values, values from a parent table’s primary key, or values from a candidate key for referential integrity to hold in a relational database. This will help you maintain data quality and ensure that no data is lost.
This is a concept in data quality that makes sure that when you modify data in one area, it is updated in all associated entries.
Examples:
# 1 – Relying solely on the system to define the constraint name.
CREATE TABLE studentGroups(
GroupID BIGINT PRIMARY KEY,
Groups VARCHAR(20))
CREATE TABLE student_details(
stdID BIGINT PRIMARY KEY,
student_Name VARCHAR(40) NOT NULL,
GroupID BIGINT REFERENCES studentGroups(GroupID))
# 2 – Defining a name as per the naming convention.
CREATE TABLE studentGroups(
GroupID BIGINT PRIMARY KEY,
Groups VARCHAR(20))
CREATE TABLE student_details(
stdID BIGINT PRIMARY KEY,
student_Name VARCHAR(40) NOT NULL,
GroupID BIGINT,
CONSTRAINT fk_group FOREIGN KEY(GroupID) REFERENCES studentGroups(GroupID))
Hope you find this article helpful.