Alter table to add a foreign key - mysql

I am using MySQL.
I have an existing table named school with hundreds of rows data be populated. Now I have another table named student, its primary key is "sid".
I would like to alter my school table to have a foreign key reference to a student.
I tried the following sql statement:
ALTER TABLE school ADD FOREIGN KEY (sid) REFERENCES student(sid);
But I get error:
ERROR 1072 (42000): Key column 'sid' doesn't exist in table
What is the correct way to alter table to add a foreign key to another table?

You have to add the column sid on your table first.
ALTER TABLE school ADD COLUMN sid [INT, VARCHAR2(10];
ALTER TABLE school ADD FOREIGN KEY (sid) REFERENCES student(sid);
PS: I put [INT, VARCHAR2(10] because I don't know what type student(sid) is. Just change to the correct one.

where do you want to link your foreign key?
it seems that you missed the key to link against in the school table:
As far as i can imagine you want to link a student to his school.
So what i'd do is to add a column to the student table:
ALTER TABLE STUDENT
ADD COLUMN SCHOOL_ID INT NOT NULL;
then i'd create the foreign key in STUDENT table to point to SCHOOL
ALTER TABLE STUDENT
ADD FOREIGN KEY (F_SCHOOL_ID) REFERENCES SCHOOL(ID);
This is the best way and not the other way round.

Related

Cannot Add foreign key constraint to my table

I am trying to set a FK and I am getting an error
My datatypes are same as reference table.My Artists table contain all the names and I created another table for artist images.
Tables:
ALTER TABLE Artist_Images
ADD CONSTRAINT FK_Artist_Images_Artist
FOREIGN KEY (Artist)
REFERENCES Artists (Artist)
#1215 - Cannot add foreign key constraint
Is it because Artist isnt a PK in Artists table and can't be used as PK? Any other suggestions on how can I link the tables?
One of the most common reason for not being able to create a foreign key when data exists is that the column in the table you are trying to add the key to has values which do not exist in the referenced table.
In this case, you can check for that by running the following query:
SELECT i.Image, i.Artist FROM Artist_Images i
LEFT JOIN Artists a on i.Artist = a.Artist
WHERE a.Artist IS NULL
If you get any rows, you need to resolve that before you can create the foreign key.

Adding a foreign key to a table

I haven't practised SQL in a while and I forgot how to add a foreign key to my table
mysql> alter table students
add foreign key fk_unit(unitid)
references unit(unitid)
on delete no action
on update cascade;
ERROR 1072 (42000): Key column 'unitid' doesn't exist in table
I'm wondering why this is the case? My unit table has a primary key called unitid, why does this keep happening?
Try this one it should work....
ALTER TABLE students
ADD CONSTRAINT FK_UnitId FOREIGN KEY (unitid)
REFERENCES unit(unitid);
Try this
ALTER TABLE Students
ADD FOREIGN KEY (unitid)
REFERENCES unit(unitid)
Your query is correct. Looks like field 'unitid' is missing from 'students' table or it has a different name.

How to change primary key of table

I want to change primary key of table, initially it was id, now i want to change it to userid
smsusers(id,fname,lname,userid)
Here id is varchar type
adn userid is int type
for this i am trying following query
ALTER TABLE smsusers DROP PRIMARY KEY
which is showing this error
#1025 - Error on rename of '.\xrcwrn_sms\#sql-ae0_6f' to
'.\xrcwrn_sms\smsusers' (errno: 150)
id of smsusers is associated with many tables as foreign key.
How to change the primary key.
Here is an example:
ALTER TABLE `database`.`table`
DROP PRIMARY KEY,
ADD PRIMARY KEY (`userid`);
The message is telling you that you can't drop the primary key yet because it is referenced by one or more foreign keys. You need to identify and drop the foreign keys first, then drop the primary key.
ERROR NO:150 means Foreign key definition problem. I think that some other table has a foreign key constraint depending on this PK, so you need to drop that first and rebuild it later.
I tried this link. This is working properly.
My steps are
CREATE INDEX id_pk_unique ON smsusers (id)
ALTER TABLE parent DROP PRIMARY KEY;
ALTER TABLE parent ADD PRIMARY KEY (userid);

SQL Add foreign key to existing column

If I am using the following SQL command in SQL Server 2008 to update a table with a foreign key constraint:
ALTER TABLE Employees
ADD FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id)
UserID being my FK column in the Employees table. I'm trying to reference the UserID in my ActiveDirectories table. I receive this error:
Foreign key 'UserID' references invalid column 'UserID' in referencing
table 'Employees'.
Error indicates that there is no UserID column in your Employees table. Try adding the column first and then re-run the statement.
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
Maybe you got your columns backwards??
ALTER TABLE Employees
ADD FOREIGN KEY (UserID) <-- this needs to be a column of the Employees table
REFERENCES ActiveDirectories(id) <-- this needs to be a column of the ActiveDirectories table
Could it be that the column is called ID in the Employees table, and UserID in the ActiveDirectories table?
Then your command should be:
ALTER TABLE Employees
ADD FOREIGN KEY (ID) <-- column in table "Employees"
REFERENCES ActiveDirectories(UserID) <-- column in table "ActiveDirectories"
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
MySQL / SQL Server / Oracle / MS Access:
ALTER TABLE Orders
ADD CONSTRAINT fk_PerOrders
FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
In the future.
ALTER TABLE Employees
ADD UserID int;
ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
REFERENCES ActiveDirectories(id);
ALTER TABLE Faculty
WITH CHECK ADD CONSTRAINT FKFacultyBook
FOREIGN KEY FacId
REFERENCES Book Book_Id
ALTER TABLE Faculty
WITH CHECK ADD CONSTRAINT FKFacultyStudent
FOREIGN KEY FacId
REFERENCES Student StuId
way of foreign key creation correct for ActiveDirectories(id), i think the main mistake is you didn't mentioned primary key for id in ActiveDirectories table
If the table has already been created:
First do:
ALTER TABLE `table1_name` ADD UNIQUE( `column_name`);
Then:
ALTER TABLE `table1_name` ADD FOREIGN KEY (`column_name`) REFERENCES `table2_name`(`column_name`);

MySQL Removing Some Foreign keys

I have a table whose primary key is used in several other tables and has several foreign keys to other tables.
CREATE TABLE location (
locationID INT NOT NULL AUTO_INCREMENT PRIMARY KEY
...
) ENGINE = InnoDB;
CREATE TABLE assignment (
assignmentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
locationID INT NOT NULL,
FOREIGN KEY locationIDX (locationID) REFERENCES location (locationID)
...
) ENGINE = InnoDB;
CREATE TABLE assignmentStuff (
...
assignmentID INT NOT NULL,
FOREIGN KEY assignmentIDX (assignmentID) REFERENCES assignment (assignmentID)
) ENGINE = InnoDB;
The problem is that when I'm trying to drop one of the foreign key columns (ie locationIDX) it gives me an error.
"ERROR 1025 (HY000): Error on rename"
How can I drop the column in the assignment table above without getting this error?
As explained here, seems the foreign key constraint has to be dropped by constraint name and not the index name.
The syntax is:
ALTER TABLE footable DROP FOREIGN KEY fooconstraint;
The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.
I would think the following query would do it:
ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;
As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.
ALTER TABLE your_table_with_fk
drop FOREIGN KEY name_of_your_fk_from_show_create_table_command_result,
drop KEY the_same_name_as_above
Check what's the CONSTRAINT name and the FOREIGN KEY name:
SHOW CREATE TABLE table_name;
Remove both the CONSTRAINT name and the FOREIGN KEY name:
ALTER TABLE table_name
DROP FOREIGN KEY the_name_after_CONSTRAINT,
DROP KEY the_name_after_FOREIGN_KEY;
Hope this helps!
Hey I followed some sequence above,
and found some solution.
SHOW CREATE TABLE footable;
You will get FK Constrain Name like
ProjectsInfo_ibfk_1
Now you need to remove this constraints. by alter table commantd
alter table ProjectsInfo drop foreign key ProjectsInfo_ibfk_1;
Then drop the table column,
alter table ProjectsInfo drop column clientId;
Here's a way to drop foreign key constraint, it will work.
ALTER TABLE location.location_id
DROP FOREIGN KEY location_ibfk_1;
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you a row ,at left upper corner click the +option ,the click the full text raio button then click the go .there you will get the name of the index, something like this:
CONSTRAINT region_ibfk_1 FOREIGN KEY (country_id) REFERENCES country (id) ON DELETE NO ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key region_ibfk_1;
or
more simply just type:-
alter table TableName drop foreign key TableName_ibfk_1;
remember the only thing is to add _ibfk_1 after your tablename to make like this:- TableName_ibfk_1
first need to get actual constrain name by this query
SHOW CREATE TABLE TABLE_NAME
This query will result constrain name of the foreign key, now below query will drop it.
ALTER TABLE TABLE_NAME DROP FOREIGN KEY COLUMN_NAME_ibfk_1
last number in above constrain name depends how many foreign keys you have in table
You can not drop the foreign key column because it is being referenced from the table assignmentStuff. So you should first drop the foreign key constraint assignmentStuff.assignmentIDX.
A similar question has already been asked here. Check also here for more info.
Try this:
alter table Documents drop
FK__Documents__Custo__2A4B4B5E
step1: show create table vendor_locations;
step2: ALTER TABLE vendor_locations drop foreign key vendor_locations_ibfk_1;
it worked for me.