I'm trying to understand something about the foreign key of a database.
I couldn't find a clear answer for this.
The definition of a foreign key goes something like this,
"Foreign key is a field or a group of fields in a table that refers to the primary key of another table"
OK I get that.
Then we learn about types of relationships we can have among tables using foreign keys.
In one-to-many(1:M) and many-to-many(M:N) relationships, there are duplicates in the foreign key.
But how can this be?
If a foreign key refers to a primary key and a primary key can't have duplicates, how can a foreign key can?
I'm confused.
Can someone please explain this to me?
Note - I'm expecting a common answer, not a DBMS specific one.
For example:
There is an employee table with a primary key column called EmployeeID. There is also a foreign key called SupervisorID, which references a different row in the same table.
Two employees work for the same supervisor. They will have different values in the EmployeeID field, but the same value in the SupervisorID field.
This example uses a reference back to the same table, but the concept is the same when the foreign key references a different table.
Related
What is the difference between Primary and Unique key (in MySQL)? How these can be considered as a foreign key? please explain.
I tried creating a database table and don't know how to make a primary key as a foreign key. Does it take Joins concept where the separating attribute automatically create a foreign key?
A table in MySQL can only have one Primary Key at most, while you can create as many unique Keys or indexes as you want.
Also a primary key is not nullable while a unique key can have NULL as value.
But the biggest difference is the purpose:
You want to have a primary key because you need an identifier
The unique Key/Index on the other hand is usefull to controll values that are automatically getting inserted into your table (e.g. to avoid duplicates where none are allowed)
If you want to use a column as a forgein key, you need to define it as a primary key first. Unique Constraint can not be related with other tables as a foreign key.
I am having two conflicting definitions of foreign key.
From Wikipedia
the foreign key is defined in a second table, but it refers to the primary key in the first table.
From my lecture notes:
Foreign key does not have to match a primary key but must match a candidate key in some relation
Which is which? Does a foreign key need to reference a primary key or candidate key?
In the relational model of data, a foreign key must reference a candidate key.
In almost all SQL dbms, a foreign key must reference a candidate key.
In MySQL, a foreign key can reference just about anything.
Additionally, MySQL requires that the referenced columns be indexed for performance reasons. However, the system does not enforce a requirement that the referenced columns be UNIQUE or be declared NOT NULL.
Emphasis added.
This is a Bad Thing, IMHO.
The rule that a FK must reference a "primary" key was imposed by the older versions of the SQL standard. That rule has been relaxed by now (and it is now permitted for a FK to reference any candidate key), but it may be the case that some products still go by the old rule, just as it may be the case that some textbooks or other sources have not yet been updated to reflect the new state of affairs.
I don't know precisely when the rule was relaxed in the standard, but imo it must certainly have been no later than 2003.
A foreign key must refer to an unique key (a primary key is unique), because if it doesn't, it cans be the reference of 2 lines, and it's just impossible for a foreign key. Then you can have your primary key, but an unique key who is not a primary key and do a foreign key on it. And your unique key must be NOT NULL
Foreign keys have to be linked to candidate keys because, if join between tables was made using foreign key, the FK linked to an attribute that was not a candidate key could result in multiple values being retrieved where only one value should be retrieved.
Practically, the foreign key has nothing to do with the primary key tag of another table, if it points to a unique column (not necessarily a primary key) of another table then too, it would be a foreign key. So, a correct definition of the foreign key would be:
Foreign keys are the columns of a table that points to the candidate key of another table.
I am currently creating a database using SQL but I have found the need to use a foreign key to in 3 different fields in a single table.
I have CourseID1, CourseID2 and CourseID3 in students courses table. Each of those 3 fields need to be foreign and reference to the CourseID field in the course table which is a primary key.
Is this possible? how do I go about doing this?
Thank you
This is possible. You would do:
foreign key (CourseId1) references Courses(CourseId),
foreign key (CourseId2) references Courses(CourseId),
foreign key (CourseId3) references Courses(CourseId),
That said, you don't want to do this. Having multiple columns with numeric appendages usually means that you want an association/junction table. In this case, you want a table named something like StudentCourses which would have one row per student and per course that the student takes.
I have two tables:
User (username, password)
Profile (profileId, gender, dateofbirth, ...)
Currently I'm using this approach: each Profile record has a field named "userId" as foreign key which links to the User table. When a user registers, his Profile record is automatically created.
I'm confused with my friend suggestion: to have the "userId" field as the foreign and primary key and delete the "profileId" field. Which approach is better?
Foreign keys are almost always "Allow Duplicates," which would make them unsuitable as Primary Keys.
Instead, find a field that uniquely identifies each record in the table, or add a new field (either an auto-incrementing integer or a GUID) to act as the primary key.
The only exception to this are tables with a one-to-one relationship, where the foreign key and primary key of the linked table are one and the same.
Primary keys always need to be unique, foreign keys need to allow non-unique values if the table is a one-to-many relationship. It is perfectly fine to use a foreign key as the primary key if the table is connected by a one-to-one relationship, not a one-to-many relationship. If you want the same user record to have the possibility of having more than 1 related profile record, go with a separate primary key, otherwise stick with what you have.
Yes, it is legal to have a primary key being a foreign key. This is a rare construct, but it applies for:
a 1:1 relation. The two tables cannot be merged in one because of different permissions and privileges only apply at table level (as of 2017, such a database would be odd).
a 1:0..1 relation. Profile may or may not exist, depending on the user type.
performance is an issue, and the design acts as a partition: the profile table is rarely accessed, hosted on a separate disk or has a different sharding policy as compared to the users table. Would not make sense if the underlining storage is columnar.
Yes, a foreign key can be a primary key in the case of one to one relationship between those tables
I would not do that. I would keep the profileID as primary key of the table Profile
A foreign key is just a referential constraint between two tables
One could argue that a primary key is necessary as the target of any foreign keys which refer to it from other tables. A foreign key is a set of one or more columns in any table (not necessarily a candidate key, let alone the primary key, of that table) which may hold the value(s) found in the primary key column(s) of some other table. So we must have a primary key to match the foreign key.
Or must we? The only purpose of the primary key in the primary key/foreign key pair is to provide an unambiguous join - to maintain referential integrity with respect to the "foreign" table which holds the referenced primary key. This insures that the value to which the foreign key refers will always be valid (or null, if allowed).
http://www.aisintl.com/case/primary_and_foreign_key.html
It is generally considered bad practise to have a one to one relationship. This is because you could just have the data represented in one table and achieve the same result.
However, there are instances where you may not be able to make these changes to the table you are referencing. In this instance there is no problem using the Foreign key as the primary key. It might help to have a composite key consisting of an auto incrementing unique primary key and the foreign key.
I am currently working on a system where users can log in and generate a registration code to use with an app. For reasons I won't go into I am unable to simply add the columns required to the users table. So I am going down a one to one route with the codes table.
It depends on the business and system.
If your userId is unique and will be unique all the time, you can use userId as your primary key. But if you ever want to expand your system, it will make things difficult. I advise you to add a foreign key in table user to make a relationship with table profile instead of adding a foreign key in table profile.
Short answer: DEPENDS.... In this particular case, it might be fine. However, experts will recommend against it just about every time; including your case.
Why?
Keys are seldomly unique in tables when they are foreign (originated in another table) to the table in question. For example, an item ID might be unique in an ITEMS table, but not in an ORDERS table, since the same type of item will most likely exist in another order. Likewise, order IDs might be unique (might) in the ORDERS table, but not in some other table like ORDER_DETAILS where an order with multiple line items can exist and to query against a particular item in a particular order, you need the concatenation of two FK (order_id and item_id) as the PK for this table.
I am not DB expert, but if you can justify logically to have an auto-generated value as your PK, I would do that. If this is not practical, then a concatenation of two (or maybe more) FK could serve as your PK. BUT, I cannot think of any case where a single FK value can be justified as the PK.
It is not totally applied for the question's case, but since I ended up on this question serching for other info and by reading some comments, I can say it is possible to only have a FK in a table and get unique values.
You can use a column that have classes, which can only be assigned 1 time, it works almost like and ID, however it could be done in the case you want to use a unique categorical value that distinguish each record.
should I signal the foreign key in a database column name?
FKOrder vs. FK_Order vs. Order
The short answer is no - don't put "FK" in column names of foreign key columns. You can still signal the intent of the column though, here's how I do it:
Naming foreign key columns
It depends on your naming convention for the target of the FK. If you have Id, then I'd prepend the table name when creating FK columns.
Example 1:
For table User with PK Id and table Workitem with user ID FK, I'd call the column Workitem.UserId.
If there were more than one FK between the same tables, I'd make this clear in the column name:
Example 2:
For table User with PK Id and table Workitem with "assigned to user ID" and "created by user ID" FKs, I'd call the columns Workitem.CreatedByUserId and Workitem.AssignedToUserId.
If your naming convention for PKs is more like UserId, then you'd factor that into the above examples so as not to end up with UserUserId.
Naming foreign key constraints
This is mine:
FK_childtablename_[differentiator]parenttablename
The differentiator is used when there is more than one FK between the same two tables (e.g. CreatedByUserId and AssignedToUserId). Often I use the child table's column name for this.
Example 1:
Given tables: Workitem and User
Where User has CreatedByUserId and AssignedToUserId
Foreign key names are FK_Workitem_User_CreatedByUser and FK_Workitem_AssignedToUser
I use double-underscores if tables/columns have underscores in the name:
Example 2:
Given tables: work_item and user
Where user has created_by_user_id and assigned_to_user_id
Foreign key names are FK_work_item__created_by_user and FK_work_item__assigned_to_user
Is usual to name the foreign key fields with an ID (IDORDER, IDPERSON, ...), if you have a table called PERSONS and another CITIES, if one person is in certain city, CITIES has an IDCITY field (K), PERSONS has a IDPERSON (K), and other field IDCITY (FK).
Hope this answers your question. I mean, a foreign key is only foreign when it's in other table, but not in theirs. But it's a good practice to name always the same to the same fields, even if they are in other tables, as a foreign key.
You shouldn't.
If a column becomes a foreign key later, you will have to change the column name, breaking all the scripts that are using it.
If there are multiple foreign keys, you don't know which column belongs to which key, so the only information you gain is that the column is a foreign key, but you already know it by looking at the keys.
Usually I name the foreign key column the same as the primary key, so I know immediately where the key maps.
I normally use the same name as the referenced column in the table holding the FK.
Only if this is potentially confusing (or a column with this name already exists, say id), would I be more explicit. In such a case, adding the entity type name before the rest - say ProductId.
My style is slightly different:
fk_table_column
eg: fk_user_id that is foreign key to User table on id column. I do not use any capital latter.