FOREIGN KEY ON DELETE RESTRICT Error - Oracle - oracle

Lately I have been trying to add the following foreign key in the table, with the RESTRICT Clause in Oracle with the following command.:
ALTER TABLE
Employee_SalHead
ADD CONSTRAINT PAYROLL_SHEAD_FKEY FOREIGN KEY
(
SalHead_ID
)
REFERENCES SalHead
(
SalHead_ID
)
ON DELETE RESTRICT ENABLE;
This gave me the following error:
Error starting at line : 11 in command - ALTER TABLE Employee_SalHead ADD
CONSTRAINT PAYROLL_SHEAD_FKEY FOREIGN KEY ( SalHead_ID )
REFERENCES SalHead ( SalHead_ID ) ON DELETE RESTRICT ENABLE
Error report - SQL Error: ORA-00905: missing keyword
00905. 00000 - "missing keyword"
*Cause:
*Action:
Also if I try the same through Oracle SQL developer, I get only the options Set Null, Cascade and No Action Only.

Oracle only supports ON DELETE SET NULL and ON DELETE CASCADE. You can achieve your requirement by simply doing the below query. No need to mention ON DELETE RESTRICT
ALTER TABLE Employee_SalHead
ADD CONSTRAINT PAYROLL_SHEAD_FKEY FOREIGN KEY(SalHead_ID)
REFERENCES SalHead(SalHead_ID);
ON DELETE NO ACTION is Default.
From Documentation
The No Action (default) option specifies that referenced key values cannot be updated or deleted if the resulting data would violate a referential integrity constraint. For example, if a primary key value is referenced by a value in the foreign key, then the referenced primary key value cannot be deleted because of the dependent data.

Related

Goose - Got error when add new line in sql file

Here is the sql statement in migration file
-- +goose Up
-- +goose StatementBegin
ALTER TABLE `companies` ADD CONSTRAINT `fk_company_created_user_id` FOREIGN KEY (`created_user_id`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE `companies` ADD CONSTRAINT `fk_company_updated_user_id` FOREIGN KEY (`updated_user_id`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
SELECT 'down SQL query';
-- +goose StatementEnd
And I got the error below
goose run: ERROR 20221002115116_add_foreign_key_to_company_user.sql:
failed to run SQL migration:
failed to execute SQL query "ALTER TABLE `companies` ADD CONSTRAINT `fk_company_created_user_id` FOREIGN KEY (`created_user_id`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;\nALTER TABLE `companies` ADD CONSTRAINT `fk_company_updated_user_id` FOREIGN KEY (`updated_user_id`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;\n":
Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ALTER TABLE `companies` ADD CONSTRAINT `fk_company_updated_user_id` FOREIGN KEY ' at line 2
What's wrong here?

Adding foreign key constraint in Oracle gives missing keyword error

ALTER TABLE ankita.abc
ADD CONSTRAINT abc_thid_fk FOREIGN KEY (th_id)
REFERENCES ankita.theatre (id)
ON DELETE NO ACTION
ON UPDATE CASCADE;
Error report -
SQL Error: ORA-00905: missing keyword
00905. 00000 - "missing keyword"
As far as I know the syntax is correct. What could be the problem with this statement? I am using Oracle 11g Express Edition.
As far as I know, ON UPDATE CASCADE is not there in Oracle Database. You are getting the error because of that; remove that.
Simply try:
alter table ankita.abc
add constraint abc_thid_fk FOREIGN KEY (th_id) references ankita.theatre(id);

Oracle drop constraint unique and re-add it

I've drop a constraint unique key with command:
ALTER TABLE table
DROP CONSTRAINT UNIQUE uk_nome;
it's removed because I don't see it, but when I try to re-add it with different parameter:
ALTER TABLE tale ADD CONSTRAINT UK_name UNIQUE (uk_1, uk_2);
I receive the error:
Errore SQL: ORA-00955: name is already used by an existing object.
Where is the problem?
You drop uk_nome and then add uk_name. I mean that there is a typo in uk_nome.
Resolved, the unique key is present, like index, into the system in the table dba_objects

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

Foreign Key Constraint Issue in Oracle

Having issues declaring a FK in Oracle 9i. I've looked at a number of examples here on SO and in some online docs (e.g. http://www.techonthenet.com/oracle/foreign_keys/foreign_delete.php) without any real luck; trying a similar syntax to that in the link generates the same error:
Error at Command Line:19 Column:4
Error report:
SQL Error: ORA-02253: constraint specification not allowed here
02253. 00000 - "constraint specification not allowed here"
*Cause: Constraint specification is not allowed here in the statement.
*Action: Remove the constraint specification from the statement.
An excerpt of the SQL itself is as below. "Line 19" refers to the line starting with CONSTRAINT
CREATE TABLE Flight (
flight_no varchar2(10) NOT NULL,
airplane_id varchar2(20) NOT NULL
CONSTRAINT flight_airplane_id_fk FOREIGN KEY (airplane_id) REFERENCES Airplane (airplane_id)
ON UPDATE RESTRICT ON DELETE RESTRICT,
dept_date date NOT NULL,
...
Alternatively, trying it without the CONSTRAINT keyword generates an error about a right parenthesis that I can't seem to see is missing.
PS: I understand ON UPDATE RESTRICT is the default behaviour in Oracle, but I prefer to be explicit wherever possible.
First off, in Oracle, there is no ON UPDATE RESTRICT or ON DELETE RESTRICT option. Those appear to be valid in other database engines but they aren't present in the constraint syntax diagram and do not appear to be valid. There is an ON DELETE clause but the only two valid options are CASCADE or SET NULL. There is no ON UPDATE clause.
If we add a comma at the end of the airplane_id definition before the constriant definition and remove the two invalid clauses, your DDL should be valid
CREATE TABLE Flight (
flight_no varchar2(10) NOT NULL,
airplane_id varchar2(20) NOT NULL,
CONSTRAINT flight_airplane_id_fk
FOREIGN KEY (airplane_id) REFERENCES Airplane (airplane_id),
dept_date date NOT NULL,
<<more columns>>
);
Put your constraint at the end:
CREATE TABLE Flight (
flight_no varchar2(10) NOT NULL,
airplane_id varchar2(20) NOT NULL,
dept_date date NOT NULL,
CONSTRAINT flight_airplane_id_fk FOREIGN KEY (airplane_id) REFERENCES Airplane (airplane_id) ON UPDATE RESTRICT ON DELETE RESTRICT
);

Resources