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

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;

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.

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

Check constraints on two tables in Oracle

I have two tables with a one-to-one relationship (and relationship is mandatory from one side only). As follows:
create table PRS (
id number(18) not null,
common_code varchar2(10),
constraint pk_prs primary key (id));
create table RLP {
id number(18),
spec_code varchar2(20),
constraint pk_rlp primary key (id),
constraint fk_rlp_prs foreign key (id) references prs(id) on delete cascade);
So the problem is when inserting a record in RLP at least one of common_code or spec_code must have value.
Is it possible to enforce this constraint using a constraint or the only solution is having a trigger?
It seems there is no way to create a constraint on two tables, and the only solution is to create a trigger to throw an exception on desired situation.

Oracle Database with very few foreign key constraints

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

Insufficient privileges when adding FK constraint (Oracle)

ALTER TABLE LAB_ADMIN_USER.TEST_TEMPLATE_ABBR ADD (
CONSTRAINT TEST_TEMPLATE_ABBR_R01
FOREIGN KEY (test_template_id)
REFERENCES LAB_ADMIN.TEST_TEMPLATE (test_template_id)
ON DELETE CASCADE)
What is the most likely cause of 'ORA=01031: insufficient privileges' when executing the command above? In other words, what permission does LAB_ADMIN_USER most likely not have?
I already created the table successfully and attempted to add the FK constraint as LAB_ADMIN_USER.
The table with the primary key is owned by a different schema - LAB_ADMIN. That user must grant REFERENCES on TEST_TEMPLATE to LAB_ADMIN_USER.
From the owning schema execute GRANT REFERENCES ON OWNINGSCHEMA.TABLE TO OTHERSCHEMA;

Resources