Delete/Modify row in one table based on a condition - Oracle DBMS - sql

I have a table structure like
create table EMPLOYE (
CodeEmploye varchar2(100) not null,
NAS varchar2(100),
CONSTRAINT employe_pk primary key (CodeEmploye)
);
create table SALAIRE (
CodeEmploye varchar2(100) not null,
Mois number not null,
CONSTRAINT salaire_pk primary key (CodeEmploye, Mois),
CONSTRAINT salaire_code_employe_fk FOREIGN KEY(CodeEmploye) REFERENCES EMPLOYE(CodeEmploye)
);
I want to add a constraint where I should not be allowed to modify/delete a row in EMPLOYE table if the same employee exist in SALAIRE table.
What is the best way to do that ?

As you have define the foreign key relationship between two tables by "CodeEmployee" column, what you want has been achieved.
A little bit extension is that if you add "ON DELETE CASCADE" following the fk declaration, once you delete any row form employee table, all the related records in the salary table will be deleted as well.

One of the best ways to do is by creating a foreign key constraint on the "CodeEmploye" column during CREATE TABLE or ALTER TABLE statements. In your case, it is already created (salaire_code_employe_fk) as part of your CREATE statement.
A foreign key constraint ensures that an employee row from the parent table (EMPLOYE) cannot be modified/deleted if the same employee exists in the child table (SALAIRE).

In this case, when you create the order_items table, you define a foreign key constraint with the DELETE CASCADE option as follows:
CREATE TABLE order_items
(
order_id NUMBER( 12, 0 ),
-- other columns
-- ...
CONSTRAINT fk_order_items_orders
FOREIGN KEY( order_id )
REFERENCES orders( order_id )
ON DELETE CASCADE
);
By doing this, whenever you delete a row from the orders table, for example:
DELETE
FROM
orders
WHERE
order_id = 1;
All the rows whose order id is 1 in the order_items table are also deleted automatically by the database system.

Related

How to add delete cascade constraint in sql

I have 2 tables.Table A have columns as (aid, name,depart) where aid is primary key.
Table B has (aid1,aid2,aid3,created_by) where aid1 is the primary_key. aid1, aid2 and aid3 all are primary key of Table A
I want to delete a record in Table B i.e aid1 and simultaneously with delete cascade all three records in TABLE A should be deleted. My doubt here is where should I put the delete cascade constraint. I know that in parent child relationship we need to put delete cascade on the child table so that when parent is deleted, child entities are also deleted but in this scenario I dont understand where I should put delete cascade
Cascading a table will be on the child table. You have to set this on your child table when creating or after creating the child table.
E.g
CREATE TABLE schools (
id int auto_increment primary key not null,
schoolname varchar(191) not null
);
CREATE TABLE students(
id int auto_increment primary key not null,
studentname varchar(191) not null,
school_id int FOREIGN KEY REFERENCES students(id) ONDELETE CASCADE
);
or
You can as well alter the table by running this command.
ALTER TABLE childTable
ADD FOREIGN KEY (childTableParentTableColumn) REFERENCES parentTable(parentTableColumn);

Check if data exists in another table on insert?

Table A
(
Table_A_ID int
)
Table B
(
Table_B_ID int
Value int
)
Say I want to insert data into Table B, where 'Value' would be the same as a Table_A_ID.
How would I make a constraint or check that the data actually exists in the table on insertion?
You probably need to enforce data integrity not only on INSERT into Table B, but also on UPDATE and DELETE in both tables.
Anyway options are:
FOREIGN KEY CONSTRAINT on Table B
TRIGGERs on both tables
As a last resort if for some reason 1 and 2 is not an option STORED PROCEDUREs for all insert, delete update operations for both tables
The preferred way to go in most cases is FOREIGN KEY CONSTRAINT.
Yap, I agree with #peterm.
Cause, if your both Table_A_ID and Table_B_Id are primary keys for both tables, then you don't even need two tables to store the value. Since, your two tables are seems to be on 'one-to-one' relationship. It's one of the database integrity issues.
I think you didn't do proper normalisation for this database.
Just suggesting a good idea!
I found this example which demonstrates how to setup a foreign key constraint.
Create employee table
CREATE TABLE employee (
id smallint(5) unsigned NOT NULL,
firstname varchar(30),
lastname varchar(30),
birthdate date,
PRIMARY KEY (id),
KEY idx_lastname (lastname)
) ENGINE=InnoDB;
Create borrowed table
CREATE TABLE borrowed (
ref int(10) unsigned NOT NULL auto_increment,
employeeid smallint(5) unsigned NOT NULL,
book varchar(50),
PRIMARY KEY (ref)
) ENGINE=InnoDB;
Add a constraint to borrowed table
ALTER TABLE borrowed
ADD CONSTRAINT FK_borrowed
FOREIGN KEY (employeeid) REFERENCES employee(id)
ON UPDATE CASCADE
ON DELETE CASCADE;
NOTE: This tells MySQL that we want to alter the borrowed table by adding a constraint called ‘FK_borrowed’. The employeeid column will reference the id column in the employee table – in other words, an employee must exist before they can borrow a book.
The final two lines are perhaps the most interesting. They state that if an employee ID is updated or an employee is deleted, the changes should be applied to the borrowed table.
NOTE: See the above URL for more details, this is just an excerpt from that article!
Create a foreign key constraint on the column 'Value' on table B that references the 'Table_A_ID' column.
Doing this will only allow values that exist in table A to be added into the 'Value' field of table B.
To accomplish this you first need to make Table_A_ID column the primary key for table A, or it at least has to have some sort of unique constraint applied to it to be a foreign key candidate.
BEGIN TRANSACTION -- REMOVE TRANSACTION AND ROLLBACK AFTER DONE TESTING
--PUT A PRIMARY KEY ON TABLE A
CREATE TABLE A
( Table_A_ID int CONSTRAINT PK_A_Table_A_ID PRIMARY KEY)
--ON VALUE ADD A FOREIGN KEY CONSTRAINT THAT REFERENCEs TABLE A
CREATE TABLE B
( Table_B_ID int,
[Value] int CONSTRAINT FK_B_Value_A REFERENCES A(Table_A_ID)
)
-- TEST VALID INSERT
INSERT A (Table_A_ID) VALUES (1)
INSERT B (Table_B_ID, [Value]) VALUES (1,1)
--NOT ALLOW TO INSERT A VALUE THAT DOES NOT EXIST IN A
--THIS WILL THROW A FOREIGN KEY CONSTRAINT ERROR
INSERT B (Table_B_ID, [Value]) VALUES (1,2) -- 2 DNE in table A
ROLLBACK
Note: there is no magic to 'FK_B_Value_A' or 'PK_A_Table_A_ID' it simply a naming convention and be called anything. The syntax on the foreign key and primary key lines work like this:
column-definition CONSTRAINT give-the-constraint-a-name REFERENCES table-name ( table-column )
column-definition CONSTRAINT give-the-constraint-a-name PRIMARY KEY

Enforce a foreign-key constraint to columns of same table

How to enforce a constraint of foreign key on columns of same table in SQL while entering values in the following table:
employee:
empid number,
manager number (must be an existing employee)
Oracle call this a self-referential integrity constraint. The documentation is here for a description,
You create a self-referential constraint in the same manner you would a normal one:
alter table employees
add constraint employees_emp_man_fk
foreign key ( manager_no )
references employees ( emp_id )
on delete set null
;
I'm assuming that your manager_no is nullable. I've added set null here as a delete cascade would probably wipe out a significant amount of your table.
I can't think of a better way of doing this. Deleting a manager should not result in the deletion of all their employees so you have to set null and have a trigger on the table to alert you to anyone with no manager.
I always like this site, which is good for simple references. and don't forget to have an index on the FK as well or Tom will yell at you :-).
One can also utilise standard Oracle syntax to create a self-referential FK in the create table statement, which would look like the following.
create table employees
( emp_id number
, other_columns ...
, manager_no number
, constraint employees_pk
primary key (emp_id)
, constraint employees_man_emp_fk
foreign key ( manager_no )
references employees ( emp_id )
on delete set null
);
EDIT:
In answer to #popstack's comment below:
Whilst you can do this in one statement not being able to alter a table is a fairly ridiculous state of affairs. You should definitely analyze a table that you're going to be selecting from and you will still want an index on the foreign key ( and possibly more columns and / or more indexes ) otherwise whenever you use the foreign key you're going to do a full table scan. See my link to asktom above.
If you're unable to alter a table then you should, in descending order of importance.
Find out how you can.
Change your DB design as a FK should have an index and if you can't have one then FKs are probably not the way to go. Maybe have a table of managers and a table of employees?
SELF REFERENCES QUERY...
Alter table table_name ADD constraints constraints_name foreign key(column_name1,column_name2..) references table_name(column_name1,column_name2...) ON DELETE CASCADE;
EX- ALTER TABLE Employee ADD CONSTRAINTS Fr_key( mgr_no) references employee(Emp_no) ON DELETE CASCADE;
CREATE TABLE TABLE_NAME (
`empid_number` int ( 11) NOT NULL auto_increment,
`employee` varchar ( 100) NOT NULL ,
`manager_number` int ( 11) NOT NULL ,
PRIMARY KEY (`empid_number`),
CONSTRAINT `manager_references_employee`
FOREIGN KEY (`manager_number`) REFERENCES (`empid_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Hope it helps!

How to insert a record in many to many relationship tables?

For exmple i have two tables
A
create table teachers(
id number(4) primary key,
name varchar(20)
);
B
create table students(
id number(4) primary key,
name varchar(20)
);
and a third table
AB
create table Teacher_Student(
T_Id number(4),
S_Id number(4)
);
and their relationship
alter table teacher_student
add constraint s_t_pk Primary key(T_Id, S_Id);
Is this relationship is created correctly? and what would be the insertion query if i want to add a new student or a teacher.
Suggestion: also add referential integrity constraints:
alter table teacher_student
add constraint s_t_fk_t foreign key (T_Id)
references teachers (id)
on delete cascade
on update cascade;
alter table teacher_student
add constraint s_t_fk_s foreign key (S_Id)
references students (id)
on delete cascade
on update cascade;
Usual manouever for this would require primary keys for student and teacher tables, and then foreign keys for T_Id and S_id to Teachers and Students from Teacher_Student.
When you've done that, inserting to student and teacher, would only check uniqueness of their keys, i.e , you can't have two student's with an id of 1.
Inserting to Teacher_Student would check uniqueness of the relationship, and that the inserted ids exist in their respective tables.
PS abbreviating database object names is a very objectionable habit.

How to declare a foreign key with an OR condition using Oracle?

I have a table (A) whose primary key is either a foreign key to table (B) or table (C).
create table A (
akey number,
txt varchar2(10)
);
create table B (
bkey number,
txt varchar2(10)
);
create table C (
ckey number,
txt varchar2(10)
);
What I want is something like:
alter table A add constraint BorCkey foreign key (akey) references B(bkey)` or C(ckey);
Is this possible?
No, that sort of thing is not possible in Oracle.
Your options generally are
Create two different columns (bkey and ckey) in A where bkey references B.bkey and ckey references C.ckey and create a constraint that ensures that only one is non-NULL at any point in time.
Create some sort of "combined B & C" entity that B & C have foreign keys to and make the foreign key in A reference the key of this combination entity.
If you want a constraint that ensures that exactly one of two columns is NULL and one is NOT NULL for any row
create table one_key(
col1 number,
col2 number,
check( nvl2(col1,1,0) + nvl2(col2,1,0) = 1 )
)
A foreign key constraint is to one foreign table.
That means you'd need to use two ALTER TABLE statements in this situation to setup foreign keys to reference the two tables. There's no opportunity in there to specify an OR in the relationship -- the value in A.akey would have to exist in both B.bkey and C.ckey at the same time. For example, if B.bkey has a value of NULL, but C.ckey does not -- then A.akey can never have a value of NULL. Foreign keys are deferrable in Oracle, but the behavior described is what you will encounter if both foreign keys are enabled at the same time -- you won't be able to enable a constraint if all the values don't satisfy the relationship.
You need to review your needs for how to simplify the relationship so it doesn't need two tables to make this work.
Sounds like you have some form of subtype/supertype relationship going on.
A typical example is 'PERSON' which may be either a 'CUSTOMER' or a 'SUPPLIER'.
You might have, in the PERSON table the unique key of PERSON_ID plus an attribute of PERSON_TYPE ('CUST' or 'SUPP'). If you create the primary key on PERSON_ID,PERSON_TYPE you can reference that in the subtype tables (SUPPLIER/CUSTOMER).
Then you add a unique constraint on the person_id to ensure that any value of person_id must be either a customer or supplier but not both, and check constraints on the subtype tables so that only one type is represented in the table.
create table person
(person_id number,
person_type varchar2(4),
name varchar2(10),
constraint person_pk primary key (person_id, person_type),
constraint person_id_uk unique (person_id));
create table supplier
(supplier_id number,
supplier_type varchar2(4),
blah varchar2(10),
constraint supplier_pk primary key (supplier_id, supplier_type),
constraint supp_pers_fk foreign key (supplier_id, supplier_type)
REFERENCES person (person_id, person_type)
)
/
alter table supplier add constraint supp_type_ck check (supplier_type = 'SUPP');
Its not pretty but types/subtypes are more of an object concept than a relational one.
My solution inspired by Justin:
CREATE OR REPLACE TRIGGER abc
BEFORE INSERT OR UPDATE ON a
FOR EACH ROW
DECLARE
v_testB NUMBER:= 0;
v_testC NUMBER:= 0;
BEGIN
SELECT
COUNT(bkey)
INTO
v_testB
FROM
b
WHERE
bkey = :new.aKey;
SELECT
COUNT(ckey)
INTO
v_testC
FROM
c
WHERE
ckey = :new.aKey;
IF ((v_testB + v_testC) <> 1) THEN
RAISE_APPLICATION_ERROR(-20002,'Foreign key to B or C missing.');
END IF;
END;
/
SHOW ERRORS TRIGGER abc
Create a materialized view that unions tables B & C, and point your FK constraint to the view