I am familiar with foreign keys and referential integrity. I have a table in which the PK is made up of two fields. That PK is also part of the primary key in a child table. When the parent record is deleted, I want the child record deleted as well (cascade delete). I know how to define a complex fk constraint on the child table using SQL.
How do you define a complex fk key constraint through the phpMyAdmin user interface with the relations view? There does not appear to be a mechanism for having the constraint based on a two field combination.
I only want the child record deleted if the parent table record is deleted, which means both fields that make up the foreign key are being deleted and not just one.
Thanks in advance for anyone who can tell me how to do this or for letting me know it is not possible.
Related
I'm gonna migrate multiple DBs to one DB, all those DBs have same tables, the problem is duplicate keys, so for this reason I thought the easiest solution is to have ex_id in my main tables and then have a foreign key in child tables that should reference either to id or ex_id.
Can we have something like that, or any better solution ?
Note: I do not want to lose any data, they are the real live DBs.
Thanks
No. A foreign key constraint names exactly which table and column(s) it references, and it must reference the same table and column(s) on every row.
I say column(s) because some constraints are multi-column, not because the foreign key can reference your choice of column.
When we delete a primary key which is foreign key in other table, which gets deleted first? Primary key in first table or Foreign key in the other table? I was asked this question in interview. Please provide some reason with answer too :)
In general, you would need to delete the foreign key references before deleting the primary key. Otherwise, the foreign key constraint would be invalid.
I might guess that this is the answer the interviewer is looking for.
In practice, though, the answer would be "at the same time". The normal way to accomplish this is using a cascading delete foreign key reference. The deletes would all take place in the same transaction (on most databases at least), so they would not take effect until the commit.
If you were doing this manually, you do typically do:
Drop the foreign key constraint.
Re-set the values in the columns for the foreign key reference (typically to NULL).
Delete the appropriate row(s) in the primary key table.
Well to me looks like a tricky question.
My answer would be neither, you will get an error unless you define a DELETE CASCADE constraint
In that case row reference that PK would be delete first.
The PK record cannot be deleted until the FK records are gone. That is part of the very definition of what having such relationships is and one of the main reasons for having a FK relationship. The reason is that you don't want to have orphaned child records that no longer have a parent and thus do not make sense. This is the data integrity issue.
Databases will give an error if you try to delete the PK without first deleting the child records. Cascade delete can hide this by deleting them first in the background, but this is very bad thing much of the time and should be avoided. You do not want to willy nilly delete child records, there are many times when the existence of a child record is telling you that the parent should not be deleted.
i am creating a database with a EER Diagram and used non-identifying foreign key relationships to create my foreign key.
what i need for my foreign keys:
Default values should be 0 and should be used when no value is given for the FK
the presences of the keys in the related table should not be required
dont allow null values
what i get when synchronizing data models:
Default values are not synced to DB from EER Diagram
Default values are not used when implemented manually
the presences of the keys in the related table are required
FK fields dont allow nulls (yay!)
what am i doing wrong? i tought i had read on the web that non-identifying Foreign keys did what i needed? if everything fails i could create simple columns and only put an index on em but i tought it could be handy in the future to use foreign keys plus it looks better in my EER Diagram.
A non-identifying Foreign key means that your entity can exists without relation to the other entity, and you got it.
But technically in mysql this is achived by using null and not 0, which means instead "linked to an entity with ID=0"
We are in the midst of trying to clean up the database and debating about whether or not to put in place foreign key constraints on our tables. It would be a very convincing argument for using them if changing the schema of a primary key in one table affected the schema of foreign keys in other tables. But is this the case?
For example, let's say I have a USER table with primary key id and I have another table BLOGGERS whose blogger_id is a foreign key tied to id. Let's say that id is initially declared as a SMALLINT, but then I have hordes of users signing up and we need to increase the range available for ids. If I alter id to be and INT, will that automatically alter blogger_id in the BLOGGER table to be an INT also?
Regardless of the answer to my primary question, does anyone know of any compelling reasons to formally declare foreign key constraints, other than to limit the data the can be placed in that field? Thanks!
No, MySQL does not change the data type in child tables if you change the data type in the parent table.
I had to help one of my consulting customers who had reached the maximum INT value in their Users table. But as you can imagine, there were 30 other tables that referenced Users. We had to ALTER TABLE on each of those other 30 tables before we could change the primary key data type in the Users table, because it wouldn't work if new user id's could not be referenced by the child tables.
As for your question about foreign keys, yes, I do recommend them for the sake of enforcing data integrity. In every database I have analyzed that tried to do without foreign keys, they had a lot of orphaned rows in child tables, with no automatic way of detecting them.
That said, it's surprisingly common for sites to forego foreign keys, assuming they will "just do the right thing" in their application code to avoid orphaned data.
One of the arguments against foreign keys is that the presence of foreign keys creates some cases of locking that you may not expect. If I UPDATE a child row, you expect it to lock that row for the duration of your transaction. But if you have a foreign key, this also locks the parent row, in the table referenced by the foreign key.
Example: suppose you have a parent table ShoppingCart and a child table LineItems. If you UPDATE the quantity of a row in LineItems, your transaction makes an exclusive lock (X-lock) on that row. But it also makes a shared lock (S-lock) on the parent row in ShoppingCart. It makes sense that you wouldn't want the row you're depending on to be DELETEd, for example, while you're in progress of working on one of the rows that references it.
This is a shared lock, so multiple transactions can have this kind of lock at the same time, but then if you need to update the parent row directly while one or more clients have those implicit shared locks, you are blocked.
I went over a legacy database and found a couple of foreign keys that reference a column to itself. The referenced column is the primary key column.
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
What is the meaning of it?
ALTER TABLE [SchemaName].[TableName] WITH CHECK ADD
CONSTRAINT [FK_TableName_TableName] FOREIGN KEY([Id])
REFERENCES [SchemaName].[TableName] ([Id])
This foreign key is completely redundant and pointless just delete it. It can never be violated as a row matches itself validating the constraint.
In a hierarchical table the relationship would be between two different columns (e.g. Id and ParentId)
As for why it may have been created quite likely through use of the visual designer if you right click the "Keys" node in object explorer and choose "New Foreign Key" then close the dialogue box without deleting the created foreign key and then make some other changes in the opened table designer and save it will create this sort of redundant constraint.
In some cases this is a preferred way to reduce redundancy in your model. In using the self referencing foreign key (as shown in you example) you create a hierarchical relationship between rows in your table. Pay attention to what happens when you delete a row from the table, cascading on delete might remove rows you still want.
Using these sort of keys moves some of the data validation to the DB model as opposed to making this a responsibility of the program/programmer. Some outfits prefer this way of doing things. I prefer to make sure programs and programmers are responsible - data models can be hard to refactor and upgrade in production environments.