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

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.

Related

Can FOREIGN KEY be omitted in PostgreSQL when using REFERENCES?

I'm wondering if there's any (maybe subtle) difference between these two SQL statements:
CREATE TABLE profiles (
profile_id SERIAL PRIMARY KEY NOT NULL,
bio TEXT,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(user_id)
);
and
CREATE TABLE profiles (
profile_id SERIAL PRIMARY KEY NOT NULL,
bio TEXT,
user_id INTEGER NOT NULL REFERENCES users(user_id)
);
I've noticed that when I create a table in Postico with the first notation, but look at the DDL of the created profiles table later, the FOREIGN KEY is removed and I end up with the shorter second notation.
Create table with FOREIGN KEY:
DDL view doesn't show FOREIGN KEY:
So, I'm wondering (and seeking confirmation) that the two statements are in fact 100% equivalent or if there are some subtle differences in what they do to the DB.
Any pointer to official resources (and maybe also how that differs from MySQL) would be appreciated.
The two samples you show do the same thing, just with a different syntax.
The first method is called table constraint, the second column constraint, but the latter name is somewhat misleading because the constraint is on the table as well.
The main difference is that the column constraint syntax is shorter, but cannot be used for all constraints: if you have for example a primary key that contains two columns, you have to write it in the table constraint syntax.
DDL view doesn't show FOREIGN KEY
DDL view created by unknown third-party tool in not an argument.
See fiddle. Foreign key exists in both cases. Moreover, I do not see the result difference for both DDL queries.
PS. As a recommendation - always specify the constraint name explicitly. What if you need to delete it? It is problematic without the constraint name...
In PostgreSQL, you define a foreign key through a foreign key constraint. A foreign key constraint indicates that values in a column or a group of columns in the child table match with the values in a column or a group of columns of the parent table. We say that a foreign key constraint maintains referential integrity between child and parent tables.
This may explain to you better or you can read about Foreign Keys documentation .

Adding FOREIGN KEY Constraint in column

How can i add FOREIGN KEY constraint in the referrer_id(same as profile id) column? Since the column name contains parentheses it is throwing error
ALTER table Referrals ADD Constraint fk_referrer_ID
FOREIGN KEY(referrer_id(same as profile id)) REFERENCES Profiles(profile_id)
ERROR: Incorrect syntax near 'referrer_id(same as profile id)'.
Use below query, column name delimited by brackets ([ ]):
ALTER table Referrals ADD Constraint fk_referrer_ID FOREIGN KEY([referrer_id(same as profile id)]) REFERENCES Profiles(profile_id)
I believe referrer_id is your column name
ALTER table Referrals ADD Constraint fk_referrer_ID
FOREIGN KEY(referrer_id) REFERENCES Profiles(profile_id)
You don't to specify that it is same as profile id in foreign key, REFERENCES Profiles(profile_id) conveys that message to compiler.
or if you really have a ugly column name(referrer_id(same as profile id)) then you need to use square brackets to escape the special characters present in your column name
ALTER table Referrals ADD Constraint fk_referrer_ID
FOREIGN KEY([referrer_id(same as profile id)]) REFERENCES Profiles(profile_id)

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);

Add new column with foreign key constraint in one command

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);

Trouble understanding SQL (Oracle) create table code

I am aware of Oracle's create table syntax
CREATE TABLE MyTable(
id int primary key,
...
);
This will create a table called MyTable with an int primary key. So, nothing new here.
but I am having difficulties understanding the following query:
CREATE TABLE departament (
cod_dept INTEGER CONSTRAINT dept_key PRIMARY KEY,
dept_name CHAR(15) NOT NULL,
admission DATE NOT NULL,
localization CHAR(20))
When I look up on Oracle's SQL Developer software on departement's table, I can see 4 columns: cod_dept, dept_name, admission and localization. On the constraints tab, I can also see dept_key, but I am confused as to what this might mean. What is dept_key purpose here?
Edit
Ok, seems it is a way to define the name of the constraint you're adding to the table. My next question is why don't you just call it the same name as the primary key column? From what I've seen it seems Oracle by default just creates a random name for the constraint!
Thanks
When you write id int primary key, Oracle will create a primary key constraint to ensure uniqueness of primary key values. All constraints have names, so in this case Oracle assigns an autogenerated name to this constraint. But you can set a name of this constraint explicitly using the CONSTRAINT syntax:
cod_dept INTEGER CONSTRAINT dept_key PRIMARY KEY
This name may be used later to refer to the constraint, for example, to delete or modify it:
ALTER TABLE department DROP CONSTRAINT dept_key;
EDIT:
Constraint names are unique across the schema, so Oracle can't just use the name of primary key column as a constraint name.
Primary keys can be explicitly be named. dept_key is just a name.
dept_key is the name of the primary key constraint. That means cod_dept is the unique identifier for your table, the mechanism for identifying a row, and so it can only have one occurrence of any given value.
That is the constraint you created representing the primary key.
A table is made up of:
Columns (where the data lives)
Indexes (indexed copies of the data used for faster searching)
Constraints (rules about what data can be in the table, including PK, FK, and check constraints).
dept_key is the name of the constraint. You specified the name here : "INTEGER CONSTRAINT dept_key PRIMARY KEY," so it will create a constraint with the name dept_key.
Another syntax for the same would be to write the following after your CREATE TABLE instruction.
ALTER TABLE department
ADD CONSTRAINT dept_key PRIMARY KEY (cod_dept)
dept_key is then the name of the constraint you created to be the primary key for this table. In order for a database engine to know the primary key, and to index it for fastest results and so forth, it needs to create a known constraint that is indexed. Here, it is you who has given the name which is dept_key.
For you kind information, it is often seen to write PK_[table name] for primary keys constraints and FK_[current_table_name]_[foreign_table_name] for foreign keys constraints.
Hope this helps! =)
I think whenever we create a Primary Key value then by default Oracle will crate constraint for it with the same name but it looks like that u are creating constraint with some other name.
Thank You