Create table - foreign key
Hi all.I started to create tables in SQL.
My question is about the best way to refer to a column as a foreign key.
Example:
A simple way to make a primary key field.
CREATE table emp (emp_id number (3.0) not null not the primary key)
This will create emp_id as the primary key of the table emp.
If there is another field, dept_no and this must be the foreign key.
CREATE table emp (emp_id number (3.0) not null primary key, dept_no?)
So my question is what is the most easy, less complicated way to make the dept_no field a foreign key to the emp table
Thank you
GtG
Try like this...
CREATE table emp (emp_id number (3.0) not null primary key, done dept_no refers to table_name (coluimn_name));
-Clément
Tags: Database
Similar Questions
-
How to create a foreign key constraint on a table nested column
Dear Experts,
I create 2 tables using the object type. the VESSEL_PARAM table contains the list of the parameters allowed.
The table VESSEL_TYPE containe single item we list some parameters.
On this table, I love the column VESSEL_PARAM table VESSEL_PARAM to check if the settings are and the reference value is allowed.
How to create a foreign key?
Here my script that generates this runtime error: 00904. 00000 - '% s: invalid identifier' on this line
ALTER TABLE VESSEL_PARAM_TAB ADD CONSTRAINT FK_VESSEL_TYPE FOREIGN KEY (NAME, DATA_VALUE)
REFERENCES VESSEL_PARAM (PARAM_NAME, LIST_PARAM_VALUE. DATA_VALUE)
Thank youCREATE OR REPLACE TYPE OBJ_PARAM_VALUE AS OBJECT ( DATA_VALUE VARCHAR2(20) ,DESCRIPTION VARCHAR2(125) ) NOT FINAL; / CREATE OR REPLACE TYPE LIST_PARAM_VALUE AS TABLE OF OBJ_PARAM_VALUE; / -- derive object subtype from object supertype CREATE OR REPLACE TYPE OBJ_PARAM_NAME UNDER OBJ_PARAM_VALUE ( NAME VARCHAR2(30) )NOT FINAL; / CREATE OR REPLACE TYPE LIST_PARAM_NAME AS TABLE OF OBJ_PARAM_NAME; / Prompt create table VESSEL_PARAM; CREATE TABLE VESSEL_PARAM ( PARAM_NAME VARCHAR2(20) NOT NULL ,PARAM_DESC VARCHAR2(125) ,PARAM_VALUE LIST_PARAM_VALUE ,CONSTRAINT PK_VESSEL_PARAM PRIMARY KEY (PARAM_NAME) ) NESTED TABLE PARAM_VALUE STORE AS PARAM_VALUE_TAB TABLESPACE CMS_ADMDATA; / ALTER TABLE PARAM_VALUE_TAB ADD CONSTRAINT UN_PARAM_VALUE_TAB UNIQUE (DATA_VALUE); / SHOW ERROR; Prompt create table CMS_ADM.VESSEL_TYPE; CREATE TABLE CMS_ADM.VESSEL_TYPE ( VESSEL_TYPE VARCHAR2(20) NOT NULL ,VESSEL_DESC VARCHAR2(125) ,VESSEL_PARAM LIST_PARAM_NAME ,CONSTRAINT PK_VESSEL_TYPE PRIMARY KEY (VESSEL_TYPE) -- ,CONSTRAINT FK_VESSEL_TYPE FOREIGN KEY (VESSEL_PARAM) -- REFERENCES VESSEL_PARAM (PARAM_NAME) ) NESTED TABLE VESSEL_PARAM STORE AS VESSEL_PARAM_TAB TABLESPACE CMS_ADMDATA; / ALTER TABLE VESSEL_PARAM_TAB ADD CONSTRAINT UN_VESSEL_PARAM_TAB UNIQUE (NAME); ALTER TABLE VESSEL_PARAM_TAB ADD CONSTRAINT FK_VESSEL_TYPE FOREIGN KEY (NAME,DATA_VALUE) REFERENCES VESSEL_PARAM (PARAM_NAME,LIST_PARAM_VALUE.DATA_VALUE) / SHOW ERROR;
SalvatoreCould you please indicate your answer as correct if you judge them correct.
Best regards
Mohamed Houri
-
Can we create a foreign key by using built in functions?
Hi all
I'm in the need to create a foreign key referring to an expression of a column in another table.
For example, I try below and I got some errors.
CREATE TABLE TABLE_A
(
student_id VARCHAR2 (30),
student_name VARCHAR2 (100),
CONSTRAINT fk_A FOREIGN KEY (student_id) REFERENCES TABLE_B (UPPER (column_name))
);
Please suggest if it is possible that a foreign key could be made in an expression or not?
2761969 wrote:
Hi all
I'm in the need to create a foreign key referring to an expression of a column in another table.
For example, I try below and I got some errors.
CREATE TABLE TABLE_A
(
student_id VARCHAR2 (30),
student_name VARCHAR2 (100),
CONSTRAINT fk_A FOREIGN KEY (student_id) REFERENCES TABLE_B (UPPER (column_name))
);
Please suggest if it is possible that a foreign key could be made in an expression or not?
No - it isn't.
You can, however, create a VIRTUAL column in the parent table, and then create a foreign key that references.
-
I'm creating a foreign key between two tables with the following command
ALTER TABLE core_business.cb_insured_person ADD)
CONSTRAINT fk_present_prov_cty_cbi
FOREIGN KEY (present_province_code, present_city_code)
General_information.cb_city (province_code, city_code) NOVALIDATE REFERENCES);
I have the DBA privilege and I used to do this work, but when I run stated above I give error of insufficient privileges, how can I solve this problem...
CREATE THE TABLE CORE_BUSINESS. CB_INSURED_PERSON
(
NUMBER OF IP_REGION_FO_CODE (4, 0) NOT NULL
, IP_CHECK_DIGIT VARCHAR2 (1 BYTE) NOT NULL
NUMBER OF IP_SERIAL_NO (6, 0) NOT NULL
NUMBER OF EO_CODE (6: 0)
NUMBER OF REGISTRATION_CODE (2, 0)
TITLE VARCHAR2 (5 BYTE)
, VARCHAR2 (35 BYTE) NAME NOT NULL
OLD_NIC_NO VARCHAR2 (13 BYTE)
NEW_NIC_NO VARCHAR2 (15 BYTE)
VARCHAR2 (6 BYTE) FAMILY_CODE
SEX VARCHAR2 (1 BYTE)
RELATIVE_NAME VARCHAR2 (35 BYTE)
NUMBER OF RELATIONSHIP_CODE (3, 0)
DATE_OF_BIRTH DATE
DATE_OF_JOINING_EOBI DATE
PRESENT_ADDRESS VARCHAR2 (100 BYTE)
NUMBER OF PRESENT_PROVINCE_CODE (2, 0)
NUMBER OF PRESENT_CITY_CODE (5, 0)
NUMBER OF PRESENT_POST_CODE (5, 0)
PRESENT_TELEPHONE VARCHAR2 (30 BYTE)
CONSTRAINT PK_CB_INSURED_PERSON PRIMARY KEY
(
IP_REGION_FO_CODE
IP_CHECK_DIGIT
IP_SERIAL_NO
)
ENABLE
)
LOGGING
TABLESPACE "EOBI.
PCTFREE 10
INITRANS 1
STORAGE
(
747634688 INITIAL
MINEXTENTS 1
MAXEXTENTS 2147483645
USER_TABLES KEEP
);
CREATE TABLE GENERAL_INFORMATION. CB_CITY
(
NUMBER OF PROVINCE_CODE (2, 0) NOT NULL
NUMBER OF CITY_CODE (5, 0) NOT NULL
, NAME VARCHAR2 (25 BYTE) NOT NULL
AREA_CODE VARCHAR2 (6 BYTE)
VARCHAR2 (1 BYTE) STATUS NOT NULL
, CREATED_BY VARCHAR2 (10 BYTE) NOT NULL
CREATED_DATE DATE NOT NULL
, MODIFIED_BY VARCHAR2 (10 BYTE) NOT NULL
MODIFIED_DATE DATE NOT NULL
NUMBER OF DIVISION_CODE (5, 0)
NUMBER OF DISTRICT_CODE (5, 0)
CONSTRAINT PK_PRV_CTY PRIMARY KEY
(
PROVINCE_CODE
CITY_CODE
)
ENABLE
)
LOGGING
TABLESPACE "EOBI.
PCTFREE 10
INITRANS 1
STORAGE
(
81920 INITIAL
MINEXTENTS 1
MAXEXTENTS 2147483645
DEFAULT USER_TABLES
);
CREATE A UNIQUE GENERAL_INFORMATION INDEX. CB_CITY_PK ON GENERAL_INFORMATION. CB_CITY (NAME ASC)
LOGGING
TABLESPACE "EOBI_IDX".
PCTFREE 10
INITRANS 2
STORAGE
(
65536 INITIAL
MINEXTENTS 1
MAXEXTENTS 2147483645
DEFAULT USER_TABLES
);
CREATE A UNIQUE GENERAL_INFORMATION INDEX. CB_CITY_UK ON GENERAL_INFORMATION. CB_CITY (CSA, CSA CITY_CODE PROVINCE_CODE)
LOGGING
TABLESPACE "EOBI_IDX".
PCTFREE 10
INITRANS 2
STORAGE
(
65536 INITIAL
MINEXTENTS 1
MAXEXTENTS 2147483645
DEFAULT USER_TABLES
);The schema CORE_BUSINESS has REFERENCES and privileges SELECT on the table that you want to refer to the foreign key constraint?
-
Maker of SQL data - how to create the foreign key in the relationship 1 to 1?
Hi guys...
I had 2 tables...
Table 1 - CFR
-----------------------
CFR_ID = primary key
Table 2 - USER_PLAN
----------------------------
User_id = primary key
PLAN_ID ARGUMENT,
CFR_ID = reference foreign key (table 1)
Business flow go like this...
table insdie CFR, it contains all the documents / transactions of a particular plan user. each time a new transaction occurs for a plan/user, a new CFR_ID / row will be generated.
After that, the newly generated for the new line, CFR_ID will be updated to the CFR_ID in USER_PLAN
Thus, there is always a 1 to 1 relationship between table 2, no matter how much CFR_ID is generated for a particular USER_PLAN. as the CFR_ID in the USEr_plan table will always be the last being produced within the table of the CFR.
However, in the Data Modeler, I am unable to create this foreign key relationship... NO idea how create a 1 on 1 relationship of foreign key? or there is no way...
Thank you and best regards,
NoobHey Noob,
Yes, that's correct.
Best regards
Philippe -
Create a foreign key constraint against a different schema
Hi all
I use the oracle 10g r2 on windows 2003 server database.
I have a table in the HRMS as STAFF.
I have another INVENTORY schema, where I want to access a column as a foreign key in HRMS. STAFF (STAFF_ID).
What exactly I have to grant so this diagram of the INVENTORY will be able to create a referential constraint?connect hrms/hrms@orcl grant select on STAFF to INVENTORY; connect inventory/inventory@orcl alter table inv_details add constraint fk_inv_hr_staff foreign key (staff_id) references HRMS.STAFF(STAFF_ID); Error report: SQL Error: ORA-00942: table or view does not exist 00942. 00000 - "table or view does not exist"
Kind regards.You must also grant the privilege of REFERENCES.
See privileges in table 18-2 at http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9013.htm#BGBCIIEG
Hemant K Collette
-
Please, help me to create the foreign key.
Oracle 10g using sqldbx
I tried everything I could but all in vain.
(Folder) CREATE TABLE
FolderId INT NOT NULL PRIMARY KEY,
FolderName varchar (255) NOT NULL,
CreatedBy varchar (255) NOT NULL,
CreateDate TIMESTAMP NOT NULL
)
(Document) CREATE TABLE
DocumentID INT NOT NULL PRIMARY KEY,
FolderId INT NOT NULL,
DocumentTitle varchar (255) NOT NULL,
DocumentAuthor varchar (255) NOT NULL,
CreateDate TIMESTAMP NOT NULL
)
Document of ALTER TABLE ADD CONSTRAINT fkdocument FOREIGN KEY (document.folderid) REFERENCES (the folder. FOLDERID)
the last statement says invalid folder name. Help, pleaseHello
Welcome to the forum!
See the Manual of the SQL language for the correct syntax:
ALTER TABLE document ADD CONSTRAINT fkdocument FOREIGN KEY (folderid) REFERENCES folder (FOLDERID) ;
Thanks for posting your code! It is very useful.
Have you seen the FAQ forum yet? {message: id = 9360002} -
Hai
I have two table
Nrgp_main
Nrgpno here is primary ky
And NRGP_ITEM
I need NRGPno as foreign key I dropped it and I now I need to recreate
I have an error inIt
ALTER table nrgp_item add constraint
FK_NRGPITA foreign key (nrgpno) references nrgp_main (nrgpno);
Error
FK_NRGPITA foreign key (nrgpno) references nrgp_main (nrgpno)
*
ERROR on line 2:
ORA-02270: no unique or primary key corresponding to this column list
Concerning
sRikkanthHello
You do something like that?
SQL> create table a(n number primary key); Table created. SQL> create table b(n number); Table created. SQL> alter table b 2 add constraint 3 fk_n foreign key(n) references a(n); Table altered. SQL> alter table b 2 drop constraint fk_n; Table altered. SQL> alter table b 2 add constraint 3 fk_n foreign key(n) references a(n); Table altered.
Twinkle
-
Creating a relationship creates no foreign key attribute (s)
Hello
In my logical model, I have an entity supertype/subtype with 2 subtypes with no own attributes (each subtype has only 1: m relationship). When I create the relationship of 1:m of subtype to another entity (the entity-side m), there is no attribute generated FK. I found a trick to create the relationship first of Supertype in the other entity, and then reconnect it to the subtype. Then, the foreign key is generated (I see that in the dialogue relationship property > FK attributes).
So I guess it's a bug.
Robert
Hi Robert,.
Thanks for reporting the issue that is fixed in 4.1.2 code
Philippe
-
How to fill out the table foreign key to the primary key form
Hi all
I'm stuck in this problem for 3 days, and I'm about to research and implement solutions on the internet.
I have two tables
create table prim (a number primary key, b varchar2 (100));
create table CHILD (a number references (a) prim, varchar2 (100)) c;
I created a page for PRIM table.
= page name form on PRIM2
I have manually two columns for the CHILD table to know
P26_A_1 (for the primary key in the CHILD table)
P26_C (for the column in the CHILD Table c)
now when the user clicks on the button CREATE, a row must be inserted into the child table.
I want to assign the P26_A to P26_A_1 during the validation process, so that a line must be inserted into the PRIM table as well as in the CHILD table.
How to do this?
I downloaded my application page in https://apex.oracle.com
my workspace identifiers are inferior to
name of the workspace = IMBERT
username = demo
password = demo
kindly guide me.
Thank you.
Hello
I created a new page (page 30) similar to your page and added the insertion of the child. It just check the page and code. It works now, when you insert the prim file is triggered a second trial which inserts the child record manually.
On page 26 it was some sort of mistake, was easier to create a new as it was almost a standard form.
Concerning
Bottom
-
missing closing parenthesis when creating foreign key
Schema1.Table1 ALTER TABLE ADD (CONSTRAINT test_FK
FOREIGN KEY (test)
REFERENCES schema1.table2 (test)
USING INDEX TABLESPACE indextb);
With the HELP of INDEX TABLESPACE indextb)
*
ERROR on line 4:
ORA-00907: lack of right parenthesis
Please help, I tried several times. But I still get the same error
Delete the TABLESPACE of INDEX clause to HELP. It is not valid here.
Create a foreign key does not implicitly create an index. Since there is no index, there is no tablespace to worry. As a general rule, you don't want to create an index to support the how foreign key constraint there a sense perhaps specify a tablespace.
Justin
-
Question: Is foreign key references to a different column in the same table
Hello
I'm not grasp this concept. Would you be able to provide the logic how and why you need to create a foreign key that references a column of the same table?
For example, referencing the schema, SupervisorNo @ here is a FOREIGN KEY to the "EmpNo" column in the same table.
EMPLOYEE (EmpNo, title, Fname, Lname, phone, Email, date of birth, sex, salary, HireDate, OutNo, SupervisorNo @)
Why would you want to do this and how can it be used? If you are filling out the data in the table, and this constraint is enabled, you will not be able to load whatever it is because the "EmpNo" column will be empty.
Any input you can provide me with this would be greatly appreciated. Thank you!
His name
Self-referential integrity constraints
Lets say that we have the table emp with emp_no and mgr_no columns.
Now all managers should also be an employee too. How can I check this when inserting data into this table? I applied auto integrity constraint. It would help me to make sure no handler (doesn't mean no mgr_no) must be registered if this Manager is not an employee of this organization. Which means, I won't be able to enter any mgr_no in the column until and unless that the same employee also is an employee (emp_no from the same table).
Check the link as well below.
Thank you
Ishan
-
Foreign keys of a logical Table
Hi all
I want to know in what scenarios, we create the foreign key of a logical Table. Once we have create the foreign key for the logical table, this means he automatically substitute if joins are here.
Physical table A, B (without physical joins)
Logic table A, B (B (Sun)--> (Fact) A logical join)
created the foreign key in the logical table A with b. (A.1 = B.1)
The RPD will generate sql with A.1 = B.1 join condition for the reports.
I tried to create the logical foreign key for table logical, I couldn't see any option from the table. Here is his
http://Tinypic.com/r/jq1gkz/6
Thank you
ViratIn general when we go to the complex joins in the physical layer, we opt for logical foreign key joins in layer MDB, best examples is SCD Type II.
Physical table A, B (without physical joins)
--> You must have a physical join so that it can be override by layer MDBcreated the foreign key in the logical table A with b. (A.1 = B.1) the RPD will generate sql with A.1 = B.1 join condition for the reports.
--> Yes, you can see this join in the physical BI query.I tried to create the logical foreign key for table logical, I couldn't see any option from the table. Here is his
--> 2 cases: 1) you must remove existing logical joins 2) you could not have involved physical layer.Hope this helps
Let me know for questionsPublished by: Srini VIEREN on 18 January 2013 13:29
BTW: You got a very good reputation, why don't update you your profile to see your name instead of a number
Published by: Srini VIEREN on 18 January 2013 13:29
-
Questions about the creation of a foreign key on a table
Hello @ll,
during an update of the database, I lost a foreign key between two tables. The tables are called werteart and werteartarchiv_pt. Because of its size, werteartarchiv_pt is a partitioned table. The missing foreign key was a constraint on werteartarchiv_pt table referencing werteart.
Some statistics on the size of the mentioned tables:
werteart 22 MB
werteartarchiv_pt 223 GB
werteartarchiv_pt (Index) 243 GB
I tried to create the foreign key again but it failed with the following error (apologies for the German error message):
sqlplus ORA-00604: Fehler auf rekursiver SQL-ebony 1
sqlplus ORA-01652: Temp-Segment kann nicht um 128 in Tablespace TEMPS00 judgements
The statement that I used:
ALTER table werteartarchiv_pt
Add constraint werteartarchiv_pt_fk1
foreign key (rail, werteartadresse, merkmale)
Reference werteart (rail, werteartadresse, merkmale)
on delete cascade
at the delayed start can be delayed;
So, the problem seems to be that Oracle needs a lot of temporary tablespace to generate foreign key and I do not know how and why.
My questions now are, and I hope that someone is there who can answer all or part of it:
(1) why Oracle should temporary tablespace to create the foreign key? The foreign key uses the same columns as the primary key.
is 2 (a) possible to change the statement without using the temporary tablespace?
2 (b) if it is not possible to avoid the use of temporary storage space, is there a formula how to calculate the necessary temporary tablespace?
(3) is it possible to modify data in tables while the foreign key is created or is the whole table locked during the process?
Any help or advice is appreciated.
Kind regards
BjoernRollinHand wrote:
My questions now are, and I hope that someone is there who can answer all or part of it:(1) why Oracle should temporary tablespace to create the foreign key? The foreign key uses the same columns as the primary key.
Because it is data validation to ensure that the foreign key are violated. If you had specified NOVALIDATE ACTIVATE in its creation then the existing data in the table should be checked and the statement must fill out instantly (future data added is enabled by the constraint).
http://download.Oracle.com/docs/CD/B28359_01/server.111/b28310/general005.htm
Search for "Enable Novalidate constraint State"
-
Hi all
I need to create a table (mytable) filled from 2 different tables, for example, table1 and table2
When the rows of the table (mytable) comes from the first table (table1) columns in mytable (foreign key to the second table) are nulled, when they come (foreign key) column in the second table (table2)
the first table) are cancelled as well.
In terms of performance, architecture is valid, in other words, create a foreign key 2 on mytable and consequently, (the composite foreign key in this table are null according to whether they belong to the first or the second table)?
Thanks in advance for any help
I hope to clearAs promised,
mhouri.world > create table p as select * from all_users; Table created. mhouri.world > alter table p add constraint p_pk primary key (user_id); Table altered. mhouri.world > create table c (user_id references p, name varchar2(30)); Table created. mhouri.world > select min(user_id),max(user_id) from p; MIN(USER_ID) MAX(USER_ID) ------------ ------------ 0 72 mhouri.world > insert into c (user_id, name) values (0, 'test without index'); 1 row created.
Thanks to the autonomous operation I simulates the effect of two users working on the same parent/child table
(a) first of all, without any index covering the FK on the child table
(b) second with a function based index on the FK column (note the desc clause in the definition of the index)
(c) and finally with an index b-tree on the FK columns
case (a)
mhouri.world > declare 2 pragma autonomous_transaction; 3 begin 4 delete from p where user_id = 72; 5 commit; 6 end; 7 / declare * ERROR at line 1: ORA-00060: deadlock detected while waiting for resource ORA-06512: at line 4 mhouri.world > rollback; Rollback complete.
case (b)
mhouri.world > create index fbi_c_fk on c (user_id desc); Index created. mhouri.world > insert into c (user_id, name) values (0, 'test with fbi index'); 1 row created. mhouri.world > declare 2 pragma autonomous_transaction; 3 begin 4 delete from p where user_id = 72; 5 commit; 6 end; 7 / declare * ERROR at line 1: ORA-00060: deadlock detected while waiting for resource ORA-06512: at line 4 mhouri.world > rollback; Rollback complete.
case (c)
mhouri.world > create index btree_c_fk on c (user_id); Index created. mhouri.world > insert into c (user_id, name) values (0, 'test with b-tree index'); 1 row created. mhouri.world > declare 2 pragma autonomous_transaction; 3 begin 4 delete from p where user_id = 72; 5 commit; 6 end; 7 / PL/SQL procedure successfully completed.
Only the index b-tree covered with success the threat of the deadlock in key foreign unidexed
Best regards
Mohamed Houri
Maybe you are looking for
-
Replacing hard drive for Satellite 2450-101
Hi, my laptop hard drive is broken and I need a hard drive replacement for my aging * Satellite 2450-101 * urgent, but I can't find my mannual and another source model support for portable computers. I thought it was a * standard internal 2.5 "IDE *
-
http://forums.Lenovo.com/T5/T400-T500-and-newer-T-series/create-win-8-recovery-media-in-ThinkPad-thi... According to the link above, I can create a backup of the recovery to an external flash drive partition. According to the manual, I can also use t
-
Password bios clear (Compaq CQ-62)
Hello I don't have my code BISO to use my PC. I tried 3 times and got the code: 81918292 Thank you for your help
-
LV2013.1, Win7 I'm an old hand at LabVIEW, but again using the menus of execution. I have a project with several windows, and I want a WINDOWS menu in each window. I am at the beginning of development, and I'm still adding new windows. Rather than du
-
MOU leei oti dn egatastithike sosta eno oti erat sto ti ekana video Hello na kanw?