Hi I am developing a database in Oracle SQL dev, that is trying to access foriegn keys from another table. I am currently working on the ItemOrdered table which I’ve created with the following CREATE statement
CREATE TABLE ItemOrdered(OrderID varchar2(9) REFERENCES Ords(OrderID),
BeltID varchar2(9) REFERENCES BeltID(BeltID),
Quantity varchar(4) NOT NULL,
PRIMARY KEY(OrderID, BeltID))
As you can See I have the following foriegn keys Ords and BeltID.
Now when I try to run the following statement
INSERT INTO ItemOrdered VALUES(401565981,234489212,'2')
It gives me the following error
violated — parent key not found
02291. 00000 — «integrity constraint (%s.%s) violated — parent key not found»
I have provided my Ords CREATE statement if its needed
CREATE TABLE Ords(OrderID varchar2(9) PRIMARY KEY,
CustomerID varchar(9) REFERENCES Customers(CustomerID),
Expected_Delivery_Date date DEFAULT sysdate NOT NULL,
Actual_Delivery_Date date DEFAULT sysdate NOT NULL,
Payment_Due_Date date DEFAULT sysdate NOT NULL,
Order_Date date DEFAULT sysdate NOT NULL, Price Varchar(10),
Order_Placed varchar2(1) CONSTRAINT OrderPlaced
CHECK(Order_Placed IN('Y','N')) NOT NULL,
Order_Confirmed varchar2(1)
CONSTRAINT Order_Confirmed CHECK(Order_Confirmed IN('Y','N')) NOT NULL,
Order_Completed varchar2(1) CONSTRAINT Order_Completed
CHECK(Order_Completed IN('Y','N')) NOT NULL)
And I have also provided my BeltID CREATE statement
CREATE TABLE BeltID(BeltID varchar2(9) PRIMARY KEY,
BeltLengthID varchar2(9) REFERENCES BeltLength(BeltLengthID),
ColourID varchar2(9) REFERENCES Colour(ColourID),
DesignID varchar2(9) REFERENCES Design(DesignID),ComponentID varchar2(9) REFERENCES Component(ComponentID))
I don’t seem to quite understand why I am getting this error. Is there an clear explanation why?
Here is the http link of what I am trying to do.
link text
Categories
- 385.5K All Categories
- 5.1K Data
- 2.5K Big Data Appliance
- 2.5K Data Science
- 453.4K Databases
- 223.2K General Database Discussions
- 3.8K Java and JavaScript in the Database
- 47 Multilingual Engine
- 606 MySQL Community Space
- 486 NoSQL Database
- 7.9K Oracle Database Express Edition (XE)
- 3.2K ORDS, SODA & JSON in the Database
- 585 SQLcl
- 4K SQL Developer Data Modeler
- 188K SQL & PL/SQL
- 21.5K SQL Developer
- 46 Data Integration
- 46 GoldenGate
- 298.4K Development
- 4 Application Development
- 20 Developer Projects
- 166 Programming Languages
- 295K Development Tools
- 150 DevOps
- 3.1K QA/Testing
- 646.7K Java
- 37 Java Learning Subscription
- 37.1K Database Connectivity
- 201 Java Community Process
- 108 Java 25
- 8.1K Embedded Technologies
- 22.2K Java APIs
- 138.3K Java Development Tools
- 165.4K Java EE (Java Enterprise Edition)
- 22 Java Essentials
- 176 Java 8 Questions
- 86K Java Programming
- 82 Java Puzzle Ball
- 65.1K New To Java
- 1.7K Training / Learning / Certification
- 13.8K Java HotSpot Virtual Machine
- 94.3K Java SE
- 13.8K Java Security
- 208 Java User Groups
- 25 JavaScript — Nashorn
- Programs
- 667 LiveLabs
- 41 Workshops
- 10.3K Software
- 6.7K Berkeley DB Family
- 3.6K JHeadstart
- 6K Other Languages
- 2.3K Chinese
- 207 Deutsche Oracle Community
- 1.1K Español
- 1.9K Japanese
- 474 Portuguese
![]()
When trying to create a Foreign key (ou_fk) on table [FACT], referencing table [OU] which has a primary key (ou_pk), I get the error «ORA_02298: Cannot validate (SCHEMA.OU_FK) — parent keys not found». Both tables have a related column that the keys reference. Same result with trying to create other foreign keys on [FACT]to different tables. What is wrong here?
Comments
-

Would it be possible for you to post the statement you are using to create the foreign key ?
-

Are the tables have data?
If no, then try to truncate them and add your foreign key again. -

I am using OEM to create the Foreign keys. The generated SQL follows:
ALTER TABLE «SCHEMA».»FACT»
ADD (CONSTRAINT «OU_FK» FOREIGN KEY(«FUNDS_CENTER»)
REFERENCES «SCHEMA».»OU»(«FUNDS_CENTER»))All tables have data.
Hope this can help find a solution.
-

then there are some values that doesn’t match with primary key values in parent table. Check for this data.
-

APC
Member Posts: 11,316 Bronze CrownTo do this:
If you don’t have an EXCEPTIONS table create one by running the UTLEXCPT.SQL script which you’ll find in $ORACLE_HOME/rdbms/admin
Then rerun the statement like this
ALTER TABLE "SCHEMA"."FACT"
ADD (CONSTRAINT "OU_FK" FOREIGN KEY("FUNDS_CENTER")
REFERENCES "SCHEMA"."OU"("FUNDS_CENTER"))
EXCEPTIONS INTO <<your EXCEPTIONS table >>That will give you the ROWIDs for the errant rows, which will allow you to find which keys you are missing in the parent table.
I don’t think the OEM Constraints Wizard allows us to use this clause. Someone please disabuse me if I’m wrong.
Cheers, APC
-

<<Someone please disabuse me if I’m wrong.>>
UTLEXCPT.SQL uses physical rowids. Therefore it can accommodate rows from conventional tables but not from index-organized tables.UTLEXPT1.SQL uses universal rowids, so it can accommodate rows from both heap-organized and index-organized tables. If you create your own exceptions table, then it must follow the format prescribed by one of these two scripts. If you are collecting exceptions from index-organized tables based on primary keys (rather than universal rowids), then you must create a separate exceptions table for each index-organized table to accommodate its primary key storage. You create multiple exceptions tables with different names by modifying and resubmitting the script.
-

Thanks for the helpful suggestions. Problem was due to data integrity. The table which the foreign key was linking to needed to be updated for new records.
This discussion has been closed.
Содержание
- ORA-02291: Integrity Constraint-Parent Key Not Found (WWV_FLOW_FND_GU_INT_G_FK) — When Importing A Workspace In APEX — ORDS(with Weblogic) (Doc ID 1992236.1)
- Applies to:
- Symptoms
- Cause
- To view full details, sign in with your My Oracle Support account.
- Don’t have a My Oracle Support account? Click to get started!
- Oracle / PLSQL: ORA-02291 Error Message
- Description
- Cause
- Resolution
- Option #1
- ORA-02291: Integrity Constraint,parent Key Not Found Error Code: 2291 Call: Insert Into MEDIATOR_RE (Doc ID 2494061.1)
- Applies to:
- Symptoms
- Changes
- Cause
- To view full details, sign in with your My Oracle Support account.
- Don’t have a My Oracle Support account? Click to get started!
- ORA-02291: integrity constraint violated — parent key not found
- Answers
- ORA-02291: integrity constraint violated — parent key not found
- Answers
ORA-02291: Integrity Constraint-Parent Key Not Found (WWV_FLOW_FND_GU_INT_G_FK) — When Importing A Workspace In APEX — ORDS(with Weblogic) (Doc ID 1992236.1)
Last updated on OCTOBER 25, 2022
Applies to:
Symptoms
Steps to reproduce:
1) In APEX Instance #1 , create a developer account
and assign it to one (or all) of the pre-created user groups: RESTful
Services, SQL Developer, OAuth2 Client Developer.
2) Export this workspace.
3) In APEX Instance #2, log in as instance administrator and open Manage
Workspaces / Import Workspace page.
4) Upload the export file from Step 2 and complete the import wizard — the
following error is displayed:
Execution of the statement was unsuccessful. ORA-02291: integrity constraint
(APEX_040200.WWV_FLOW_FND_GU_INT_G_FK) violated — parent key not found
This error occurs because pre-created user groups (SQL Developer, etc) do not
have the same IDs in two APEX instances.
ORA-02291: integrity constraint (APEX_040200.WWV_FLOW_FND_USER_GRPS_FK) violated — parent key not found when importing a workspace into a newly reinstalled instance
Cause
To view full details, sign in with your My Oracle Support account.
Don’t have a My Oracle Support account? Click to get started!
In this Document
My Oracle Support provides customers with access to over a million knowledge articles and a vibrant support community of peers and Oracle experts.
Oracle offers a comprehensive and fully integrated stack of cloud applications and platform services. For more information about Oracle (NYSE:ORCL), visit oracle.com. пїЅ Oracle | Contact and Chat | Support | Communities | Connect with us |
|
|
| Legal Notices | Terms of Use
Источник
Oracle / PLSQL: ORA-02291 Error Message
Learn the cause and how to resolve the ORA-02291 error message in Oracle.
Description
When you encounter an ORA-02291 error, the following error message will appear:
- ORA-02291: integrity constraint violated — parent key not found
Cause
You tried to reference a table using a unique or primary key, but the columns that you listed did not match the primary key, or a primary key does not exist for this table.
Resolution
The option(s) to resolve this Oracle error are:
Option #1
This error commonly occurs when you have a parent-child relationship established between two tables through a foreign key. You then have tried to insert a value into the child table, but the corresponding value does not exist in the parent table.
To correct this problem, you need to insert the value into the parent table first and then you can insert the corresponding value into the child table.
For example, if you had created the following foreign key (parent-child relationship).
Then you try inserting into the products table as follows:
You would receive the following error message:

Since the supplier_id value of 5000 does not yet exist in the supplier table, you need to first insert a record into the supplier table as follows:
Then you can insert into the products table:
Источник
ORA-02291: Integrity Constraint,parent Key Not Found Error Code: 2291 Call: Insert Into MEDIATOR_RE (Doc ID 2494061.1)
Last updated on OCTOBER 21, 2021
Applies to:
Symptoms
On : 12.2.1.3.0 version, Fabric
While using a composite with mediator, execution after running a purge is throwing the error as below.
ORA-02291: integrity constraint (OPS_SOAINFRA.MEDIATOR_GROUP_STATUS_FK1) violated — parent key not found
ERROR
————————
Got an exception: Exception [EclipseLink-4002] (Eclipse Persistence Services — 2.6.5.v20170607-b3d05bd): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (OPS_SOAINFRA.MEDIATOR_GROUP_STATUS_FK1) violated — parent key not found Error Code: 2291 Call: Insert into MEDIATOR_RESEQUENCER_MESSAGE (ID,OWNER_ID,COMPONENT_DN,OPERATION,LEVEL_DETAIL2,GROUP_ID,SEQUENCE_ID, CREATION_DATE,NEXT_SEQUENCE_ID, SOURCE_URI,STANDARD_SEQUENCE_ID,STATUS,INSTANCE_CREATED,property1,property2,DUMMY1,FLOW_ID,SCA_PARTITION_ID,PARTITION_DATE) values (. systimestamp at time zone ‘UTC’. ) bind = 4
Changes
Cause
To view full details, sign in with your My Oracle Support account.
Don’t have a My Oracle Support account? Click to get started!
In this Document
My Oracle Support provides customers with access to over a million knowledge articles and a vibrant support community of peers and Oracle experts.
Oracle offers a comprehensive and fully integrated stack of cloud applications and platform services. For more information about Oracle (NYSE:ORCL), visit oracle.com. пїЅ Oracle | Contact and Chat | Support | Communities | Connect with us |
|
|
| Legal Notices | Terms of Use
Источник
ORA-02291: integrity constraint violated — parent key not found
Hi all,
I have two tables
A,B
A has primary key referenced as foreign key in B table
When I need to dleete some rows from table A.But when i tried to delete them,Iwas thrown with the error.
ORA-02292: integrity constraint (string.string) violated — child record found
So idisble the constraint from table B.
AFter that i delete the rows from table A and reserted some other rows.
But now when i try to enable the constraint,I am getting this error.
ORA-02291: integrity constraint (string.string) violated — parent key not found.
How to overcome this situation?
Answers
Error: ORA 2291
Text: integrity constraint (%s.%s) violated — parent key not found
——————————————————————————-
Cause: Attempted to insert or update values that do not have corresponding
Parent key values.
Action: obvious.
Explanation:
If you have a FOREIGN KEY constraint on a table you cannot INSERT
or UPDATE rows such that they would not have a matching PARENT
in the MASTER table.
>
Refer to metalink Doc ID: Note:19524.1
Yes you are getting the correct error .
If Oracle allows you to do this that is allow you to insert into the foreign key column without corresponding primary key then What is the purpose of enforcing primary and foreign key or parent child relationship.
In your case you can only insert into the foreign key if you have the corresponding entry in the Primary key.
If at the time of creating foreignn key, you have use «On delete cascade or On delete set null» Then you can simply delete the primary key without doping anything to the foreign key. Corresposnding values for the foreignn key will automatically be deleted or set to null.
When you enable the constraint it check existing data also. so overcome from this situation enable the constraint with novalidate option so it check for future insertion only not check existing data.
Edited by: Vivekdhiman on Oct 21, 2008 12:12 PM
The correct answer is to ensure that you DO have the parent key values — ie in the Parent table.
You would use NOVALIDATE only under exceptional circumstances — eg you are «fixing» data which was erroneous OR that you need to ignore existing rows but want the constraint enabled for future rows to be inserted after this point in time.
I have a table A which has a column x as primary key.
This column x is referenced in column y of table B.
Now as per my understanding,table A is the primary table and table B is the foriengn key table.
On deleteing from table A,i got the error child record found as x is foreign key in table B.
I disabled the foriegn key constraint in table B.
I deleted the rows from table A.
I,then reserted some rows in tbale A.
I committed the transaction.
Now I want to enable the foriegn key constraint in table B.
But I am getting parent key not found.
I have records in parent table ie table A. I am not inserting in table B[foreign key table].
I inserted in table A.
The situation is like this.
table A table B
x y
1 1
2 1
3 2
4 3
5
6
7
8
Now when i enable cforiegn key constraint in table B,I get parent key not found,but all the parent key is present in table A.
I inserted 5,6,7,8 in table A after deleting some records.
Edited by: MYH on Oct 21, 2008 12:33 AM
SQL> create table parent1(id number primary key);
SQL> insert into parent1 values(&i);
Enter value for i: 1
old 1: insert into parent1 values(&i)
new 1: insert into parent1 values(1)
SQL> /
Enter value for i: 2
old 1: insert into parent1 values(&i)
new 1: insert into parent1 values(2)
SQL> /
Enter value for i: 3
old 1: insert into parent1 values(&i)
new 1: insert into parent1 values(3)
SQL> /
Enter value for i: 4
old 1: insert into parent1 values(&i)
new 1: insert into parent1 values(4)
SQL> create table child1(id number CONSTRAINT FK_ID references parent1(id));
SQL> insert into child1 values(&i);
Enter value for i: 1
old 1: insert into child1 values(&i)
new 1: insert into child1 values(1)
SQL> /
Enter value for i: 1
old 1: insert into child1 values(&i)
new 1: insert into child1 values(1)
SQL> /
Enter value for i: 3
old 1: insert into child1 values(&i)
new 1: insert into child1 values(3)
SQL> /
Enter value for i: 2
old 1: insert into child1 values(&i)
new 1: insert into child1 values(2)
SQL> /
Enter value for i: 4
old 1: insert into child1 values(&i)
new 1: insert into child1 values(4)
SQL> select * from parent1;
SQL> delete from parent1 where > delete from parent1 where > *
ERROR at line 1:
ORA-02292: integrity constraint (SCOTT.FK_ID) violated — child record found
SQL> select constraint_name,constraint_type from user_constraints where table_name=’CHILD
SQL> ALTER TABLE CHILD1 DISABLE CONSTRAINT FK_ID;
SQL> delete from parent1 where >
1 row deleted.
SQL> ALTER TABLE CHILD1 ENABLE CONSTRAINT FK_ID;
ALTER TABLE CHILD1 ENABLE CONSTRAINT FK_ID
*
ERROR at line 1:
ORA-02298: cannot validate (SCOTT.FK_ID) — parent keys not found
SQL> INSERT INTO PARENT1 VALUES(1);
SQL> ALTER TABLE CHILD1 ENABLE CONSTRAINT FK_ID;
Источник
ORA-02291: integrity constraint violated — parent key not found
I have a row in parent table. I am using the same sequence from the parent table during insertion. (In fact I am getting the sequence from the drop down during insertion in plsql developer tool). Still I am getting this error.
1) Parent table’s primary key is Child table’s primary key as well as foreign key.
2) Parent table’s primary key is referred as primary key in some other child table as well.
3) But not using Supertype-Subtype relationship. Just direct reference
Can you please tell me why am I getting this error.
Answers
Because the integrity check is made immediately, and the database is temporarily inconsistent.
When you set the foreign key to be deferred it will evaluate at commit, when everything should be ok again.
———
Sybrand Bakker
Senior Oracle DBA
I am assuming you know the fact that by this design, your Parent can have a Single Child. Hence, a change in Business req, to support multiple childs can be a headache for you.>
Can you please let me know why can’t I have more than 1 table. As I mentioned in my 2nd point, I have more than 1 child table for a same parent.
sybrand_b wrote:
Because the integrity check is made immediately, and the database is temporarily inconsistent.
When you set the foreign key to be deferred it will evaluate at commit, when everything should be ok again.
———
Sybrand Bakker
Senior Oracle DBA
Curious to understand this.
In below test case (which I am assuming is on same lines as OP’s):
In this test case, an Integrity was made immediately and reported an error.
Can you please explain if I misunderstood your point?
I am assuming you know the fact that by this design, your Parent can have a Single Child. Hence, a change in Business req, to support multiple childs can be a headache for you.>
Can you please let me know why can’t I have more than 1 table. As I mentioned in my 2nd point, I have more than 1 child table for a same parent.
I never mentioned «can’t I have more than 1 table». I was talking in terms of Records.
Say, your Parent ID 1, can possibly have more than 1 child (speaking in General terms excluding your Requirements), hence if you keep your Foreign Key as Primary Key, your Table would not allow you, would it?
I do understand that you being knowledgeable about your requirements have designed the Tables accordingly, I was just raising a concern I saw.
No Objections to your design. 
Источник

Learn the cause and how to resolve the ORA-02291 error message in Oracle.
Description
When you encounter an ORA-02291 error, the following error message will appear:
- ORA-02291: integrity constraint <constraint name> violated — parent key not found
Cause
You tried to reference a table using a unique or primary key, but the columns that you listed did not match the primary key, or a primary key does not exist for this table.
Resolution
The option(s) to resolve this Oracle error are:
Option #1
This error commonly occurs when you have a parent-child relationship established between two tables through a foreign key. You then have tried to insert a value into the child table, but the corresponding value does not exist in the parent table.
To correct this problem, you need to insert the value into the parent table first and then you can insert the corresponding value into the child table.
For example, if you had created the following foreign key (parent-child relationship).
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier (supplier_id)
);
Then you try inserting into the products table as follows:
INSERT INTO products (product_id, supplier_id) VALUES (1001, 5000);
You would receive the following error message:

Since the supplier_id value of 5000 does not yet exist in the supplier table, you need to first insert a record into the supplier table as follows:
INSERT INTO supplier (supplier_id, supplier_name, contact_name) VALUES (5000, 'Microsoft', 'Bill Gates');
Then you can insert into the products table:
INSERT INTO products (product_id, supplier_id) VALUES (1001, 5000);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
CREATE TABLE DEPARTMENT( DEPARTMENTS_ID NUMBER NOT NULL, DEPARTMENTS_OTDEL NUMBER, DEPARTMENTS_NAME VARCHAR2(100 BYTE), PRIMARY KEY (DEPARTMENTS_ID) ); INSERT INTO DEPARTMENT VALUES('1','1','АДМИНИСТРАЦИЯ'); INSERT INTO DEPARTMENT VALUES('2','16','КАФЕДРА АГРОНОМИИ'); INSERT INTO DEPARTMENT VALUES('3','22','КАФЕДРА ИНФОРМАТИКИ'); INSERT INTO DEPARTMENT VALUES('4','25','ПЛАНОВЫЙ ОТДЕЛ'); INSERT INTO DEPARTMENT VALUES('5','29','БУХГАЛТЕРИЯ'); INSERT INTO DEPARTMENT VALUES('6','46','МАТЕРИАЛЬНЫЙ ОТДЕЛ'); INSERT INTO DEPARTMENT VALUES('7','50','ОТДЕЛ ОХРАНЫ ТРУДА'); INSERT INTO DEPARTMENT VALUES('8','52','ОТДЕЛ КАДРОВ'); INSERT INTO DEPARTMENT VALUES('9','66','КАФЕДРА ХИМИИ'); INSERT INTO DEPARTMENT VALUES('10','92','ХОЗЧАСТЬ'); INSERT INTO DEPARTMENT VALUES('11','96','КАФЕДРА ФИЗИКИ'); INSERT INTO DEPARTMENT VALUES('12','97','БИОЛОГИЧЕСКИЙ ФАКУЛЬТЕТ'); CREATE TABLE POSIT( POSITIONS_ID NUMBER NOT NULL, POSITIONS_DOLJNOST NUMBER, POSITIONS_NAME VARCHAR2(120 BYTE), PRIMARY KEY (POSITIONS_ID) ); INSERT INTO POSIT VALUES ('1','5','ДОЦЕНТ'); INSERT INTO POSIT VALUES ('2','7','ЗАВЕДУЩИЙ ЛАБОРАТОРИЕЙ'); INSERT INTO POSIT VALUES ('3','8','ЛАБОРАНТ'); INSERT INTO POSIT VALUES ('4','9','КАНЦЕЛЯРИСТ'); INSERT INTO POSIT VALUES ('5','10','ИНЖЕНЕР'); INSERT INTO POSIT VALUES ('6','12','НАЧАЛЬНИК ОТДЕЛА'); INSERT INTO POSIT VALUES ('7','14','МАСТЕР'); INSERT INTO POSIT VALUES ('8','15','ПРОГРАММИСТ'); INSERT INTO POSIT VALUES ('9','16','ПРОФЕССОР'); INSERT INTO POSIT VALUES ('10','18','СЛЕСАРЬ-ЭЛЕКТРИК'); INSERT INTO POSIT VALUES ('11','20','СТАРШИЙ ПРЕПОДАВАТЕЛЬ'); INSERT INTO POSIT VALUES ('12','22','ЭЛЕКТРИК'); INSERT INTO POSIT VALUES ('13','100','ДИРЕКТОР'); CREATE TABLE STAFF( STAFF_ID NUMBER NULL, STAFF_NOMER NUMBER, STAFF_SURNAME VARCHAR2(100 BYTE), STAFF_NAME VARCHAR2(100 BYTE), STAFF_PATRONYMIC VARCHAR2(100 BYTE), STAFF_DATEBIRTH DATE, STAFF_DATEWORK DATE, POSITIONS_DOLJNOST NUMBER, DEPARTMENTS_OTDEL NUMBER, STAFF_STATUS VARCHAR2(100 BYTE), STAFF_OKLAD NUMBER, STAFF_KEY_MAIN NUMBER, PRIMARY KEY (STAFF_ID), FOREIGN KEY (POSITIONS_DOLJNOST) REFERENCES POSIT, FOREIGN KEY (DEPARTMENTS_OTDEL) REFERENCES DEPARTMENT ); INSERT INTO STAFF VALUES('1','2061','ГУБИН','АЛЕКСАНДР','МИХАЙЛОВИЧ','30.01.1963','02.09.1995','16','8','Р','1500','2309'); INSERT INTO STAFF VALUES('2','2072','КОНДРАТЬЕВ','НИКОЛАЙ','НИКОЛАЕВИЧ','28.08.1996','17.06.1996','22','8','Р','1000','2409'); INSERT INTO STAFF VALUES('3','2081','ШИРЯЕВ','ЮРИЙ','БОРИСОВИЧ','25.01.1961','08.08.1988','16','20','Р','3000','2402'); INSERT INTO STAFF VALUES('4','2084','ВЕТРОВА','ЛЮДМИЛА','ВЛАДИМИРОВНА','05.12.1951','01.09.1996','97','16','Р','1500','2332'); INSERT INTO STAFF VALUES('5','2160','НИКИТИНА','МАРИНА','АЛЕКСЕЕВНА','07.02.1955','01.05.1995','50','10','Р','3500','2332'); INSERT INTO STAFF VALUES('6','2198','ШУЛЬЖЕНКО','НАИНА','ИВАНОВНА','28.07.1969','01.05.1995','52','9','Р','1000','2332'); INSERT INTO STAFF VALUES('7','2202','ГРЕБЕШКОВА','СВЕТЛАНА','СЕРГЕЕВНА','20.02.1949','01.05.1995','52','12','Р','1500','2397'); INSERT INTO STAFF VALUES('8','2271','БУРАНОВ','АЛЕКСАНДР','АЛЕКСАНДРОВИЧ','04.06.1941','23.05.1988','25','14','Р','3000','2409'); INSERT INTO STAFF VALUES('9','2276','ДЕРБЕНЕВ','ВЛАДИМИР','АЛЕКСАНДРОВИЧ','11.03.1960','01.08.2004','92','22','Р','3000','2297'); INSERT INTO STAFF VALUES('10','2290','ИВАНОВА','ЛЮБОВЬ','АНДРЕЕВНА','20.11.1949','01.08.1996','92','8','Р','1000','2297'); INSERT INTO STAFF VALUES('11','2297','ГУЩИНА','ТАМАРА','МИХАЙЛОВНА','29.10.1949','18.11.1995','92 ','8','Р','1000','2332'); INSERT INTO STAFF VALUES('12','2309','ЛАРЦЕВА','ИННА','ВЛАДИМИРОВНА','07.10.1958','01.11.1995','16','7','Р','3000','2372'); INSERT INTO STAFF VALUES('13','2314','АЛИМБЕКОВ','РУСЛАН','СЕРГЕЕВИЧ','21.06.1970','01.03.2016','92','18','Р','3000','2297'); INSERT INTO STAFF VALUES('14','2351','БОЧКИН','ВАЛЕРИЙ','АЛЕКСАНДРОВИЧ','20.10.1956','23.05.1988','25','14','Р','1000','2409'); INSERT INTO STAFF VALUES('15','2353','АНДРИАНОВ','ВЛАДИМИР','ВЛАДИМИРОВИЧ','01.04.1960','01.09.1996','96','5','Р','1000','2414'); INSERT INTO STAFF VALUES('16','2368','БУШУЕВ','КИРИЛЛ','АНАТОЛЬЕВИЧ','10.11.1972','01.09.1995','29','5','Р','3000','2332'); INSERT INTO STAFF VALUES('17','2372','АШИРОВ','АНВАР','РАШИДОВИЧ','28.07.1969','01.11.1995','16','5','Р','1000','2332'); INSERT INTO STAFF VALUES('18','2379','ЗВЕРЕВ','НИКОЛАЙ','ТИМОФЕЕВИЧ','09.02.1960','01.09.1995','46','15','Р','1000','2332'); INSERT INTO STAFF VALUES('19','2381','АНТОШКИН','ОЛЕГ','ИВАНОВИЧ','29.08.1963','01.09.1993','29','22','Р','1000','2368'); INSERT INTO STAFF VALUES('20','2382','ЗАЙЦЕВА','РАИСА','МИХАЙЛОВНА','20.04.1983','02.09.1996','29','20','Р','2500','2368'); INSERT INTO STAFF VALUES('21','2397','СТЕЖКИН','АНДРЕЙ','ВЛАДИМИРОВИЧ','30.09.1973','01.05.2003','52','9','Р','1500','2198'); INSERT INTO STAFF VALUES('22','2402','ПОВЕТКИНА','НИНА','МИХАЙЛОВНА','20.02.1949','01.09.2010','16','5','Р','1500','2309'); INSERT INTO STAFF VALUES('23','2409','ОВСЯННИКОВ','МИХАИЛ','КОНСТАНТИНОВИ','11.12.1976','15.01.2010','22','5','Р','1000','2332'); INSERT INTO STAFF VALUES('24','2414','ВАСИЛЬЕВА','ГАЛИНА','ИВАНОВНА','01.04.1981','01.09.2001','96','5','Р','500','2332'); INSERT INTO STAFF VALUES('25','2419','КАПЕЛИНА','ДИНАРА','АМИРОВНА','22.12.1971','01.09.1999','16','5','Р','1000','2372'); INSERT INTO STAFF VALUES('26','2420','ДОБРЫНИН','СЕРГЕЙ','СЕРГЕЕВИЧ','05.01.1962','01.05.1995','50','12','Р','1500','2332'); INSERT INTO STAFF VALUES('27','2436','ЧЕРНОВА','МАРИНА','НИКОЛАЕВНА','29.08.1974','02.09.1996','22','5','Р','1200','2309'); INSERT INTO STAFF VALUES('28','2332','СОБОЛЕВ','ИВАН','ИВАНОВИЧ','18.12.1969','01.10.1996','1','100','Р','10000','0'); |
May 1, 2021
I got ” ORA-02291: integrity constraint (string.string) violated – parent key not found ” error in Oracle database.
ORA-02291: integrity constraint (string.string) violated – parent key not found
Details of error are as follows.
ORA-02291: integrity constraint (string.string) violated - parent key not found Cause: A foreign key value has no matching primary key value. Action: Delete the foreign key or add a matching primary key.
integrity constraint (string.string) violated – parent key not found
This ORA-02291 errors are related with the foreign key value has no matching primary key value.
To solve this error, you need to drop the foreign key or add a matching primary key.
Or firstly you need to insert the same value into the parent table, then you can insert the value into child table.
For example; I have 2 table which has relation between two table with EMPLOYEE_ID column as follows.
CREATE TABLE EMPLOYEE ( EMPLOYEE_ID numeric(10) not null, NAME varchar2(50) not null, LAST_NAME varchar2(50), CONSTRAINT emp_pk PRIMARY KEY (EMPLOYEE_ID) ); CREATE TABLE MANAGER ( ID numeric(10) not null, EMPLOYEE_ID numeric(10) not null, CONSTRAINT fk_EMPLOYEE FOREIGN KEY (EMPLOYEE_ID) REFERENCES EMPLOYEE (EMPLOYEE_ID) );
I have inserted the following record.
INSERT INTO MANAGER (ID, EMPLOYEE_ID) VALUES (10, 63);
But I got this error, because 63 employee_id doesn’t exist in the employee table. So You need to insert this record to parent table, then you can insert the child table as follows.
INSERT INTO EMPLOYEE (EMPLOYEE_ID, NAME, LAST_NAME) VALUES (63, 'Mehmet ', 'Deveci ');
Then you can insert into the MANAGER table:
INSERT INTO MANAGER (ID, EMPLOYEE_ID) VALUES (10, 63);
Or you need to drop the emp_pk constraint.
Do you want to learn Oracle Database for Beginners, then read the following articles.
Oracle Tutorial | Oracle Database Tutorials for Beginners ( Junior Oracle DBA )
1,222 views last month, 3 views today
About Mehmet Salih Deveci
![]()
I am Founder of SysDBASoft IT and IT Tutorial and Certified Expert about Oracle & SQL Server database, Goldengate, Exadata Machine, Oracle Database Appliance administrator with 10+years experience.I have OCA, OCP, OCE RAC Expert Certificates I have worked 100+ Banking, Insurance, Finance, Telco and etc. clients as a Consultant, Insource or Outsource.I have done 200+ Operations in this clients such as Exadata Installation & PoC & Migration & Upgrade, Oracle & SQL Server Database Upgrade, Oracle RAC Installation, SQL Server AlwaysOn Installation, Database Migration, Disaster Recovery, Backup Restore, Performance Tuning, Periodic Healthchecks.I have done 2000+ Table replication with Goldengate or SQL Server Replication tool for DWH Databases in many clients.If you need Oracle DBA, SQL Server DBA, APPS DBA, Exadata, Goldengate, EBS Consultancy and Training you can send my email adress [email protected].- -Oracle DBA, SQL Server DBA, APPS DBA, Exadata, Goldengate, EBS ve linux Danışmanlık ve Eğitim için [email protected] a mail atabilirsiniz.
When trying to add a foreign key to a table sometimes the error ORA-02298 is thrown.
Let’s have two tables a MyTable and a MyTableHistory connected by a historyid column from MyTable that points to the id column from MyTableHistory
Try then to add add foreign key like:
ALTER TABLE MyTableHistory add CONSTRAINT MyKey foreign key (default_id) references MyTable;
If we are in the case of the ORA-02298 error the following message will be given by Oracle:
Error report -
ORA-02298: cannot validate (MyKey) - parent keys not found
02298. 00000 - "cannot validate (%s.%s) - parent keys not found"
*Cause: an alter table validating constraint failed because the table has child records.
*Action: Obvious
Funny how someone marked the solution as “Obvious” 🙂 Not so obvious because I had to look around some time to figure out what was the problem.
This error means that you have ids in your MyTableHistory table that are not present in the MyTable table. The foreign key can therefore not be applied.
This can be checked by running a query like:
SELECT * FROM MyTableHistory WHERE id NOT IN (SELECT MyTable.historyid FROM MyTable);
If the above query returns some rows it means that at some point we deleted (cleaned) some rows from the MyTable without cleaninf also the refered entries from MyTableHistory.
Do do the proper clean-up I had to execute:
DELETE FROM MyTableHistory WHERE id NOT IN (SELECT MyTable.historyid FROM MyTable);
After the clean-up is done we then ca execute again:
ALTER TABLE MyTableHistory add CONSTRAINT MyKey foreign key (default_id) references MyTable;
Success !
Find the row which causing violation of foreign key constraint in Oracle
Find the row which caused a violation of the foreign key when tried to enable the foreign key constraint:
To clean the rows that violate the foreign key constraint, You need to create an EXCEPTIONS table in the current schema. Use this script present in the RDBMS folder of Oracle Home: rdbms/admin/utlexcpt.sql.
Following are the steps to find the row that violate the foreign key constraint:
1. Create an exceptions table.
SQL> @?/rdbms/admin/utlexcpt.sql;
2. Populate the EXCEPTIONS table with the rows that violate the constraint, using the EXCEPTIONS INTO clause.
SQL> alter table table_name modify constraint fk_constraint_name validate exceptions into exceptions;
Note This statement while executing still throws the ORA-02298 error as long as there are rows that violate the constraint. The statement also inserts records into the EXCEPTIONS table for any bad rows.
- Check the Exception table for rows.
You use the ROW_ID column of the EXCEPTIONS table to remove any records that violate the constraint. In Example, you find that only one row needs to be removed from the EMP table.
SQL> SELECT * FROM EXCEPTIONS;
Example:
ROW_ID OWNER TABLE_NAME CONSTRAINT
------------------ ----- ---------- --------------------
AAAFKQAABAAAK8JAAB SCOTT EMP EMP_DEPT_FK
Example of Creating Foreign key and reproducing the error and solution:
--- Created Parent p1 and Child c1 table with foreign key established
SQL> create table p1(id number primary key, name varchar2(100));
Table created.
SQL> create table c1(cid number primary key, pid number, constraint fk_c2 foreign key (pid) references p1(id));
Table created.
-- insert into parent and child table
SQL> insert into p1 values (1,'a');
1 row created.
SQL> insert into p1 values (2,'b');
1 row created.
SQL> insert into c1 values (2,5);
insert into c2 values (2,5)
*
ERROR at line 1:
ORA-02291: integrity constraint (SYS.FK_C2) violated - parent key not found
-- Disable the foreign key constraint to insert value
SQL> alter table c2 disable constraint FK_C2;
Table altered.
SQL> insert into c2 values (2,5);
1 row created.
--Enable the constraint throw the error
SQL> alter table c2 enable constraint FK_C2;
alter table c2 enable constraint FK_C2
*
ERROR at line 1:
ORA-02298: cannot validate (SYS.FK_C2) - parent keys not found
--Find the row causing problem to enable the constraint:
SQL> @?/rdbms/admin/utlexcpt.sql;
Table created.
--Run again the command using EXCEPTION table:
SQL> alter table c2 modify constraint FK_C2 validate exceptions into exceptions;
alter table c2 modify constraint FK_C2 validate exceptions into exceptions
*
ERROR at line 1:
ORA-02298: cannot validate (SYS.FK_C2) - parent keys not found
--Check the EXCEPTION table having rowid which causing problem:
SQL> col owner for a10
SQL> col table_name for a10
SQL> col constraint for a20
SQL> select * from exceptions;
ROW_ID OWNER TABLE_NAME CONSTRAINT
------------------ ---------- ---------- --------------------
AAATBmAABAAAIGBAAA SYS C2 FK_C2
-- Check the row in table
SQL> select * from c2 where rowid in (select row_id from exceptions);
CID PID
---------- ----------
2 5