Oracle Database with very few foreign key constraints - oracle

I've just started a new project and I am confronted with a production application Oracle 10g database that has just 3 foreign key constraints. I am not used to seeing databases with no foreign key constraints. I am guessing that there may be some performance/concurrency considerations to not using FKs. The reason is that in the logical database schema the architect has specified all the relationships, but these relationships are not implemented in the database as Foreign Key constraints.
Question: I read that I can define a Foreign Key Constraint with RELY NOVALIDATE that will not impact performance. Is it worth while to define RELY FK constraints on this database just so that the relationship can be easily seen? this application is not built using ORM, is it really worth while to do without foreign keys?
The database is denormalised with example below
Table 1 : FINProduct(ID (number), Description(varchar(5)), FINproductCode(varchar(10))...)
Table 2: FINProductCode(ID (number, FINproductCode(varchar(10)) , LastUpdated(datetime)...)
So instead of having a relationship between Tables 1 and 2 the FINproductCode column is just replicated in table 1.
It's too early to drink but I think i need one!

I would be very wary about assuming that the absence of foreign key constraints was a reasoned response to performance issues. There is an overhead to enforcing a foreign key constraint (particularly where appropriate indexes are missing) but it is incredibly unlikely that your application can validate the constraint more efficiently than Oracle can. So the question really is whether you want the small overhead of foreign key constraints or the near certainty that you will get invalid data inserted into the database. It would be extremely unlikely that this is a trade-off that you want to make-- I've yet to meet a business user that would be happy to capture incorrect and incomprehensible data even if doing so was a bit faster than capturing correct data.
Unless there is substantially more background, I would tend to create all the missing foreign key constraints. Creating RELY NOVALIDATE constraints is possible but it defeats the major benefit of foreign key constraints-- preventing invalid data from entering the database in the first place.

It depends on whether you want to add the FK only for documentation purposes or whether you want to prevent future INSERTs/UPDATEs with an invalid FK value.
If you want it only for documentation purposes, I'd create the FK constraint with RELY NOVALIDATE and DISABLE it afterwards - otherwise, Oracle will check it for future INSERTs / UPDATEs.
However: DON'T DO THIS UNLESS YOU ABSOLUTELY NEED IT!
I agree with Justin Cave: In most cases, you should just add "plain" FK constraints - this way, you can ensure that your existing data is correct.

I would try to create the constraints and report violations into a exception table. Fix the data and enable the constraint.
Create some test data
create table parent (pk integer
,data varchar2(1)
,CONSTRAINT PARENT_PK PRIMARY KEY (PK) ENABLE );
create table child (pk integer
,pk_parent integer
,data varchar2(1)
,CONSTRAINT CHILD_PK PRIMARY KEY (PK) ENABLE );
insert into parent values (1,'a');
insert into parent values (2,'b');
insert into child values (1,1,'a');
insert into child values (2,2,'b');
insert into child values (3,3,'c');
Create a foreign key constraint:
alter table child add constraint fk_parent foreign key(pk_parent) references parent(pk);
SQL Error: ORA-02298: Kan (ROB.FK_PARENT) niet valideren - bovenliggende sleutels zijn niet gevonden.
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
Create the foreign key with 'enable novalidate' option
alter table child add constraint fk_parent foreign key(pk_parent) references parent(pk) enable novalidate;
table CHILD altered.
insert into child values (4,4,'c');
SQL Error: ORA-02291: Integriteitsbeperking (ROB.FK_PARENT) is geschonden - bovenliggende sleutel is niet gevonden.
02291. 00000 - "integrity constraint (%s.%s) 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.
No new data violating the FK can be inserted.
Now let's fix the data already in the table that violates the FK constraint
Create an exceptions table and try to enable the constraint:
create table exceptions(row_id rowid,
owner varchar2(30),
table_name varchar2(30),
constraint varchar2(30));
ALTER TABLE child ENABLE constraint fk_parent EXCEPTIONS INTO EXCEPTIONS;
Error report:
SQL Error: ORA-02298: Kan (ROB.FK_PARENT) niet valideren - bovenliggende sleutels zijn niet gevonden.
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
Check the exceptions table for problems:
select * from exceptions;
ROW_ID OWNER TABLE_NAME CONSTRAINT
------ ------------------------------ ------------------------------ ------------------------------
AABA78 ROB CHILD FK_PARENT
AAFAAA
Ow9AAC
select * from child where rowid = 'AABA78AAFAAAOw9AAC';
Fix the problem
delete from child where pk = 3;
1 rows deleted.
ALTER TABLE child ENABLE constraint fk_parent EXCEPTIONS INTO EXCEPTIONS;
table CHILD altered.
Constraint enabled and data correct

Related

In which order should we apply primary key, foreign key constraints and create index if the Oracle table has data?

1.In which order should we apply primary key, foreign key constraints and create index if the Oracle table has millions of data and does not have prior constraints?
2.Can we use 'NOLOGGING PARALLEL' while applying primary key and foreign key constraints like we do while applying(creating) indexes? Or any other method so that primary key and foreign key constraints could be applied faster?
Note: I'll use bullets so that it is easier to read, as it is easy to get lost in long sentences.
My thoughts on the subject; see if anything of this helps.
Well,
as you can't create a foreign key constraint if column(s) it references aren't part of primary or unique key
you'll obviously first have to create primary key constraints
and then foreign key constraints
When you
create a primary key constraint,
Oracle automatically creates index that supports it, unless there's already an index you can use (with the USING INDEX clause)
which means that you can "skip" some indexes (those for primary key constraints as they'll already exist) and virtually save some time
and create "other" indexes
On the other hand,
if you first create unique index on future primary key columns and
later add primary key constraint with the USING INDEX clause, Oracle will "skip" check for possible duplicate values because unique index won't allow them
The same goes for
NOT NULL constraint on future primary key columns; primary key doesn't allow NULLs so - if a column already is NOT NULL, enforcing primary key constraint can skip NULL check as well
I don't know
which columns you'll additionally index, but - as you're on Oracle 11g -
don't forget to index all foreign key constraint columns
because you might encounter unexpected table locks if you
update primary key column in parent table, or
delete parent record
Can you do it with no logging and in parallel? Yes:
SQL> create table test (id number, name varchar2(20));
Table created.
SQL> create unique index ui1_test_id on test (id) nologging parallel 20;
Index created.
SQL> alter table test add constraint pk_test primary key (id) using index ui1_test_id nologging parallel 20;
Table altered.
SQL>
But you'll probably want to change the index and table back to NOPARALLEL and LOGGING when the initial creation is done.
SQL> alter index ui1_test_id noparallel;
Index altered.
SQL> alter table test logging noparallel;
Table altered.

How to capture constraint name using save exception in PL/SQL?

I need to perform delete in bulk from multiple tables.
These tables are having referential integrity constraint enabled.
In case if I miss out to delete any record from child table, I should be able to capture the foreign key constraint name that got violated.
I'm able to capture the foreign key constraint name if I don't use SAVE EXCEPTIONS, however if I use SAVE EXCEPTIONS I'm not able to capture the name.
e.g. To demonstrate I have created 2 tables with referential integrity.
test_parent(id number,PARENT_NAME VARCHAR2)
test_child (id number,child_NAME VARCHAR2)
id column is referenced from test_child to test_parent
I inserted few records in both and then tried to delete from test_parent without deleting from test_child to replicate the error for demonstration.
set serveroutput on <br>
declare <br>
cursor cp is select * from test_parent;<br>
type t_cp is table of cp%rowtype;<br>
tt_cp t_cp;<br>
begin<br>
select * bulk collect into tt_cp from test_parent;<br>
begin<br>
forall idx in 1..tt_cp.count save exceptions<br>
delete from TEST_PARENT where id=tt_cp(idx).id;<br>
exception<br>
when others then<br>
for i in 1..sql%bulk_exceptions.count<br>
loop<br>
dbms_output.put_line(sqlerrm(-1 * SQL%BULK_EXCEPTIONS(i).ERROR_CODE));<br>
end loop;<br>
end;<br>
exception<br>
when others then<br>
rollback;<br>
dbms_output.put_line(sqlerrm);<br>
rollback;<br>
end;<br>
/<br>
How do I capture the constraint name along with using SAVE EXCEPTIONS?
[Below output if I don't use SAVE EXCEPTIONS]
ORA-02292: integrity constraint (SYSTEM.SYS_C0014790) violated - child record found
[Below output if I use SAVE EXCEPTIONS]
ORA-02292: integrity constraint (.) violated - child record found
ORA-02292: integrity constraint (.) violated - child record found

Creating foreign keys on a table fails in Oracle and 2 schemas

I have two schemas, and I am trying to create a table with two foreign key constraint. Creating the foreign key constraint does not work regardless of whether I add the constraint separately or in the table creation DDL. Also regardless of which of the two users I try to run it.
The oracle error is ORA-01031: insufficient privileges.
The table is created when I omit the foreign key constraints.
Intended result: create a table with two constraints.
CREATE TABLE "XXX_MONITORING"."COMPOSITE_STATUS"
( "COMPOSITE_STATUS_ID" NUMBER,
"COMPOSITE_ID" NUMBER,
"STATUS" CHAR(1),
CONSTRAINT "COMPOSITE_FK" FOREIGN KEY ("COMPOSITE_ID")
REFERENCES "XXX_MONITORING_CONFIGURATION"."COMPOSITE_KPI_COMPONENTS" ("COMPONENT_ID") ON DELETE CASCADE ENABLE,
CONSTRAINT "COMPOSITE_STATUS_FK" FOREIGN KEY ("STATUS")
REFERENCES "XXX_MONITORING_CONFIGURATION"."INDICATION_COLOR" ("INDICATION_COLOR_ID") ON DELETE CASCADE ENABLE
);
The table COMPOSITE_KPI_COMPONENTS and INDICATION_COLOR are in different schema i.e. XXX_MONITORING_CONFIGURATION.
That user must grant REFERENCES on COMPOSITE_KPI_COMPONENTS and INDICATION_COLOR to XXX_MONITORING.
-- Grant statement
grant REFERENCES on COMPOSITE_KPI_COMPONENTS to XXX_MONITORING;
grant REFERENCES on INDICATION_COLOR to XXX_MONITORING;

Still Getting Errors After Applying All I've Read About the Error 02270

I'm creating a couple of Tables for an assignment.
So I created a Gardener Table and an Offering Table, with all the appropriate data types and NULL statuses, as well as the Primary Key constraint for each. In the Gardener table I've included offeringID, and vice versa.
When I try to add Foreign Key constraint offeringID to the Gardener Table I get an error.
After checking online, I realized I had forgotten to make offeringID and gardenerID in each other's tables UNIQUE, hence I altered table to add uniqueness.
Tried adding Foreign Key constraint and I get the same error. I reckon I may be understanding something wrongly, but I can't seem to put my finger on it.
Create Table Gardener
(gardenerID NUMBER(10) NOT NULL,
offeringID NUMBER(10) NOT NULL,
CONSTRAINT gardener_pk PRIMARY KEY(gardenerID)
);
Create Table Offering
(offeringID NUMBER(10) NOT NULL,
gardenerID NUMBER(10) NOT NULL,
CONSTRAINT offering_pk PRIMARY KEY(offeringID)
);
Alter Table Gardener
add CONSTRAINT offering_fk FOREIGN KEY(offeringID)
REFERENCES Offering(offeringID);
Alter Table Gardener
add Unique(offeringID);
Alter Table Offering
add Unique(gardenerID);
This is the error:
ORA-02270: no matching unique or primary key for this column-list
02270. 00000 - "no matching unique or primary key for this column-list"
Cause: A REFERENCES clause in a CREATE/ALTER TABLE statement gives a column-list
for which there is no matching unique or primary key constraint in the referenced table.
Like, I still don't get it. Isn't offeringID a Primary Key hence pointing to it from Gardener shouldn't be an issue still?
Since you're trying to add a a foreign key constraint for offering.offeringID column within the Gardener table, whereas that column has no unique/primary key key when you try to add a foreign key. i.e. operation stops at the 3rd command.
So, just exchange the order of commands as :
Alter Table Gardener
add Unique(offeringID); -- should be prior to the below command
Alter Table Gardener
add CONSTRAINT offering_fk FOREIGN KEY(offeringID)
REFERENCES Offering(offeringID);
Demo

how to "re-validate" a foreign constraint in oracle

I have a foreign constraint as below. This was created like three years ago. All the data that are created after this constraint are valid but the backlog data (data before three years) are not valid. Toad shows this constraint as 'Not Validated'
ALTER TABLE ISSUES ADD (
CONSTRAINT FK_CLIENT
FOREIGN KEY (CLIENT)
REFERENCES REPORTERS(USERID)
DEFERRABLE INITIALLY DEFERRED);
Today i fixed all the backlog data and now this constraint will hold good both for existing as well as new data. But how will i make the constraint as 'Validated'.
Is there any way to 're-validate' a foreign constraint?
You should be able to:
ALTER TABLE issues ENABLE VALIDATE CONSTRAINT fk_client;

Resources