Add Foreign Key to an existing column? - sql

Hello i am beginner in SQL and i have one question:
How to add new Column_B(int) which is foreign key to an existing Column_A(id) in same Table_A?
I tried this but i got Error Code: 1215. Cannot add foreign key constraint
ALTER TABLE Table_A ADD COLUMN Column_B int;
ALTER TABLE Table_A
ADD fk_Table_A FOREIGN KEY (Column_B) REFERENCES Table_A (Column_A);

alter table Table_A
ADD constraint fk_Table_A FOREIGN KEY (Column_B) REFERENCES Table_A (Column_A);

It is possible that your references does not match. It can only add a foreign key when all the rows satisfy the foreign key condition, which is in your case that every value of Column_B is in table_A.Column_A.

Related

DB2 - Can I recreate a foreign key constraint in a table with data?

I'm having the following problem with DB2:
I need to change a column name (column "A"), but the thing is that column A has a PK constraint and a FK constraint. So I need to drop this constraints first, change the column name and then create the constraints again. But I remember a Professor told me once that you can't create a foreign key in a column which already has values. Is that true?
This is my script:
ALTER TABLE TARGET_TABLE
DROP PRIMARY KEY PK_A CASCADE;
ALTER TABLE TARGET_TABLE
RENAME COLUMN A TO B;
alter table TARGET_TABLE
add CONSTRAINT PK_B PRIMARY KEY( B);
alter table TARGET_TABLE add CONSTRAINT FK_B FOREIGN KEY( B) REFERENCES OTHER_TABLE(C);
Thanks in advance.
You can create a foreign key on a column which already has values. The only restriction is that the values must be be valid for the FK you are defining.
If not you will get an error such as
SQL0667N The FOREIGN KEY "I..." cannot be created because the table contains
rows with foreign key values that cannot be found in the parent key of the
parent table. SQLSTATE=23520

SQL ON UPDATE CASCADE - Composite key

I have 2 tables
Table1(PKFK1, PKFK2)
Table2(PKFK1, PKFK2, PKFK3)
I want to do an update cascade on table2 so that every time pkfk2 is updated in table1 is does the same in table2. I have tried the following:
alter table Table2
ADD CONSTRAINT fk_cascadeUP FOREIGN KEY (PKFK1) REFERENCES Table1(PKFK1) ON UPDATE CASCADE,
ADD CONSTRAINT fk_cascadeUP2 FOREIGN KEY (PKFK2) REFERENCES Table1 (PKFK2) ON UPDATE CASCADE;
This gives an error. How can I do the update cascade?
Each ALTER TABLE needs to be its own statement. Try this:
alter table Table2
ADD CONSTRAINT fk_cascadeUP FOREIGN KEY (PKFK1) REFERENCES Table1(PKFK1) ON UPDATE CASCADE
alter table Table2
ADD CONSTRAINT fk_cascadeUP2 FOREIGN KEY (PKFK2) REFERENCES Table1 (PKFK2) ON UPDATE CASCADE
First, you will have to delete the foreign key, and then add the foreign key with your desired requirements. Drop the foreign key from the table and then add foreign key with "ON UPDATE CASCADE".
It would be somewhat like:
ALTER TABLE Table2
DROP FOREIGN KEY [foreign key name]
ADD CONSTRAINT fk_cascadeup2 FOREIGN KEY (PKFK2) REFERENCES Table1 (PKFK2) ON UPDATE
CASCADE;
The other method can be "set foreign_key_checks = 0" and after altering the foreign key, you can set it back to "1".

How to add foreign key to an existing column in SQL Server 2012

I am trying to add foreign key to my existing column using below query
ALTER TABLE Sub_Category_Master
ADD FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
but I'm getting an error
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK__Sub_Categ__Categ__5812160E". The conflict occurred in database "shaadikarbefikar_new", table "shaadikarbefikar.Category_Master", column 'Category_ID'.
Well, the error clearly tells you that Category_ID in your Sub_Category_Master table contains some values that are not present in Category_Master (column Category_ID). But that's exactly the point of having a foreign key constraint - making sure your child table (Sub_Category_Master) only uses defined values from its parent table.
Therefore, you must fix those "voodoo" values first, before you're able to establish this foreign key relationship. I would also strongly recommend to explicitly name that constraint yourself, to avoid those system-generated, but not really very useful constraint names like FK__Sub_Categ__Categ__5812160E:
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FK_SubCategoryMaster_CategoryMaster
FOREIGN KEY (Category_ID) REFERENCES Category_Master(Category_ID)
ALTER TABLE Sub_Category_Master
ADD CONSTRAINT FKSub_Category_Master_Category_ID FOREIGN KEY (Category_ID)
REFERENCES Category_Master(Category_ID);
CREATE TABLE Orders
(
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

How to add unique constraint as foreign key ?

I am trying to add unique constraint as foreign key by this statement:
ALTER TABLE SOME_TABLE ADD(
CONSTRAINT FK_ID FOREIGN KEY (S_ID) REFERENCES OTHER_TABLE(O_ID) UNIQUE (S_ID)
);
I thought that this statement is correct, but all time I got "missing right parenthesis error". Probably I have wrong order of key words.
Could you give me advice how to create an unique constraint ?
I red this issue:
Add a unique constraint of a sql table as foreign key reference to an another sql table
but still I have problem with this.
First, you don't need parentheses. Second, this is two constraints and you might as well give both names:
ALTER TABLE SOME_TABLE
ADD CONSTRAINT FK_ID FOREIGN KEY (S_ID) REFERENCES OTHER_TABLE(O_ID);
ALTER TABLE SOME_TABLE
ADD CONSTRAINT UNQ_ST_S_ID UNIQUE (S_ID);

How to add a column and make it a foreign key in single MySQL statement?

In mysql, can I add a column and foreign key in the same statement? And what is the proper syntax for adding the fk?
Here is my SQL:
ALTER TABLE database.table
ADD COLUMN columnname INT DEFAULT(1),
FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE;
...and the accompanying error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE' at line 4
Try this:
ALTER TABLE database.table
ADD COLUMN columnname INT DEFAULT(1),
ADD FOREIGN KEY fk_name(fk_column) REFERENCES reftable(refcolumn) ON DELETE CASCADE;
The following query adds a column by alter query and the constraint query makes it a FK in a single mysql query. You can do it like this,
SYNTAX:
ALTER TABLE `SCHEMANAME`.`TABLE1`
ADD COLUMN `FK_COLUMN` BIGINT(20) NOT NULL,
ADD CONSTRAINT `FK_TABLE2_COLUMN` FOREIGN KEY (`FK_COLUMN`)
REFERENCES `SCHEMANAME`.`TABLE2`(`PK_COLUMN`);
EXAMPLE:
ALTER TABLE `USERDB`.`ADDRESS_TABLE`
ADD COLUMN `USER_ID` BIGINT(20) NOT NULL AFTER `PHONE_NUMBER`,
ADD CONSTRAINT `FK_CUSTOMER_TABLE_CUSTOMER_ID` FOREIGN KEY (`USER_ID`)
REFERENCES `USERDB`.`CUSTOMER_TABLE`(`CUSTOMER_ID`);
This can be simplified a bit. You just need to add the "ADD" keyword before "FOREIGN KEY". Adding example below.
ALTER TABLE database.table
ADD COLUMN columnname INT DEFAULT(1),
ADD FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE;
You can use it.
ALTER TABLE database.table
ADD COLUMN columnname INT DEFAULT(1);
ALTER TABLE database.table add FOREIGN KEY (fk_name) REFERENCES reftable(refcolumn) ON DELETE CASCADE;