Add new column with foreign key constraint in one command - sql

I am trying to add a new column that will be a foreign key. I have been able to add the column and the foreign key constraint using two separate ALTER TABLE commands:
ALTER TABLE one
ADD two_id integer;
ALTER TABLE one
ADD FOREIGN KEY (two_id) REFERENCES two(id);
Is there a way to do this with one ALTER TABLE command instead of two? I could not come up with anything that works.

As so often with SQL-related question, it depends on the DBMS. Some DBMS allow you to combine ALTER TABLE operations separated by commas. For example...
Informix syntax:
ALTER TABLE one
ADD two_id INTEGER,
ADD CONSTRAINT FOREIGN KEY(two_id) REFERENCES two(id);
The syntax for IBM DB2 LUW is similar, repeating the keyword ADD but (if I read the diagram correctly) not requiring a comma to separate the added items.
Microsoft SQL Server syntax:
ALTER TABLE one
ADD two_id INTEGER,
FOREIGN KEY(two_id) REFERENCES two(id);
Some others do not allow you to combine ALTER TABLE operations like that. Standard SQL only allows a single operation in the ALTER TABLE statement, so in Standard SQL, it has to be done in two steps.

In MS-SQLServer:
ALTER TABLE one
ADD two_id integer CONSTRAINT fk FOREIGN KEY (two_id) REFERENCES two(id)

In MS SQL SERVER:
With user defined foreign key name
ALTER TABLE tableName
ADD columnName dataType,
CONSTRAINT fkName FOREIGN KEY(fkColumnName)
REFERENCES pkTableName(pkTableColumnName);
Without user defined foreign key name
ALTER TABLE tableName
ADD columnName dataType,
FOREIGN KEY(fkColumnName) REFERENCES pkTableName(pkTableColumnName);

For SQL Server it should be something like
ALTER TABLE one
ADD two_id integer constraint fk foreign key references two(id)

In Oracle :
ALTER TABLE one ADD two_id INTEGER CONSTRAINT Fk_two_id REFERENCES two(id);

2020 Update
It's pretty old question but people are still returning to it I see. In case the above answers did not help you, make sure that you are using same data type for the new column as the id of the other table.
In my case, I was using Laravel and I use "unsigned integer" for all of my ids as there is no point of having negative id LOL.
So for that, the raw SQL query will change like this:
ALTER TABLE `table_name`
ADD `column_name` INTEGER UNSIGNED,
ADD CONSTRAINT constrain_name FOREIGN KEY(column_name) REFERENCES foreign_table_name(id);
I hope it helps

PostgreSQL DLL to add an FK column:
ALTER TABLE one
ADD two_id INTEGER REFERENCES two;

For DB2, the syntax is:
ALTER TABLE one ADD two_id INTEGER FOREIGN KEY (two_id) REFERENCES two (id);

ALTER TABLE TableName
ADD NewColumnName INTEGER,
FOREIGN KEY(NewColumnName) REFERENCES [ForeignKey_TableName](Foreign_Key_Column)

You can do it like below in SQL Server
ALTER TABLE one
ADD two_id int foreign key
REFERENCES two(id)

If you also need to add default values in case you already have some rows in the table then add DEFAULT val
ALTER TABLE one
ADD two_id int DEFAULT 123,
FOREIGN KEY(two_id) REFERENCES two(id);

Try this:
ALTER TABLE product
ADD FOREIGN KEY (product_ID) REFERENCES product(product_ID);

For SQL Server with constraint name
ALTER TABLE one
ADD two_id INT NOT NULL,
CONSTRAINT FK_name FOREIGN KEY (two_id) REFERENCES two(id);

Related

ALTER COLUMN Command doesn't work SQL Server

i want to add to a primary key in one table a references to the primary key of another table.
my code:
CREATE TABLE[payment]
(ID int Primary key)
CREATE TABLE [tab]
(ID int Primary key references tab2(ID))
Alter Table payment
alter column ID
ADD constraint fk_payment
references tab(ID)
i get the error that the syntax near constraint is wrong, but i don't know what to change
because of the not changeable order of the table Alter table is the only option. to reference from one table to the other doesn't work cause I've references from that table to another one already.
i need two one-to-one-relations from one table to another
If you want to add a FK constraint, just use this code:
ALTER TABLE dbo.payment
ADD CONSTRAINT fk_payment
FOREIGN KEY(ID) REFERENCES dbo.tab(ID)
You don't need to alter the column or table - just add the constraint

Oracle SQL-ALTER TABLE Error

I've been looking over the following SQL code for awhile and just can't seem to find the problem. I'm relatively new to SQL, so I'm sure it's just something I'm overlooking. The error message I get is: ORA-01735: Invalid ALTER TABLE option.
Code:
ALTER TABLE PATIENT
(
ADD CONSTRAINT PProfileForeignKey
FOREIGN KEY (pProfileID) REFERENCES PATIENT_PROFILE(Profile_ID),
ADD CONSTRAINT InsForeignKey
FOREIGN KEY (pInsID) REFERENCES INSURANCE(Insurance_ID)
ON DELETE SET NULL
);
I have triple checked to make sure the foreign key column names and the referenced column names are correct.
seems The parentheses are in wrong place
ALTER TABLE PATIENT
ADD (CONSTRAINT PProfileForeignKey
FOREIGN KEY (pProfileID) REFERENCES PATIENT_PROFILE(Profile_ID),
CONSTRAINT InsForeignKey
FOREIGN KEY (pInsID) REFERENCES INSURANCE(Insurance_ID)
ON DELETE SET NULL);

Is there any way to make the following sql query work?

I am trying to create two tables using the following SQL:
create table student(sid char(20) primary key,name char(20),age int,hours char(10) references courses(cid));
create table courses(cid char(10),cname char(10),grader char(20) references student(sid));
However I get the following error:
1: ERROR: relation "courses" does not exist
3: ERROR: relation "student" does not exist
Is there any way or syntax which can solve this problem?
You would need to create the tables first (without REFERENCES clause). After that create your foreign keys manually by statement ALTER TABLE mytable ADD CONSTRAINT mytablefk FOREIGN KEY... But first I'd consider if there really is a relationship from table courses to table student!
Rather than creating the Foreign Key constraints at the same time as the tables with the References short-hand, you can add one or both of them afterwards with an Alter Table Add Constraint command. See the Alter Table page in the PostgrSQL manual here.
As mu pointed out, the target of a foreign key has to have a Unique or Primary Key constraint defined, so I've added that on the cid column in the example below.
In your case, it could look something like this:
create table student(sid char(20) primary key,name char(20),age int,hours char(10));
create table courses(cid char(10) primary key,cname char(10),grader char(20));
Alter Table student Add Constraint fk_student_hours_cid Foreign Key (hours) References courses(cid);
Alter Table courses Add Constraint fk_courses_grader_sid Foreign Key (grader) References student(sid);

What is the Difference between adding Column as Foreign Key and as a Constraint

I am Using Oracle 10g. I am Adding new column deptId to my UserList Table where I use deptId column as Foreign key which references other table Column Departments.DepartmentId
Is there Difference between adding foreign key as constraint and First Query
Query1
ALTER TABLE UserList
ADD FOREIGN KEY (DeptId)
REFERENCES Departments(DepartmentId)
Query2
ALTER TABLE UserList
ADD CONSTRAINT fk_DeptId FOREIGN KEY (DeptId)
REFERENCES Departments(DepartmentId)
There is no difference except in your use of the optional "CONSTRAINT" and constraint name clause.
There are two kinds of constraint definition: inline and out of line. The former operates on a column as part of the column definition, and hence does not need to name the DeptID column. The latter is part of the table definition and therefore does.
Both of your examples are out of line constraints, but you have not named the constraint in the former case, which is a bad practice:
http://docs.oracle.com/cd/E18283_01/server.112/e17118/clauses002.htm#g1053592
The second syntax allows you to name your constraint. The first doesn't.
ALTER TABLE [dbo].[UserList] WITH NOCHECK ADD CONSTRAINT [fk_DeptId] FOREIGN KEY([DeptId])
REFERENCES [dbo].[Departments] ([DepartmentId])
No, there is no difference in both of your queries.But you to name the foreign key constraints names . You can use the above query.

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;