I met Rasmus Lerdorf at a conference a few months ago. During his talk, one suggestion he made was that we rarely use foreign keys, because if something goes wrong with a foreign key relationship it can lock up your whole database.
Here's what foreign keys enforce that Rasmus warned against: "When one table has a foreign key to another table, the concept of referential integrity states that you may not add a record to the table that contains the foreign key unless there is a corresponding record in the linked table."
On the flip side, foreign keys are great for documentation, staying organized and establishing relationships that save coding leg work.
What can be done to mitigate the risks of foreign keys, while leveraging the benefits?
This question / answer does a great job of laying out both the benefits and risks of foreign keys, but I'm looking for more specific insight on how to avoid the pitfalls yet take advantage of the good.
The database wont lock up, its the badly written application on top of it.
Ofcourse you can take some shortcuts when building application but later on you are more likely than not pull the hair on that inconsistent data you have because of not using FKs.
Related
I'm curious if something like this is possible, if at all reasonable.
I have a column in a table, that's called ref_table and it points to a table that the current entry relates to. Let's say, in table table_people, Person ID 1 is a client and Person ID 3 is an employee, so respectively their ref_tables will show "table_clients" and "table_emplyees". I shouldn't have a problem keeping the values valid through PHP, but what would some ways of achieving it through SQL be?
I tried testing it with a foreign key constraint to INFROMATION_SCHEMA:
FOREIGN KEY `people_constraint_tables` (`ref_table`)
REFERENCES `INFORMATION_SCHEMA`.`COLUMNS`(`COLUMN_NAME`)
ON DELETE RESTRICT
ON UPDATE RESTRICT
No point refining it since it didn't work. It seems like there's one way to make it work but it is a dirty cheat apparently.
Would you do it with triggers? Would you do it at all? Someone with experience with MySQL tell me if that'sreasonable at all, I'd like to know. Thank you.
MySQL doesn't have the facility to do this easily. Other databases do, through generated columns or table inheritance.
Would I do this with triggers? Well, yes and no. If I had to do this with one table and I had to use MySQL and I wanted to introduce relational integrity, then triggers are the way to go. There is little other choice.
But really, I would simply have a different table for each reference type. There is a little bit of overhead in this (in terms of partially filled tables). And for some applications, a single reference table is quite convenient (internationalization comes to mind). But in general, I would stick with the standard method of a separate table for each entity with properly declared foreign key relationships.
I am working on an assignment and I'm a little rusty with my SQL basics as I mainly work with already created tables, not with creating them. I was given a database model and asked to create it. I was told the model may have errors and to just correct them. Here is a snippet of the part I am having issue with:
http://i.imgur.com/0KyMquZ.jpg
I've been trying to figure it out and Googling and researching but I'm just not sure if there's something I'm not getting or I need to adjust the model. The issue I am having is with the operation table and the connecting tables. The primary key for operation is made up of the three primary keys from the connecting tables and another primary key, date. Can that be done? If they were foreign keys in the other tables I think I could figure it out. I've been trying to figure out how to do it but mostly just trying to wrap my head around the concept of what this is showing. I just don't understand how or why. Wouldn't that composite primary key have to be in the other 3 tables are they fine split up? Shouldn't that composite primary key be referencing foreign keys in other tables? I'm just really confused. I'm ok working with databases but designing, not so much.
I would just ask my professor about it but we are never on the same page. I think I understand him in the moment and then I wind up more confused. I don't think it matters for this but it's MySQL.
Although it is technically allowable, I think that it is semantically meaningless in this case as it allows the following situation to exist.
A patient can be subject to the same operation on the same day multiple times by different doctors, but ...
the patient cannot be subject to the same operation on the same day multiple times by the same doctor, but ...
the patient can be subject to different operations from the same doctor on the same day.
To me, this primary key is nonsense and you might as well add a synthetic primary key and make these simple foreign key columns where appropriate.
There is no problem with declaring a composite PK where some of the components are also declared FKs. Logically, this is quite correct.
The effects on performance will be hard to predict. The index that Mysql builds based on the PK declaration will be hard to predict. Some queries will be sped up, others won't.
After reading the comments, I now understand my misconception. I was thinking the primary composite key is made up of primary keys, duplicates from the other tables. I realize now that the composite primary key is made up of foreign keys and one primary key: date. Thanks for the clarification.
This question already has answers here:
What's wrong with foreign keys?
(38 answers)
Closed 6 years ago.
I'm confused about something, time and again i've seen developers including team leaders tell me that using foreign key constraints on their DB is bad practice, that it adds "logic to the database" but that goes against everything i've ever learned about SQL so far...
I need someone to tell me if i'm wrong for thinking that foreign key constraints are a major benefit or if i'm totally wrong and if so why.
It just makes sense to me that in order to ensure data integrity you'd refuse any data that doesn't make sense being there, i'm sorry if this is a duplicate question, but i'm not really finding any definitive answers i'm happy with.
thinking that foreign key constraints are a major benefit
That statement is bit confusing to me cause whether you will create a FK constraint between tables depends on whether those table(s) contains/maintain any relationship between them or not; like Students has courses (OR) Employees works under department
If those table can exist individually (stand alone) then why would you create a FOREIGN KEY constraint at all.
Per your comment: Then what's the reason for not using foreign keys. Ask your lead to give the explanation behind not using FK's instead just saying they are bad. If your lead says that they don't want to enforce foreign key constraint then suggest them to go for NOSQL database like MongoDB or Cassandra and not use Relational Database
I've been tasked with optimizing a somewhat small Microsoft SQL Server 2008 DB that we all feel is under-performing for its size and whose structure is know to have been abused over the years. Now I'm no dedicated DBA, but I do have enough SQL knowledge to CRUD my way through most problems I've so far encountered so I'm looking for advice here that may fill in some gaps in my knowledge.
1) So my first step will be to take a look at the indexing and the fragmentation thereof. One question is, should I rebuild/reorganize existing indexes or should I drop and recreate them?
My next step would be then be to determine if current keys are indexed and if not, create indexes for them.
2) I've noticed many tables contain columns with foreign key values, but very few contain foreign key constraints on these values. Now I know foreign key constraints aim to maintain the relationships between tables, but should every column containing foreign key values have a foreign key constraint? I feel values used in joins for example, should be constrained so those I will be adding without question wherever I find they're missing. I've read adding foreign key constraints doesn't necessarily improve performance as it results in an extra check during write operations, but indexing these added foreign keys may. What are your thoughts on this?
I'm also researching into adding a maintenance plan that could automatically do index maintenance from time to time and have found some great material to help me accomplish this.
Thanks guys!
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.