Sql (Oracle)-- cannot insert value(could be the constraint factor) - sql

As you can see in the code. three table have its own primary key. "protectmedalno" and "mastermedalno" are the foreign key of the player table.
protectmedalno could not be null. masterdealno could be null. I drop table protector first, then drop master , the last drop player.
There is weak relationship between table player and table master.
There is no problem with inserting the value of protector and master.
But inserting the value into table player, it will occur:
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
I think that it is a problem with constraint.
insert into player values('01','Joe','101','');
insert into player values('02','Elsa','102','201');
insert into protector values('101','Dragon');
insert into protector values('102','Lion');
insert into master values('201','Fairy')
commits;
It could display the protector table and the master table.
But it could not show the player table.
drop table protector;
drop table master;
drop table player;
CREATE TABLE player (
playno NUMBER(2) NOT NULL,
playname VARCHAR2(30) NOT NULL,
protectmedalno CHAR(10) NOT NULL,
mastermedalno CHAR(10)
);
ALTER TABLE player ADD CONSTRAINT play_pk PRIMARY KEY ( playno );
CREATE TABLE protector (
protectmedalno CHAR(3) NOT NULL,
protectname VARCHAR2(30) NOT NULL
);
ALTER TABLE protector ADD CONSTRAINT protector_pk PRIMARY KEY ( protectmedalno );
CREATE TABLE master (
mastermedalno CHAR(3) NOT NULL,
mastername VARCHAR2(30) NOT NULL
);
ALTER TABLE master ADD CONSTRAINT master_pk PRIMARY KEY ( mastermedalno );
ALTER TABLE player
ADD CONSTRAINT player_protector_fk FOREIGN KEY ( protectmedalno )
REFERENCES protector ( protectmedalno );
ALTER TABLE player
ADD CONSTRAINT player_master_fk FOREIGN KEY ( mastermedalno )
REFERENCES master ( mastermedalno );

Since protector and master are the primary tables, you should populate the records there first. Then, insert into player and refer to those records:
insert into protector values('101','Dragon');
insert into protector values('102','Lion');
insert into master values('201','Fairy');
insert into player values('01','Joe','101','201'); -- refer to master
insert into player values('02','Elsa','102','201'); -- refer to master
Note that I edited the inserts into the player table such that both records refer to a record in the master table which actually exists.

You first have to insert protector and master, afterwards insert player since player refers to master and protector and values have to be inside there.
Do otherwise round on delete...
insert into protector values('101','Dragon');
insert into protector values('102','Lion');
insert into master values('201','Fairy');
insert into player values('01','Joe','101','');
insert into player values('02','Elsa','102','201');
If you delete first delete from player, then from protector and master.

To insert data in the player table, you need a record in the protector table. This is because of the foreign key restriction.
When inserting data in a table that has a foreign key(Which in this case of protector vs player, cannot be null), you have to create the foreign record first.
1. insert into protector values('101','Dragon');
2. insert into player values('01','Joe','101','');
3. insert into protector values('102','Lion');
4. insert into master values('201','Fairy');
5. insert into player values('02','Elsa','102','201');
commits;
I hope this helps, happy debugging :)

You are inserting in the wrong order: you must insert the master and protector first so that when you insert the player it can reference them:
insert into protector values('101','Dragon');
insert into protector values('102','Lion');
insert into master values('201','Fairy');
insert into player values('01','Joe','101',NULL);
insert into player values('02','Elsa','102','201');
Edit: '' is not NULL it's an empty String. To insert null use the explicit NULL jeyword.

Always include the columns when doing an insert. You should also use single quotes for only string and date constants.
insert into player(playno, playname, protectmedalno, mastermedalno)
values(1, 'Joe', '101', '');
I don't think the problem is specifically on player, but you should do this for all your inserts and you'll find the problem.

Populating the "parent" tables first (as our colleagues have suggested) is a step towards solving the problem. In order to get the foreign key constraint to work properly, I suggest modifying the DDL code, too.
With your tables in place (using Oracle 12c), we can do the following:
begin
insert into master ( mastermedalno, mastername ) values ('201','Fairy') ;
insert into protector ( protectmedalno, protectname )
values( '101', 'Dragon');
insert into protector ( protectmedalno, protectname )
values( '102', 'Lion');
end ;
/
SQL> select * from master;
MAS MASTERNAME
--- ------------------------------
201 Fairy
SQL> select * from protector ;
PRO PROTECTNAME
--- ------------------------------
101 Dragon
102 Lion
So far so good. When INSERTing into PLAYER, we get:
insert into player ( playno, playname, protectmedalno, mastermedalno )
values('02', 'Elsa', '102', '201');
-- ORA-02291: integrity constraint (...PLAYER_MASTER_FK) violated - parent key not found
Suggestion: use the same datatype for the foreign key and the referenced key. Just drop the PLAYER table (including its constraints), and create it afresh:
drop table player cascade constraints ;
CREATE TABLE player (
playno NUMBER(2) NOT NULL,
playname VARCHAR2(30) NOT NULL,
protectmedalno CHAR(3) NOT NULL, -- changed (was: CHAR(10))
mastermedalno CHAR(3) -- changed (was: CHAR(10))
);
ALTER TABLE player
ADD CONSTRAINT player_protector_fk FOREIGN KEY ( protectmedalno )
REFERENCES protector ( protectmedalno );
ALTER TABLE player
ADD CONSTRAINT player_master_fk FOREIGN KEY ( mastermedalno )
REFERENCES master ( mastermedalno );
Now execute the INSERTs.
begin
insert into player values('01','Joe','101',''); -- original INSERT
insert into player values('02','Elsa','102','201'); -- original INSERT
commit;
end;
/
-- PL/SQL procedure successfully completed.
The tables contain the following data now:
SQL> select * from player ;
PLAYNO PLAYNAME PROTECTMEDALNO MASTERMEDALNO
1 Joe 101 NULL
2 Elsa 102 201
SQL> select * from master ;
MASTERMEDALNO MASTERNAME
201 Fairy
SQL> select * from protector;
PROTECTMEDALNO PROTECTNAME
101 Dragon
102 Lion
Are both foreign key constraints working now? Yes.
SQL> insert into player values('03','Fifi','101','202');
Error starting at line : 1 in command -
insert into player values('03','Fifi','101','202')
Error report -
ORA-02291: integrity constraint (...PLAYER_MASTER_FK) violated - parent key not found
SQL> insert into player values('03','Fifi','103','201');
Error starting at line : 1 in command -
insert into player values('03','Fifi','103','201')
Error report -
ORA-02291: integrity constraint (...PLAYER_PROTECTOR_FK) violated - parent key not found

Related

How can I insert values into a table with a composite primary key?

These are the tables I already have:
CREATE TABLE Gyartok
(
GyID INT IDENTITY(2, 3),
Nev VARCHAR(20),
CONSTRAINT PK_Gyartok PRIMARY KEY (GyID)
)
CREATE TABLE Focicsuka
(
CsID INT IDENTITY(2, 2),
Meret INT,
CONSTRAINT PK_Focicsuka PRIMARY KEY (CsID)
)
CREATE TABLE FcsGyartjaGya
(
GyID INT IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1
FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2
FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya
PRIMARY KEY (GyID, CsID)
)
The problem is that every time I try to add new values to the table (like such)
INSERT INTO FcsGyartjaGya (Ar) VALUES (300);
I get an error saying I didn't initialize the CsID INT column:
Cannot insert the value NULL into column 'CsID', table 'Lab3.dbo.FcsGyartjaGya'; column does not allow nulls. INSERT fails.
I know I must initialize it with something, but I have no idea what do to it with, because IDENTITY(x, y) doesn't work (it's occupied by another column already) and adding another parameter to the code (like such)
INSERT INTO FcsGyartjaGya (Ar, CsID) VALUES (300, 7);
creates another error which says
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Lab3a", table "dbo.Gyartok", column 'GyID'.
It is important to note that I already filled every column with data, so that couldn't be the problem.
As I mention in the comments, your INSERT will work fine, provided the stars align correctly. For your table Gyartok you have GyID as your PRIMARY KEY, which is defined as a IDENTITY(2,3); so the first value generated is 2 and then each row attempted to be INSERTed will increment by 3.
So, if we run the following, we get the IDs 2, 5, 7 and 17. (11 and 14 are skipped as the INSERT failed).
CREATE TABLE Gyartok (
GyID INT IDENTITY(2, 3),
Nev VARCHAR(20),
CONSTRAINT PK_Gyartok PRIMARY KEY (GyID)
);
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES ('asdfjahsbvd'),
('ashjkgdfakd'),
('kldfbhjo');
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES (REPLICATE('A',25)), --Force a truncation error
('ashjkgdfakd');
GO
INSERT INTO dbo.Gyartok (Nev)
VALUES (REPLICATE('A',15));
Let's now add some data for your other table:
CREATE TABLE Focicsuka (
CsID INT IDENTITY(2, 2),
Meret INT,
CONSTRAINT PK_Focicsuka PRIMARY KEY (CsID)
)
INSERT INTO dbo.Focicsuka (Meret)
VALUES(12),
(25);
Now we want to INSERT into the table FcsGyartjaGya, defined as the following:
CREATE TABLE FcsGyartjaGya (
GyID INT IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1 FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2 FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya PRIMARY KEY (GyID, CsID)
)
This has a IDENTITY on GyID, but defined as an IDENTITY(3,2), so the first value is 3 and then incremented by 2.
As this has 2 foreign keys, on GyID and CsID when we INSERT the row the values must appear in the respective tables. As GyID is defined as anIDENTITY(3,2) however, this is where we need to rely on the Stars luck for the INSERT to work. Why? Well 2 + (3*n) and 3+(2*n) can give very different numbers. The first are as you saw at the start of this answer. For the latter, we have numbers like 3, 5, 7, 9, 11. As you can see, only 1 in 3 of these numbers match a number in our original sequence, so luck is what we are going to be relying on.
Let's, therefore, try a single INSERT.
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(2,1);
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Sandbox", table "dbo.Gyartok", column 'GyID'.
Well, that didn't work, but it was expected. 3 isn't a value in the table Gyartok. Let's try again!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(2,2);
It worked! The stars Luck was our side, and the IDENTITY value was a value in the table Gyartok. Let's try a couple of rows this time!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,3),
(4,4);
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_FcsGyartjaGya1". The conflict occurred in database "Sandbox", table "dbo.Gyartok", column 'GyID'.
No!! Not again. :( That's because the stars didn't align; 7 and 9 aren't in the other table. But wait, 11 was in the sequence, so let's try that:
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,5);
Error, again?! No, it cannot be!!! :( Oh wait, I forgot, the stars were against us before, because that INSERT failed against Gyartok for the value of 11. I need to wait for 17!
--13 fails
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
GO
--15 fails
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
GO
--17 works!
INSERT INTO dbo.FcsGyartjaGya (CsID,Ar)
VALUES(4,6);
And now we have another row in our table.
So what is the problem? Your design. GyID is defined as an IDENTITY and a FOREIGN KEY; meaning you are at the "whims" of SQL Server generating a value valid. This is not what you want. Just don't define the column as an IDENTITY and then INSERT the data with all 3 of your columns defined:
CREATE TABLE FcsGyartjaGya (
GyID int,-- IDENTITY(3, 2),
CsID INT,
Ar INT,
CONSTRAINT FK_FcsGyartjaGya1 FOREIGN KEY (GyID) REFERENCES Gyartok(GyID),
CONSTRAINT FK_FcsGyartjaGya2 FOREIGN KEY (CsID) REFERENCES Focicsuka(CsID),
CONSTRAINT PK_FcsGyartjaGya PRIMARY KEY (GyID, CsID)
)
GO
INSERT INTO dbo.FcsGyartjaGya (GyID, CsID, Ar)
VALUES(2,2,1),
(2,4,2),
(5,4,3),
(8,2,4),
(8,4,5);
And all these rows insert fine.
I think there is a bit confusion, if I understand correctly what You're trying to do, then you have two tables each with their own id, which is based on an identity column, so you get new values in those for free.
Then you are trying to make a relation table with extra data.
Issue 1: You cannot have FcsGyartjaGya.GyID be identity if it refers to Gyartok.GyID because you will want to insert into it and not rely on an auto increment. If it doesn't refer to the same it should have another name or my head will possibly explode :))
Issue 2: When populating a relation table you need to insert it with what pairs you want, there is no way SQL server can know how it should match these identity pairs in the relation table
I think this is what people are aiming at in the comments, for example
to insert a relationship between row with Focicsuka.CsID = 1 to Gyartok.GyID 7 and adding Ar = 300 have to look like
INSERT INTO FCSGYARTJAGYA(GYID, CSID, AR)
VALUES(7, 1, 300)
Unless You've forgotten to mention that you want to put some value for each of some value or based on something which can be scripted, in other words unless You have logics to define the pairs and their values, relationship tables cannot have defaults on their foreign key fields.

Violating foreign key constraint with deferred constraint

I'm trying to set my sql scripts into a transaction to achieve atomicity with my database.
The table structure is (simplified):
CREATE TABLE foo (
id serial NOT NULL,
foo varchar(50) NOT NULL,
CONSTRAINT foo_pk PRIMARY KEY (id)
);
CREATE TABLE access (
id serial NOT NULL,
foo_id int NULL
CONSTRAINT access_pk PRIMARY KEY (id)
);
ALTER TABLE access ADD CONSTRAINT access_foo
FOREIGN KEY (foo_id)
REFERENCES foo (id)
ON DELETE CASCADE
ON UPDATE CASCADE
DEFERRABLE
INITIALLY DEFERRED;
In my code I first declare:
client.query('BEGIN'); (I'm using npm library 'pg') then
insert a row into a table 'foo', then another insert to 'access' with a foo_id from the first insert. After that there is client.query('COMMIT');
All of this is in a try catch, and in the catch is client.query('ROLLBACK'); and the rolling back seems to be working if there is an issue either of the inserts. When everything should be committed I still end up in the catch block for this:
message: "insert or update on table "access" violates foreign key constraint "access_foo""
detail: "Key (foo_id)=(20) is not present in table "foo"."
I thought that deferring constraint would be enough to do this, but I guess I'm wrong. Any help is welcome.
You probably have some issue with the transaction demarcation. I ran a simple test and works wells.
insert into foo (id, foo) values (1, 'Anne');
start transaction;
insert into access (id, foo_id) values (101, 1);
insert into access (id, foo_id) values (107, 7); -- 7 does not exist yet...
insert into foo (id, foo) values (7, 'Ivan'); -- 7 now exists!
commit; -- at this point all is good
See running example at DB Fiddle.

How is unique constraint applied from more than one table in oracle?

I have 3 tables is shown this tables:
table A
A(
code1
.
.
.
)
table B
B(
code2
.
.
.
)
table C
C(
code3
.
.
.
)
I want to be unique between code1,code2,code3 of this tables.
How do i recieve to my goal in oracle?
Does any syntax of oracle exist about this problem?
Based on materialized view.
P.s.
The code is not validated.
I currently have access only to oracle XE 11gR2, so I'm not able to use the materialized view log feature.
create table A (code int primary key);
create table B (code int primary key);
create table C (code int primary key);
create materialized view log on a with primary key;
create materialized view log on b with primary key;
create materialized view log on c with primary key;
create materialized view ABC_MV
refresh fast
as
select code from A
union all select code from B
union all select code from C
;
alter table ABC_MV add unique (code);
You can do that with trigger.
CREATE OR REPLACE TRIGGER table1_check
BEFORE INSERT OR UPDATE ON table1
FOR EACH ROW
BEGIN
IF EXISTS (
SELECT attribute FROM table2
WHERE attribute = :NEW.attribute
) THEN
RAISE_APPLICATION_ERROR(-20001,
'Already exist in table2');
END IF;
END;
/
You can modify it to check in more tables as well.
Using a 4th table
create table ABC (tab char(1) not null ,code int primary key, unique (tab,code));
create table A (tab char(1) as ('A') virtual not null,code int primary key,foreign key (tab,code) references ABC(tab,code));
create table B (tab char(1) as ('B') virtual not null,code int primary key,foreign key (tab,code) references ABC(tab,code));
create table C (tab char(1) as ('C') virtual not null,code int primary key,foreign key (tab,code) references ABC(tab,code));
insert into ABC (tab,code) values ('A',1);
insert into A (code) values (1);
insert into A (code) values (1);
[Code: 1, SQL State: 23000] ORA-00001: unique constraint (SYS.SYS_C0012834) violated
insert into B (code) values (1);
[Code: 2291, SQL State: 23000] ORA-02291: integrity constraint
(SYS.SYS_C0012839) violated - parent key not found

sql trigger not firing with insert

DROP TABLE ENROLLMENT CASCADE CONSTRAINTS;
DROP TABLE SECTION CASCADE CONSTRAINTS;
CREATE TABLE SECTION
(
SectionID CHAR(5),
Course VARCHAR2(7),
Students NUMBER(2,0) DEFAULT 0,
CONSTRAINT PK_SECTION
PRIMARY KEY (SectionID)
);
CREATE TABLE ENROLLMENT
(
SectionID CHAR(5),
StudentID CHAR(7),
CONSTRAINT PK_ENROLLMENT
PRIMARY KEY (SectionID, StudentID),
CONSTRAINT FK_ENROLLMENT_SECTION
FOREIGN KEY (SectionID)
REFERENCES SECTION (SectionID)
);
INSERT INTO SECTION (SectionID, Course) VALUES ( '12345', 'CSC 355' );
INSERT INTO SECTION (SectionID, Course) VALUES ( '22109', 'CSC 309' );
INSERT INTO SECTION (SectionID, Course) VALUES ( '99113', 'CSC 300' );
INSERT INTO SECTION (SectionID, Course) VALUES ( '99114', 'CSC 300' );
SELECT * FROM SECTION;
COMMIT;
CREATE TRIGGER AddStudent AFTER INSERT ON ENROLLMENT
BEGIN
DBMS_OUTPUT.PUT_LINE('DONE');
END;
All I am trying to see is if the trigger is fired and when I run a script like INSERT INTO enrollment VALUES('12345','1234567');
I have no output, just "1 row inserted" but I do not get "done" making me thing the trigger is not fired.
The only observable effect of your insert trigger is this:
DBMS_OUTPUT.PUT_LINE('DONE');
This just puts a message into the debug buffer. To see the result, you need to enable DBMS Output.
You can do this in SQL Developer via the View menu, choose Dbms Output, and click the green "+" button. Then run your code and you should see the output, if any.
If you use SQL*Plus instead, you would run SET SERVEROUT ON.

Basic primary key / foreign key with constraint, sequence, trigger

Learner here in Oracle 11g. I'm having an issue with INSERTing some rows into two tables that are linked by a primary/foreign key relationship.
Basically I create a sequence to start with 1000 and increment by 1.
Then create a 'STORE' table with a ST_ID column
The ST_ID column is linked to the SEQUENCE with a TRIGGER.
Then I have an 'EMPLOYEE' table that has a EST_ID field that is a foreign key to the ST_ID column in the STORE table.
However, when I tried to insert rows I initially got a error saying EST_ID could not be null. So I created a sequence and trigger for EST_ID and now I'm getting an error saying the foreign key constraint is being violated.
I think that was maybe the wrong thing to do. Do I really want E_ID and EST_ID to be identical and how would I get that to happen? With some kind of trigger?
The actual code:
CREATE SEQUENCE "STORSEQ" MINVALUE 1000 MAXVALUE 9999 INCREMENT BY 1 START WITH 1000 NOCACHE NOORDER
NOCYCLE ;
CREATE TABLE "STORE"
( "ST_ID" CHAR(4) NOT NULL ENABLE,
"STADDR_ID" CHAR(4) NOT NULL ENABLE,
CONSTRAINT "STORE_PK" PRIMARY KEY ("ST_ID") ENABLE
) ;
CREATE TABLE "EMPLOYEE"
( "E_ID" CHAR(8) NOT NULL ENABLE,
"EF_NAME" VARCHAR2(20) NOT NULL ENABLE,
"EL_NAME" VARCHAR2(20) NOT NULL ENABLE,
"EST_ID" CHAR(4) NOT NULL ENABLE,
CONSTRAINT "EMPLOYEE_PK" PRIMARY KEY ("E_ID") ENABLE
) ;
alter table "EMPLOYEE" add CONSTRAINT "EMPLOYEE_CON" foreign key ("EST_ID") references
"STORE" ("ST_ID")
/
CREATE OR REPLACE TRIGGER "BI_STORE"
before insert on "STORE"
for each row
begin
if :NEW."ST_ID" is null then
select "STORSEQ".nextval into :NEW."ST_ID" from dual;
end if;
end;
/
At the moment my INSERT code looks like this:
INSERT INTO STORE
(ST_ID, STADDR_ID)
VALUES
(DEFAULT, DEFAULT);
INSERT INTO EMPLOYEE
(EF_NAME, EL_NAME)
VALUES
('James', 'Smith');
When you try to insert data into table that has foreign key reference, it will not get value for id automatically, you need to pass that value.
You can do this:
declare
v_store_id integer;
begin
INSERT INTO STORE (ST_ID, STADDR_ID) VALUES (DEFAULT, DEFAULT)
RETURNING ST_ID INTO v_Store_id;
INSERT INTO EMPLOYEE (EF_NAME, EL_NAME, EST_ID)
VALUES ('James', 'Smith', v_store_id);
end;
You can also insert id in store id table without trigger using this
declare
v_store_id integer;
begin
INSERT INTO STORE (ST_ID, STADDR_ID) VALUES ("STORSEQ".nextval, DEFAULT)
RETURNING ST_ID INTO v_Store_id;
INSERT INTO EMPLOYEE (EF_NAME, EL_NAME, EST_ID)
VALUES ('James', 'Smith', v_store_id);
end