Alternative of Foreign Key in RDBMS - mysql

I am studying database course now, and I know a foreign key is the primary key of other table. But I am curious about the presentation of relationship: if we don't use foreign key to link with other table, but use a function to map a primary key of a record from a table to another one, does it work? I think it works in theory, but I am not sure is good idea in reality. Is it reasonable?
P.S.
because I think a table is a set, a function is mapping method from a set to another.
Thanks in advance,
Sincerely.

You don't have to define foreign keys in a MySQL database. In a query, you can use joins to define how relations should be fed into your query's result set.
There are good reasons to define foreign keys, though. Some of these are:
Defining a foreign key creates an index on that column, influencing the way that the RDBMS stores its data, so that it can optimize queries for faster results;
If you set a foreign key in MySQL, you can also define what happens to child records when the table containing the primary key is changed. Child records may, for example, be deleted automatically (a "cascading delete"). This is helpful for database integrity, as this avoids orphaned records in the child table. These cascades may go through several relationships levels.

Related

Why is it necessary to explicitly specify foreign keys and references in databases?

Could you please explain me why it is necessary to specify those foreign keys when creating tables?
I mean, I've created two tables which have a one-to-many relationship (on the ER-diagram) but I didn't specify the foreign keys and references. I can connect the tables using the where-clause and even perform joins and so on.
Probably, I don't get some basic concepts, although I've read some stuff about it. I guess it has something to do with data consistency or referential integrity or something.
So, could you explain me these concepts?
Are those references and foreign keys are absolutely required if I have, let's say, 8-10 tables with one-to-many relationships and if I can assure that the data is inserted correctly into the database?
It is not necessary to specify foreign key relationships. It is just a good idea.
When you specify the relationship, the database ensures relational integrity. That is, it ensures that the values in the foreign key column are legitimate values.
In addition, the cascade options on foreign keys are a big help when values are updated or deleted.
The reason it's necessary is to ensure data integrity.
Suppose you have a table called orders, and a table called order details, both have a column called order id.
If you don't use foreign keys you might be inserting order details for an order that doesn't exists in the orders table.
Having a foreign key will make the database raise an error if you try to add order details to a non existing order.
It will also raise an error if you delete an order that already have details, unless you delete the order details first or specify cascade delete on the foreign key.
The driver for the foreign key constraint is the need for 'data integrity'. And the DBMS (the database server software) helps you prevent any accidental (unintentional) modification of the data when you specify the foreign key constraints. It's like you are helping the DBMS help you. Thus, if you specify the constraints, for instance, an accidental deletion of a product may be prevented when there are outstanding orders for that product.
You'll agree that when you carefully analyze the constraints and specify them in SQL at the time of creating the database (tables) then it helps ensure integrity.
This is useful when you are choosing to keep the 'knowledge of your entities' at the database level itself. This is a fine beginning approach in that your tables (relations) are more-or-less self-contained. An alternative approach to have all those consistency checks at a level higher than database. This is the approach, for instance, taken by an MVC framework like Rails where models are the layer where the constraints are applied and the tables themselves do not need to specify the foreign key and other constraints.
Which approach is better is up to your taste, usually, but you should use the building blocks in their spirit.

should i create index for each foreign key?

I have table department that has two column (dept_ID and dept_name)
my another table is login which i create a foreign key for the column dept_name referencing dept_name at table department. so i create an index named index_department, now in login table, i want to create another foreign key for the column eadd which will reference to DIFFERENT table named info_table.
should i create another index for the second foreign key??
another scenario, i want to create a dept_name column at info_table too. can i use the same index 'index_department'??
The general answer is, "It depends."
As #gordon-Linoff commented "You create indexes to meet performance requirements for queries."
Indexes take up space and and take processing time as the have to be maintained. So the case for any given index depends on the trade off between cost and usage. For example if you the data rarely changes, but you look it up a lot you will prefer to have more indexes.
My educated guess is that on the scale you are probably working you do want the indexes on all your foreign keys.
Specifically in mysql you seem to get the index is you formally add the FK constraint. It is discussed here does mysql index foreign key columns automatically
I say formally, because you can have implied foreign key relationships without actually declaring/enforcing the constraints. People sometimes do that to avoid even the cost of the checking/enforcing constraint. The risk is in updates that violate referential integrity. But I'm drifting onto a tangent.
As a side note, there is some pertinent discussion here does a foreign key automatically create an index
In MySQL (at least 5.6, which I am using), indices are automatically created for foreign keys.

How efficient are foreign keys?

Very simple question: Which is more efficient?
A DELETE query on a parent table, followed by a DELETE query on a child table
A DELETE query on a parent table that results in a foreign key deleting rows from a child table
To explain further, I'm working with very large tables (holding a few million rows), and I'm just wondering if the integrity offered by foreign keys is worth the extra work that MySQL has to do, over just remembering to update/delete child tables. I'd like to know before I actually go ahead and update to use foreign keys ;)
Whatever you think you can code yourself, the database can do at least as well, and without having to use the network to do it.
Use the foreign keys.

Question about MYSQL foreign keys and orphan rows

If I add a foreign key between two tables, am I allowed to add orphan rows afterwards? Also when I'm creating a foreign key between two tables, is there any way to create it ignoring the orphan rows?
My next question is about the efficiency of foreign keys. I had always thought that they created an index between one key in a table and the corresponding key in another table which essentially made it a linear lookup when doing a join.
Is a foreign key much more efficient then simply having an index or are they the same?
Thanks.
foreign key relationship is often between a foreign key in one table and a primary key in another.
primary key do implicitly create an index.
Not foreign keys. Mostly it's good practice to add index on a foreign key column.
keys are constraints to guarantee data consistency and index can be used improve access performance on the data. So these are different things that you often combine in practices and thus are often confused.
Regarding orphan rows I think the concept of keys is to prevent this. But I'm not completely sure If I understand exactly what you are asking here. I think adding orphan rows is not possible and creating keys if orphan rows exist sounds kind of impossible.
see also other questions on SO dealing with foreign key / index topic.
Here some more good answers related to primary key / key / index

Is Foreign Key field important?

I got a habit to use INT field for foreign ID (INT CommentID, INT TopicID, etc)
But I never use Foreign Key field, is this better?
Is it possible to change my currents database design in some tables to Foreign Key field? I already have over thousands data in the tables.
Foreign Keys constraints are very important. They enforce domain relationships between your entities. (It's no fun working with a database that contains orphaned or incomplete data).
Even in the less likely scenario of a high write to read ratio database, it's still best to include all FKs, and only remove them individually if they can be proven to be hurting INSERT performance.
In addition, they may allow the query optimiser to make extra performance optimisations.