Practical 4 - Foreign Key
Practical 4 - Foreign Key
Before we define what FK is, we’ll once more remind ourselves of what is the
primary key:
In our model, both tables, country, and city have 1 attribute which is used
as a primary key and that is the id attribute. The value of this attribute is
defined to start from 1 and increment by 1 for each new row added. That
way, the system automatically ensures that we don’t have duplicate values.
The one thing which is pretty obvious is that we have a line connecting our
tables. This line goes from country.id to city.country_id and there is a
good reason for that. This is how we graphically represent a FK.
Enforce for replication – possible values here are “Yes” and “No” –
Enables or disables it for replication. Please read more about the
replication in SQL Server Replication (Merge) – What gets replicated
and what doesn’t article
Enforce Foreign Key Constraint – possible values are “Yes” and
“No”. If it’s enabled, the FK constraint works as we want it. We could
disable it if we want, but we should have a good reason for that. One
could be that we want to manually change keys values and we
wouldn’t be able to do that because constraints would “scream” all the
time
Delete Rule – possible values are “No Action”, “Cascade”, “Set NULL”,
and “Set Default” – defines what will happen with child table rows if we
delete the related row from the referenced table
Update Rule – possible values are “No Action”, “Cascade”, “Set
NULL”, and “Set Default” – defines what will happen with child table
rows if we update the related row in the referenced table
Now we’ll examine the code to see how the FK was defined. Let’s right-click
on the table dbo.city and then Script Table as | CREATE to | New Query
Editor Window just as on the picture below:
The result is the following code:
USE [our_first_database]
GO
SET QUOTED_IDENTIFIER ON
GO
You can see FK definitions in the red lines, with the first statement defining
which attributes are included in the check and the second statement telling
us this is related to the definition of the city table.
If you add a row to a table, the attribute which is part of the foreign
key must have the pair in the original table (1:n). It can be NULL if
the type of that relation (FK) is not mandatory (0:n). In any case, it
can’t contain a value not existing in the referenced table
In our case, this means, that we can’t add a city if the country_id is
not in the range [1,5] – set of id values from the country table. If we
try to execute something like this (notice that in this
statement country_id = 6 and we don’t have a pair in
the country table):
The FK, when defined properly, instead of you, does the job in the
background. It takes care of the referential integrity in our database.