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.
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.
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.
My question is that can I use cascade with composite Primary key?
I have a table FbUser and a table FbFriends. FbFriends table has UID and FID as composite primary key, In other tables it is represented as foreign key(UID,FID)
If I make statement delete from FbFriends where UID="10" and FID="2" CASCADE, Will that delete the child rows as well?
ON DELETE CASCADE is an attribute of the foreign key. It is not a clause that you add to your DELETE statement. If the foreign key is defined to delete child rows when the parent is deleted, it doesn't matter whether the foreign key is defined on a single column or on multiple columns, the delete will cascade.
Personally, though, I'm not a big fan of cascading deletes or any other "magic" that happens outside of the logic in a piece of code. I've seen way too many cases where an ORM is misconfigured to do a DELETE followed by an INSERT rather than an UPDATE or where a developer builds a script that deletes and reloads some number of rows in a table inadvertently create a mess when a cascading foreign key or a trigger that wasn't looked at caused modifications to some number of other tables. If the original developer fails to realize that those tables are potentially impacted by his change, he'll certainly fail to test the data in those tables and the change can rather easily get promoted to production before users start seeing the problem and crying. Sure, it's more verbose to explicitly delete from the child table before the parent table. But doing so generally makes it much more likely that someone can read and follow your code in its entirety.
In the Oracle realm, for example, Tom Kyte is against cascade deletes. You can also find various cases where cascading constraints caused unexpected behavior because the developers maintaining a system didn't remember that someone long ago had configured the constraints in a particular way. Personally, I'd much rather get an error telling me that the database can't delete a row because there are child rows rather than potentially losing data that I didn't intend to lose.
I have a system that has categories that are joined to events. All of these categories are simple, they have an id, and name. One thing that worries me is that when I am creating these categories, the ids should always remain the same, be static. If I deleted one, let's say "Politics" at id=1, all of those events would have an orphaned category. One solution I thought of is to just assign string ids to them, so if they do happen to get deleted, it wouldn't really matter. What kind of solution do you recommend?
From my perspective it seems like you could keep the ids and just put a constraint that doesn't allow you to delete the record, only edit them. Another, is to use string ids, but that seems like a pain, although it seems to solve the problem of worrying about the ids being messed with.
Yes, this is what foreign key constraints are for. They also allow for rules on how to handle deletes -- for example, allowing a delete to cascade through dependent records, which is of course very dangerous and not what you would want in this situation. A simple basic constraint will do.
HOWEVER!!!! This is the important thing to understand about mysql. The default mysql engine (myisam) has absolutely no support for foreign key constraints. You need to use an engine that supports them -- most commonly innodb.
If you specify a constraint when you're generating your DDL, a myisam table will accept the constraint but simply ignore it, so make sure all your related tables are setup/altered to be innodb tables before you add your constraint(s).
How do you add a constraint?
ALTER TABLE `event` ADD CONSTRAINT `category_event`
FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`);
In this example, it assumes your event table has the foreign key category_id in it, to create your linkage. After adding this constraint, if you attempt to delete a row from the category table, and an existing event row contains that key, mysql will disallow the DELETE and return an error. This is discussed in great detail here: http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
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.