what is the difference between the following codes?
1.
ALTER TABLE Orders
ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
2.
ALTER TABLE Orders
ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);
what is the use of adding name to our foreign key constraint(FK_PersonOrder) in the second code?
ADD CONSTRAINT FK_PersonOrder is giving custom name to foriegn key else it will auto generate dynamically.
Both these statements are functionally the same. Giving a name to a foreign key (or any other constraint for that matter), makes working with it a tad easier - when a DML statement fails because it violates it it's easier to understand, it's easier to drop it if you choose to do so, etc.
For the same reason we name anything; to describe it sufficiently that we understand what it is, or does
Sometimes database engines don't explicitly state any details about the other end of the relationship and in those cases it's a lot nicer to be inserting into your address table and see "constraint 'fk_person-addressid_address-id' violated" than "constraint 'fk_12ef3a2dc' violated" and be left thinking "hmmm, 12ef3a2dc/ was that the addresses table one? Or the job role one? Or the company one.. I'll just go and look in the dB to find out.."
Related
I have successfully added my first FK in heidisql using the foreign key tab and adding all the appropriate sections.
I have tried to do the same to my second related column both by using the FK tab and by running a query but I keep getting an error.
SQL Error (1005): Can't create table sprout.#sql-430_3 (errno: 150 "Foreign key constraint is incorrectly formed")
sprout is my db name so I have no idea why it is saying cant create table sprout (because I'm not referencing it in my query).
sql query for my first FK(generated via heidisql):
ALTER TABLE `purchase_history`
ADD CONSTRAINT `bus_id` FOREIGN KEY (`bus_id`) REFERENCES `business` (`bus_id`);
sql query for my second FK(generated via heidisql)
ALTER TABLE `purchase_history`
ADD CONSTRAINT `bus_name_fk` FOREIGN KEY (`bus_name`) REFERENCES `business` (`bus_name`);
sql query I wrote to try and add second FK
Alter table purchase_history
Add constraint bus_name_fk
Foreign key (bus_name)
references business(bus_name);
Can someone help explain to me how my constraint is incorrectly formed? To my understanding I was able to add another constraint to the the table.
This is too long for a comment.
Huh? Why are you adding two foreign constraints to the same table . . . but using different columns? That doesn't really make sense. In general, the foreign key should be referencing the primary key of the other table, which I presume is bus_id.
Then, if you want the business name, you can use a join to get the name.
Tell me please either should I to give name the foreign key?
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns)
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
I can do some manipulations with the constraint by it's name, but what I can do with the foreign key name? Give me some examples please.
As the documentation explains:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
In other words, what you are providing is not a "foreign key name" but a "(foreign key) index name".
Having a name for an index is useful for tracking that index.
To be honest, though, I don't provide such names. I would much rather explicitly declare an index on the foreign keys, rather than have the database do it for me.
(Note: Most databases do not automatically create an index when a foreign key is declared.)
Yes it is.
If you want to alter or drop constraint in future,then it is possible using name only.
DROP FOREIGN KEY constraint_name;
You can check here.
I'm new to learning SQL syntax and came across this example in a book. I understand the need for foreign keys and using the constraint function in order to set the key to another table that is created (EMPLOYEE_TBL in this example).
My question is why it listed the line CONSTRAINT EMP_ID_FK FOREIGN KEY (EMP_ID). What exactly is the EMP_ID_FK portion? Since you just need to use the CONSTRAINT function to set a field on you child table to the parent table, couldn't you just write it as CONSTRAINT FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE_TBL (EMP_ID)); instead?
Am I understanding this incorrectly? Any help would be appreciated. Thanks!
CREATE TABLE EMPLOYEE_PAY_TBL
(EMP_ID CHAR(9) NOT NULL,
DATE_HIRE DATE NULL,
DATE_LAST_RAISE DATE NULL,
CONSTRAINT EMP_ID_FK FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEE_TBL (EMP_ID));
The clause CONSTRAINT EMP_ID_FK simply gives a name to the constraint. This becomes necessary later if you want to disable or drop the constraint. You are correct that the name (EMP_ID_FK) is optional; if you omit it you can also omit the CONSTRAINT keyword, as the clause FOREIGN KEY is enough to tell the interpreter what it is you want.
Naming your constraints is entirely optional but is considered good practice for documentary purposes and in case, as I said, you later need to do something with the constraint. If you omit the name, the database will automagically name the constraint for you, but good luck finding out what that name is.
Put it like this.
Table 1 has to have a reference to Table 2. Table 2 has a Primary Key ID that is a unique value, that means it can be accessed with this ID, as it is unique in all the rows of this table. Now table Table 1 needs to reference to that ID. You need to store that ID in Table 1 so you can reference to it and you know to which Table 2, Table 1 points. You use the naming convention Table2_ID_FK to know that that Field in Table 1 is a reference to the ID of table 2. The constraint is to set the actual relation between these tables.
I want to delete a record from a school table without affecting a foreign key to the department name. I tried but I got this message:
"Cannot delete or update a parent row: a foreign key constraint fails
(arusms.department, CONSTRAINT department_ibfk_1 FOREIGN KEY
(school_name) REFERENCES school (school_name) ON UPDATE
CASCADE)"
I'm not sure why you would want to do that. If you delete the school, the department will be orphaned. That's the point of having foreign keys in the first place, to enforce referential integrity. If you want the department to remain and to be able to do this, you will need to alter the foreign key to include ON DELETE SET NULL. Otherwise, you will have to drop the constraint, perform the delete, and recreate the constraint.
Your error message is hiding the real cause.
(
arusms.department,
CONSTRAINT department_ibfk_1
FOREIGN KEY (school_name)
REFERENCES school (school_name)
ON UPDATE CASCADE
)
When you created the foreign key constarint, you omitted the ON DELETE part. MySQL used the default action for this, which is ON DELETE RESTRICT. See the MySQL docs: FOREIGN KEY Constraints
If you want to be able to delete schools without cascading effect to the related departments, you can either
remove the FK constraint or
make the column (department.school_name) nullable and alter the constraint to have the ON DELETE SET NULL action.
If you want to be able to delete schools and cascading deleting the related departments, you can
alter the constraint to have the ON DELETE CASCADE action.
The whole purpose of having a foreign key is to keep data consistent. In your case, it means that for each department, there must exist a corresponding school record. And if you DELETE a school, all corresponding departments should be deleted as well, or at least their school reference must be NULLed.
If you don't need this kind of enforcement, DROP the foreign key.
Alternatively, if you just want to reassign a department to another school, first do that, and only then DELETE the original school.
I have a database with two tables, PROCESS (PK Process_Id) and PROCESS_STAGE (PK Stage_Id, FK Process_Id).
At least I think I have set this up - in the foreign key relationships dialogue box I have
Foreign key base table: PROCESS_STAGE,
Foreign key columns: Process_Id,
Primary/unique key base table: PROCESS,
Primary/unique key column: Process_Id.
I have also set enforce for replication and enforce foreign key constraints to 'Yes'.
But I can still do the following things which break this relationship:
Delete items from PROCESS which have references from
PROCESS_STAGE
What do I need to do to correct this?
Thanks!
Try using SQL to create the foreign key
ALTER TABLE PROCESS_STAGE WITH CHECK ADD
CONSTRAINT FK_PROCESSTAGE_PROCESS
FOREIGN KEY (Process_Id) REFERENCES PROCESS (Process_Id)
If this still fails, look at the tables schema/owner: you may have more than one table and you're using the wrong one. Example:
dbo.PROCESS_STAGE
deed02392.PROCESS_STAGE