obtaining foreign key from DEPENDENT possibility in create table SQL - 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.

Related

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.

foreign key as nullable. why is it required?

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.

Database how to model 1:1 relationship

(VS2008, SqlCE 3.5)
I try to model a 1:1 relationship. So I put the foreign key in the parent table, holding the PK of the child table. Then I set the foreign key to UNIQUE. Still when I create my entity classes (With SqlMetal), the child class has a reference to an EntitySet of the parent, not just a single entity. This seems like a m:1 relation? So what I need to do to make it 1:1 ?
EDIT1:
I'm confused.. Trying to make a set, like this:
StrategySet(ID, EntryStrategyID{Unique}, ExitStrategyID{Unique})
EntryStrategy(ID)
ExitStrategy(ID)
Is this m:1 isn't it? Though it looks like FK's are in the parent, or wouldn't we name StrategySet the parent? And how would I now change this too 1:1 ?
First of all, the parent is table which is referenced by FK from child. So you can't say that your parent table references the child: it's not correct.
Secondly, 1:1 relations can be made through:
Primary Keys in both tables
Primary Key in parent and Unique Foreign Key in child
So in your case, the architecture is correct. I suppose you should check the structure again, and look through this article.
If all columns in EntryStrategy and ExitStrategy are the same, then all you need is simply this (add all other columns too).
If EntryStrategy and ExitStrategy have some different columns, then use this. Keep all common columns in the Strategy table. EntryStrategy and ExitStrategy have only columns specific to each one.
Here is also a generic example of 1:1 due to vertical partitioning of a table.
Before:
After:
Let me understand the situation you are describing.
You have set of fields which make up a "Strategy". A subset of the fields are conceptually the "EntryStrategy" and a non-intersecting subset of the fields are the "ExitStrategy".
In your case a given set of values making up an "EntryStrategy" can be joined with one and only one set of values making up an "ExitStrategy". This is what you mean when you say there is a 1:1 correspondence.
As smirkingman said earlier, in classic relational database modeling, all of these fields belong in a single table because no subset of the fields appear in more than one record.
If you could have multiple ExitStrategies for a single EntryStrategy then you would have two tables with the EntryStrategy being the parent and the ExitStrategies being the children and the ExitStrategy records would have a Foreign Key pointing to the EntryStrategy parent record.
If you could have multiple EntryStrategies for a single ExitStrategy then you would have two tables with the ExitStrategy being the parent and the EntryStrategies being the children and the EntryStrategy records would have a Foreign Key pointing to the ExitStrategy parent record.
If you could have multiple EntryStrategies associated with multiple ExitStrategies then you would have a many-to-many relationship which requires a third table to maintain the correspondences.
The principles of classic database modeling would put all your fields in one table.
As St Woland wrote, you can enforce the 1:1 relationship by having two tables where the foreign key in the child table is a Unique index. But two tables are normally used for 1-to-many relationships.
As Damir wrote, you can enforce the 1:1 relationship by having three tables where the third table has a foreign key to each of the other two tables and both foreign key fields are marked as Unique indices. However, normally you only use three tables in this fashion when you have a many-to-many relationship.
I think you are expecting way too much from the automated data modeling tools to expect them to construct entities that represent your very unconventional approach.
The answer to your main question is simple. How do I represent a 1:1 relationship? You put them in the same record in a single table!

How do I rename primary key values in Oracle?

Our application uses an Oracle 10g database where several primary keys are exposed to the end user. Productcodes and such. Unfortunately it's to late to do anything with this, as there are tons of reports and custom scripts out there that we do not have control over. We can't redefine the primary keys or mess up the database structure.
Now some customer want to change some of the primary key values. What they initially wanted to call P23A1 should now be called CAT23MOD1 (not a real example, but you get my meaning.)
Is there an easy way to do this? I would prefer a script of some sort, that could be parametrized to fit other tables and keys, but external tools would be acceptable if no other way exists.
The problem is presumably with the foreign keys that reference the PK. You must define the foreign keys as "deferrable initially immediate", as described in this Tom Kyte article: http://www.oracle.com/technology/oramag/oracle/03-nov/o63asktom.html
That lets you ...
Defer the constraints
Modify the parent value
Modify the child values
Commit the change
Simple.
Oops. A little googling makes it appear that, inexplicably, Oracle does not implement ON UPDATE CASCADE, only ON DELETE CASCADE. To find workarounds google ORACLE ON UPDATE CASCADE. Here's a link on Creating A Cascade Update Set of Tables in Oracle.
Original answer:
If I understand correctly, you want to change the values of data in primary key columns, not the actual constraint names of the keys themselves.
If this is true it can most easily be accomplished redefining ALL the foreign keys that reference the affected primary key constraint as ON UPDATE CASCADE. This means that when you make a change to the primary key value, the engine will automatically update all related values in foreign key tables.
Be aware that if this results in a lot of changes it could be prohibitively expensive in a production system.
If you have to do this on a live system with no DDL changes to the tables involved, then I think your only option is to (for each value of the PK that needs to be changed):
Insert into the parent table a copy of the row with the PK value replaced
For each child table, update the FK value to the new PK value
Delete the parent table row with the old PK value
If you have a list of parent tables and the PK values to be renamed, it shouldn't be too hard to write a procedure that does this - the information in USER_CONSTRAINTS can be used to get the FK-related tables for a given parent table.

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