(SQL) integrity constraint violated - parent key not found - sql

I did look up for solutions for this problem but i still get the same error..
I'm trying to insert values into PART and MANUFACTURER tables. Initially, i inserted values into MANUFACTURER without knowing the fact i need to deal with the parent table i.e. PART. So, i did the PART then the MANUFACTURER but still not working :(.
These are the tables:
PART(PNum, PName, PUnitPrice, ComponentOf)
primary key (PNum)
foreign key (ComponentOf) references PART(PNum)
MANUFACTURER(MName, MAddress, MPhone)
primary key (MName)
candidate key (MPhone)
candidate key (MAddress)
PART-MANUFACTURED(MDate, PNum, MName, Quantity)
primary key (MName, PNum, MDate)
foreign key (PNum) references PART(PNum)
foreign key (MName) references MANUFACTURER(MName)
CUSTOMER(CNum, CName, CType)
primary key (CNum)
domain constraint ctype in ('INDIVIDUAL', 'INSTITUTION')
ORDERS(CNum, PNum, OrderDate, OrderQuantity)
primary key (CNum, PNum, OrderDate)
foreign key (CNum) references CUSTOMER(CNum)
foreign key (PNum) references PART(PNum)
Create statements:
CREATE TABLE PART(PNum VARCHAR(25) NOT NULL, PName VARCHAR(75) NOT NULL, PUnitPrice NUMBER(7,2) NOT NULL, ComponentOf VARCHAR(25), PRIMARY KEY(PNum), FOREIGN KEY(ComponentOf) REFERENCES PART(PNum));
Table created.
SQL> CREATE TABLE MANUFACTURER(MName VARCHAR(50) NOT NULL, MAddress VARCHAR(100) NOT NULL, MPhone VARCHAR(25) NOT NULL, PRIMARY KEY(MName), CONSTRAINT UK_MADDRESS Unique(MAddress), CONSTRAINT UK_MPHONE UNIQUE(MPhone));
Table created.
SQL> CREATE TABLE PARTMANUFACTURED(MDate DATE NOT NULL, PNum VARCHAR(25) NOT NULL, MName VARCHAR(50) NOT NULL, QUANTITY NUMBER(10) NOT NULL, PRIMARY KEY(MName, PNum, MDate), FOREIGN KEY(PNum) REFERENCES PART(PNum), FOREIGN KEY(MName) REFERENCES MANUFACTURER(MName));
Table created.
SQL> CREATE TABLE CUSTOMER(CNum VARCHAR(25) NOT NULL, CName VARCHAR(75) NOT NULL, CType VARCHAR(20) NOT NULL, PRIMARY KEY(CNum), CHECK(Ctype in('INDIVIDUAL','INSTITUTION')));
Table created.
SQL> CREATE TABLE ORDERS(CNum VARCHAR(25) NOT NULL, PNum VARCHAR(25) NOT NULL, OrderDate DATE NOT NULL, OrderQuantity NUMBER(7,2) NOT NULL, PRIMARY KEY(CNum, PNum, OrderDate), FOREIGN KEY(CNum) REFERENCES CUSTOMER(CNum), FOREIGN KEY(PNum) REFERENCES PART(PNum));
Isn't the PNum already the primary or parent key? and PART table is the parent table? since, other tables have the PNum as foreign key.. i really don't get it..
anyone knows and can help me with it, is greatly appreciated. thanks :)

The error with your insert statement INSERT INTO PART VALUES('S001', 'System-economy', 1100, 'Null') is that you are trying to insert a string 'NULL' rather than an actual NULL for the column ComponentOf in the PART table.
The problem with the string 'NULL' is that you have a FOREIGN KEY constraint on ComponentOf that references the column PNum, which means that all the values in the column ComponentOf must also be in PNum. However, there is no value 'NULL' in PNum so that's why it threw the error. An actual NULL works since it means that it is not referencing anything.

The value inserted for ComponentOf has to match an existing PNum in the PARTS table. Your key is their to ensure you don't have any "orphaned" components.
If you try to insert 'Null' (a string value as mentioned in the comments) then it can't find the "parent". However, null is allowed since it means that particular part is not a component of any other part, i.e. it doesn't have a "parent".

Related

foreign keys: number of columns not equal to referenced columns

I'm getting an error from oracle that says "number of referencing columns must match referenced columns."
I want my column recorded_on in the table measurement to reference recorded_on in the table called sample
The column Recorded on in the Sample table must be part of a composite key together with Scientist_Num
The error is coming from
FOREIGN KEY (Recorded_On) REFERENCES Sample(Scientist, Recorded_On, Site_ID)
CREATE TABLE Sample (
Scientist_Num varchar2(5) not null,
Recorded_On date not null,
Site_ID varchar2(4) not null,
Comments clob,
Primary key (Scientist_Num, Recorded_On),
FOREIGN KEY (Scientist_Num) REFERENCES Scientist(Scientist_Num),
FOREIGN KEY (Site_ID) REFERENCES Site(Site_ID)
);
CREATE TABLE Measurement (
Site_ID varchar2(4) not null,
Recorded_On date not null,
Name varchar2(10) not null,
Value varchar2(10),
Outlier_Indicator varchar2(10),
Primary key (Site_ID, Recorded_On, Name),
FOREIGN KEY (Site_ID) REFERENCES Sample(Site_ID),
FOREIGN KEY (Recorded_On) REFERENCES Sample(Scientist, Recorded_On, Site_ID)
);
The Scientist_Num and Recorded_On columns must be in a composite key together.
The answer to my problem and an explanation of what went wrong would be greatly appreciated.
You can create virtual column in sample table:
Recorded_virtual varchar2(5) [GENERATED ALWAYS] AS
(Scientist||Recorded_On||Site_ID) [VIRTUAL]
And create reference to this column:
CONSTRAINT fk_column
FOREIGN KEY (Recorded_On)
REFERENCES Sample(Recorded_virtual )
Foreign key references need to match the primary keys in number and type. So I think you intend:
CREATE TABLE Measurement (
Site_ID varchar2(4) not null,
Scientist_Num varchar2(5) not null,
----^ added for foreign key reference
Recorded_On date not null,
Name varchar2(10) not null,
Value varchar2(10),
Outlier_Indicator varchar2(10),
Primary key (Site_ID, Recorded_On, Name),
FOREIGN KEY (Site_ID) REFERENCES Site(Site_ID),
-------------------------------------^ Presumably you intend the site table
FOREIGN KEY (Scientist_Num, Recorded_On) REFERENCES
Sample(Scientist_Num, Recorded_On)
-----------------^ two columns, both need to already be defined
);
I suspect there are other issues with your data model, but this should fix the syntax error. If you want further help, then ask another question.

Why is parent key not found?

When I insert data into the ASSIGNMENTS table it all works fine except for the HARDWARE and SOFTWARE values, which are coded exactly in the same way as the others. I just don't get it.
This works:
INSERT INTO ASSIGNMENTS (ASSIGNMENT_ID, PROJECT_ID, STAFF_ID, JOB_ID)
VALUES ('A0005','B0002','ST002','J0002');
But when I try to include values for HARDWARE or SOFTWARE, like this:
INSERT INTO ASSIGNMENTS (ASSIGNMENT_ID, PROJECT_ID, STAFF_ID, JOB_ID, HARDWARE_ID)
VALUES ('A0005','B0002','ST002','J0002','H0002');
I just get the following error:
SQL Error: ORA-02291: integrity constraint (JAS1224.SYS_C0028418) violated - parent key not found
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.
Here is all the code, and all of the tables have been populated correctly (the hardware and software tables are coded in exactly the same format as the staff table):
CREATE TABLE PROJECT
(PROJECT_ID CHAR(5) NOT NULL,
PROJECT_NAME CHAR(20),
PROJECT_TYPE CHAR(20),
START_DATE DATE,
END_DATE DATE,
PRIMARY KEY (PROJECT_ID));
CREATE TABLE HARDWARE
(HARDWARE_ID CHAR(5) NOT NULL,
HARDWARE_NAME CHAR(20),
PRIMARY KEY (HARDWARE_ID));
CREATE TABLE SOFTWARE
(SOFTWARE_ID CHAR(5) NOT NULL,
SOFTWARE_NAME CHAR(20),
PRIMARY KEY (SOFTWARE_ID));
CREATE TABLE STAFF
(STAFF_ID CHAR(5) NOT NULL,
STAFF_NAME CHAR(20),
PRIMARY KEY (STAFF_ID));
CREATE TABLE JOB
(JOB_ID CHAR(5) NOT NULL,
JOB_TYPE CHAR(20),
JOB_GRADE CHAR(20),
PRIMARY KEY (JOB_ID));
CREATE TABLE ASSIGNMENTS
(ASSIGNMENT_ID CHAR(5) NOT NULL,
PROJECT_ID CHAR(5),
STAFF_ID CHAR(5),
JOB_ID CHAR(5),
HARDWARE_ID CHAR(5),
SOFTWARE_ID CHAR(5),
PRIMARY KEY (ASSIGNMENT_ID),
FOREIGN KEY (PROJECT_ID) REFERENCES PROJECT(PROJECT_ID),
FOREIGN KEY (STAFF_ID) REFERENCES STAFF(STAFF_ID),
FOREIGN KEY (JOB_ID) REFERENCES JOB(JOB_ID),
FOREIGN KEY (HARDWARE_ID) REFERENCES HARDWARE(HARDWARE_ID),
FOREIGN KEY (SOFTWARE_ID) REFERENCES SOFTWARE(SOFTWARE_ID));
The error message may be a bit cryptic at first, but it is pretty clear.
The only difference between the two INSERTs is for HARDWARE_ID. Hence 'H0002' is not a valid HARDWARE_ID. It is not in the HARDWARE table.

error: there is no unique constraint matching given keys for referenced table "incident"

I know that this question has been already answered a million of times, but I couldn't find any solution. Well I have these three tables on postgres sql.
CREATE TABLE user_account (
id SERIAL not null,
firstName VARCHAR(60) not null,
lastName VARCHAR(60) not null,
password VARCHAR(150) not null,
email VARCHAR(40) not null UNIQUE,
isVolunteer BOOLEAN,
complete BOOLEAN,
CONSTRAINT pk_user PRIMARY KEY (id));
CREATE TABLE incident (
id SERIAL not null,
patientId INTEGER not null,
incidentTime VARCHAR(10) not null,
latitude NUMERIC not null,
longitude NUMERIC not null,
city VARCHAR(60) not null,
state VARCHAR(60),
country VARCHAR(60),
complete BOOLEAN,
CONSTRAINT pk_incident PRIMARY KEY (id, patientId),
CONSTRAINT fk_incident FOREIGN KEY (patientId)
REFERENCES user_account (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE);
CREATE TABLE incident_has_volunteer (
incidentId INTEGER not null,
volunteerId INTEGER not null,
incidentTime VARCHAR(10) not null,
complete BOOLEAN,
CONSTRAINT pk_incident_has_volunteer PRIMARY KEY (incidentId, volunteerId),
CONSTRAINT fk_volunteer FOREIGN KEY (volunteerId)
REFERENCES user_account (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_incident FOREIGN KEY (incidentId)
REFERENCES incident (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE);
When I try to create the table incident_has_volunteer it throws the error there is no unique constraint matching given keys for referenced table "incident".
I tried to add on the third table and the patientId as a foreign key from table incident table but with no luck. I can't understand why it throws this error even if I have already set the primary keys on the incident table.
I'm not an expert in postgres, but I believe that the problem is while fk_incident is referencing incident.id, incident's primary key is made of id + patientId. Since incident.id is guaranteed to be unique only in combination with patientId, there's no way to ensure referential integrity.
I believe that if you add a unique constraint to incident.id (I'm assuming that it would be unique), your foreign key will be legal.
Very simply - one table of primary key acts as a foreign key for another table, so you must ensure that both key is referenced or not.
Simply you will not assign foreign key to the column of another table which does not have primary key. this is called as RDBMS.
Thanks

There are no primary or candidate keys in the referenced table error

I have a problem with combining foreign keys to different tables. For example I made a table Customers and a Table invoices. I want a foreign key from Customers to invoices so I can get the name and everything of the Customer:
Create table code of Customers:
Create Table Customers
(
customerID int IDENTITY(100,1) NOT NULL,
customer_email varchar(30) NOT NULL,
username varchar(255) NOT NULL,
password varchar(50) NOT NULL,
firstname varchar(255) NOT NULL,
lastname varchar(255) NOT NULL,
insertion varchar(10) NULL,
phonenumber int NULL,
streetname varchar(20) NOT NULL,
number int NOT NULL,
zipcode varchar(10) NOT NULL,
city varchar(255) NOT NULL,
Constraint pk_Customers
PRIMARY KEY (customerID, customer_email, username)
)
Create table code of Invoices:
Create Table Invoices
(
invoiceID int IDENTITY(1000,1) NOT NULL,
customer_email varchar(30) NOT NULL,
customerID int NOT NULL,
creationdate datetime NOT NULL DEFAULT GETDATE(),
totalAmount decimal(5,2) NOT NULL,
Constraint pk_Invoices
PRIMARY KEY (invoiceID, customer_email,creationdate)
)
The foreign key code that I want to use:
ALTER Table Invoices
ADD Constraint fk_Customers_Invoices
FOREIGN KEY (customerID) REFERENCES Customers (customerID)
ON UPDATE CASCADE
ON DELETE NO ACTION
It throws the following error:
There are no primary or candidate keys in the referenced table 'Customers' that match the referencing column list in the foreign key 'fk_Customers_Invoices'.
How can I add my foreign key?
I think it's because your primary key is a composite key:
customerID, customer_email, username
This suggests that it is only the combination of these three fields that will uniquely identify a customer, and the foreign key would need to reference all three fields.
If customerID is unique, then it should be the primary key for the table and your foreign keys would be able to use it as a reference.
For what purpose are the other fields included in the primary key?
Since your Customers table defines this primary key:
Constraint pk_Customers
PRIMARY KEY (customerID, customer_email, username)
any table that wants to reference Customers must provide all three columns of that primary key. That's the way FK constraints work.
So from your Invoices tables, you must provide all 3 columns that make up the primary key of Customers - not just one. You can never refernce only part of a primary key - it's the whole key or nothing....
ALTER Table Invoices
ADD Constraint fk_Customers_Invoices
FOREIGN KEY (customerID) REFERENCES Customers (customerID)
ON UPDATE CASCADE
ON DELETE NO ACTION
You can either:
change the PK for Customers to be just CustomerID which would make a whole lot more sense since it's an identity column
or you could add the other two columns in the Customers PK to yoru table Invoices

Primary key composed of two foreign keys? Oracle

I have a question regarding a table creation. I want to combine the attributes of "Ono" and "Pno" into a primary key for a new table. These are both foreign keys, each from different tables. Do I just use a CONSTRAINT Ono_Pno_PK PRIMARY KEY (Ono,Pno)?
what I have used so far:
CREATE TABLE ODetails
(
Ono Number Not Null,
Pno Number Not Null,
Qty Number(3) Not Null,
Creation_Date Date Not Null,
Created_By VARCHAR(10) Not Null,
Last_Update_Date Date Not Null,
Last_Updated_By VARCHAR2(10) Not Null,
CONSTRAINT Ono_FK FOREIGN KEY (Ono) REFERENCES Orders (Ono),
CONSTRAINT Pno_FK FOREIGN KEY (Pno) REFERENCES Parts (Pno)
);
just add this line after the constraints,
CONSTRAINT tb_PK PRIMARY KEY (Ono, Pno)