foreign key as nullable. why is it required? - sql

My understanding of foreign key relationships in tables is that a foreign key is a column in a child table and is a primary key in the parent table.we know that primary keys are unique and not null.I have some doubts and require clarification.
Is it necessary that when a parent table has data the child should also has to have related data?
can child table have nulls(foreign key nulls).
why is there a provision for foreign keys to be null.
I have not been able to get proper understanding of all of this.
help me in making me understand these concepts better.
thanks in advance.

why is there a provision for foreign keys to be null.
Optional participation conditions. When a child either has a single parent or non, this is one way to model this relationship between the tables.
If the value is null, then the child has no parent.
If the value is not null, then the child has a parent and the value must be an existing parent ID.
If you have such a relationship and do not allow null in the foreign key column, then you can't have a child without a parent.
You could model this with a many-to-many table, which, without any constraints would mean that participation is optional, but to ensure a one-to-one relationship you would need to make each foreign key column unique (as well as NOT NULL). I personally find this option to be overkill (and it can be changed if requirements change).
The choice between the two is one of practicality (how likely is the model to change from a one-to-one to a one-to-many or many-to-many?, for example), though relational purists would go for the many-to-many option.

A nullable foreign key in essence means the relationship is optional.
Assuming that the FK constraint is being checked, then if the Foreign Key is not null, its value must exist in the referenced table.
However, if the value of the foreign key is null, it means that the relationship doesn't exist. Typically, you would LEFT/RIGHT OUTER JOIN in this case to prevent nulls from being filtered out in the JOIN.
Optional relationships are useful when a relationship which is state-dependent.
E.g. A Customer will only be assigned to a Branch IF the customer is approved as a client, until then, the customer's BranchId will be NULL, etc.

Related

Clarification on foreign keys, SQL

If I make it so that one of the attributes in my relation A references a foreign key of another relation B, is the attribute in A required to be the primary key for A (or part of the primary key for A)?
Also, my understanding is that in order to reference an attribute, the referenced attribute must be a key or unique. Am I then right is asserting that we couldn't reference part of a primary key (i.e if the primary key had two attributes we would need to reference both of them or neither, since by itself neither attribute is guaranteed to be unique)?
A foreign key must reference a unique key of some sorts, whether it's a primary key or not. You cannot reference just part of a composite unique key, unless it's a unique key on its own right.
The referencing field(s) can be a unique key (making the relation a 1:0..1 relation, but needn't necessarily be one.
Yes you are right in your understanding. Lets say you were storing information about dogs being washed at a doggy parlor, and you had two tables (tbl_dog, tbl_DogsWashed).
tbl_Dog has the columns (DogId,DogsName,Breed,OwnersIdentityNumber)
tbl_DogsWashed has the columns (DogsWashedId,DogsName)
If you linked the two tables together using the dogs name, you would risk the fact that two different dogs with the same name have had washes.
Rather, tbl_Dog would have the columns (DogsWashedId,DogId) and you would look up the DogId using the DogsName,Breed,OwnersIdentityNumber etc and populate the tbl_DogsWashed table with a primary key from tbl_Dog.

obtaining foreign key from DEPENDENT possibility in create table SQL

Lets say you have two entity named Parent and Child.
Child entity is DEPENDENT of Parent entity.
A weak key of child entity is the NAMEOFCHILD.
Is it possible for the Parent entity to have NAMEOFCHILD as a foreign key?
This idea has not been talked about in class. I was wondering is this possible in SQL?
If so, should i just add
FOREIGN KEY (NAMEOFCHILD) source CHILD
in my table?
In the database schema, yes (if Child.NAMEOFCHILD has a unique index). In entity framework, no. EF doesn't support associations to unique indexes (yet). But this is just on the technical level. Whether it's meaningful is another question.
Also, beware of painting yourself in a corner. When both foreign keys are not nullable you'd never be able to insert data, because you can't insert two records at a time and sequential inserts always cause foreign key violations. You would be able to design the database schema but never get any data in.

SQL Foreign Key, is my example an appropriate use?

Can someone please confirm if this is an appropriate use of a foreign key(this is just an example):
Application to book a meeting room;
tblBooking -> pkName,Time,fkRoomName;
tblRoom -> pkRoomName, RoomNumber;
The UI will populate a dropdown menu using the pkRoomName data, when the booking is made the selected pkRoomName will then go to tblBooking fkRoomName.
Have I understood this correctly?
Yes, if you want to ensure that any booking that specifies a room refers to a known room, then this is an appropriate use of a foreign key.
Note, however, that just declaring the foreign key relationship is not the same thing as requiring that all bookings specify a room. Records in tblBooking with a NULL value for fkRoomName will be permitted. If you want to require a room is specified, you must also use the NOT NULL constraint on the fkRoomName field.
Finally, a small matter of semantics. I would not use "fk" in the column name for the RoomName. This is because a foreign key is a different entity from the columns it includes. It is not uncommon to have foreign keys that include multiple columns and it is also not uncommon to have several different foreign key relationships out of a single table. Therefore fkRoomName is an appropriate name for the foreign key itself, but not so much for the column.

Why is the foreign key part of the primary key in an identifying relationship?

I'm trying to understand a concept rather than fixing a piece of code that won't work.
I'll take a general example of a form (parent table) and a form field (child table). Logically, this would be an identifying relationship, since a form field cannot exist without a form.
This would make me think that in order to translate the logical relationship into the technical relationship, a simple NOT NULL for the form_id field in the form_field table would suffice. (See the left part of above screenshot.)
However, when I add an identifying relationship using MySQL Workbench, form_id is not only NOT NULL but also part of the primary key. (See the right part of above screenshot.) And when I add a non-identifying relationship, NOT NULL is still applied so logically it would actually be an identifying relationship as well.
I guess this confuses me a little, as well as the fact that until now I always simply used the id field as primary key.
So I understand the logical concept of identifying vs. non-identifying relationships, but I don't understand the technical part.
Why is it, as this answer states, 'the "right" way to make the foreign key part of the child's primary key'?
What is the benefit of these composite primary keys?
Logically, this would be an identifying relationship, since a form field cannot exist without a form.
No, identifying relationship is about identification, not existence.
Any X:Y relationship where X >= 1 guarantees existence of the left side, whether identifying or not. In your case, a 1:N relationship guarantees existence of form for any given form_field. You could make it identifying or non-identifying and it would still guarantee the same.
Remarks:
You would model an identifying relationship by making form_field.form_id part of a key. For example form_field PK could look like: {form_id, label}, which BTW would be quite beneficial for proper clustering of your data (InnoDB tables are always clustered).
Just making a PK: {id, form_id} would be incorrect, since this superkey is not a candidate key (i.e. it is not minimal - we could remove form_id from it and still retain the uniqueness).
You would model a 0..1:N relationship by making the form_field.form_id NULL-able (but then you wouldn't be able to make it identifying as well - see below).
There are two definitions of the "identifying relationship":
Strict definition: A relationship that migrates parent key into child primary key1.
Loose definition: A relationship that migrates parent key into child key.
In other words, the loose definition allows migration into alternate key as well (and not just primary).
Most tools2 seem to use the strict definition though, so if you mark the relationship as identifying, that will automatically make the migrated attributes part of the child PK, and none of the PK attributes can be NULL.
1 Which is then either completely comprised from migrated attributes, or is a combination of migrated attributes and some additional attributes.
2 ERwin and Visio do. I haven't used MySQL Workbench for modeling yet, but your description seems to suggest it behaves the same.
An identifying relationship is supposed to be one where the primary key includes foreign key attributes. That's why when you designate a relationship as identifying the posted foreign key is deemed to be part of the primary key.
The difference between an "identifying" relationship and a non-identifying one is purely informational or diagrammatic if the same key constraints and nullability constraints apply in each case. The concept is analogous to and a consequence of designating a "primary" key. If a table has more than one candidate key then all other things being equal it doesn't matter from a logical perspective which key is designated the primary one - the form, function and (presumably) the business meaning of the table is the same.
In your example however, the keys in the two tables are NOT the same. In the first case ID is unique in the form_field table while in the second case it apparently isn't. I expect that's not what you intended.

Should I use a Foreign Key to Show Tree Relationship in SQL

I am trying to model a tree relationship in a table. For instance, there are "Categories" and categories can themselves be inside a Parent category.
My schema is:
id int PRIMARY KEY,
parent_id int,
name
My question is, should I label the parent_id column as a Foreign key? Foreign implies "outside" and not self-referencing. Is there a different type of key for this purpose?
My question is similar to:
Self-referencing constraint in MS SQL, but I'm asking a different question, cascading not being an issue.
Self-referencing foreign keys happen all the time. E.g. an employee might have another "employee" as his manager, so the manager_id will be a foreign key to the employee_id field in the same table.
Foreign keys are the natural candidate for representing the parent node in hierarchical data, although they're not exclusively used for that :)
If you have very deep levels of nesting it may not be easy to performantly select out all descendants of a particular node, since most DB's do not handle recursion very well. Another approach is to use what's called the "Nested Set Model" to represent the relationships. A great article is available here:
http://www.intelligententerprise.com/001020/celko.jhtml
A foreign key between two columns in the same table is often used when mapping tree structures to relational databases. However, it is not the only approach avaiable.
See this article for alternative reperesentations: Storing Hierarchical Data in a Database
I don't believe there is another type of key... a foreign key would be fine in this scenario.. it would enforce the constraint against the parent_id to ensure it references a valid id