You can create a new user/schema using create user
clause and then start creating database tables and other objects into this schema. I would not recommend you to exploit hr
schema, I would keep that schema intact and use it for testing purposes.
If you query the table you're inserting into inside a trigger on that same table, you are likely to get "ORA-04091: table name is mutating, trigger/function may not see it." error. Check constraints cannot contain subqueries. Therefore your best option is to encapsulate logic for inserting data into a stored procedure and use that procedure instead of direct inserts.
I can assist you with writing the procedure, however, it seems to me that you have a logical flaw in your data model. Your example data shows that my_id is not a unique key for the table but rather that many rows may share the same value for my_id. So if one row with my_id = 1 has field_2 set to some value and for some other row field_2 is null, what is to be done? Don't you have a primary key in your table?
Anyways, if you want literally what you wrote in your post, you could do with something like
create or replace procedure my_practice_table_insert(p_my_id in number, p_field_2 in varchar2, p_field_3 in varchar2)
is
l_cnt number;
begin
if p_field_2 is null then
select count(*) into l_cnt from my_practice_table where my_id = p_my_id and field_2 is not null;
else
select count(*) into l_cnt from my_practice_table where my_id = p_my_id and field_2 is null;
end if;
if l_cnt = 0 then
insert into my_practice_table(my_id, field_2, field_3) values(p_my_id, p_field_2, p_field_3);
end if;
end;
I didn't actually try out the procedure so it may have slight errors, but that's the general form it could take.
Best Answer
This is very simple and there are many tutorials out there.
Here is a sample trigger to demonstrate.
In case you were wondering, "
:new
" is a reference to the newly inserted row, and each column can be referenced individually.Test case: