Error report: SQL Error: A foreign key value has no matching primary key value. Completely baffled - sql

I can safely say that I am new to SQL and therefore upon writing the code to insert data into a table, I received an error report, that I can't seem to understand what it means, therefore I am hoping someone out there may be able to tell me what silly mistake I am making and remove a lot of stress ^.^
This is the error code I got:
Error report:
SQL Error: ORA-02291: integrity constraint (H.VENDOR_ID_FK) 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.
Thanks in advance!

If I run all of that I get several errors before this point, which I'll skip over for now... the first one against this FK seems to be:
INSERT INTO parts_order VALUES
(2
,2
,95115995
,'Delivered'
,'04/dec/2012'
,'01/jan/2013'
,'20/dec/2012'
,'Handler Pro'
);
It's better to put the columns in the insert clause so you can see what lines up (i.e. INSERT INTO parts_order (order_id, job_id, vendor_id, ...) VALUES (4, 4, 95115995, ...), and also so you (and we) don't have to refer back to the table definition, and to avoid failures if the definition changes in the future. It's also better not to rely on implicit date conversions (i.e. use to_char('05/jan/2013', 'DD/mon/YYYY').
Anyway... the constraint it's complaining about is VENDOR_ID_FK, which we can see in the table definition:
CREATE TABLE parts_order
( order_id NUMBER(11)
CONSTRAINT order_id_pk PRIMARY KEY
,job_id NUMBER(11)
CONSTRAINT job_id_fk REFERENCES maintenance(job_id)
,vendor_id NUMBER(11)
CONSTRAINT vendor_id_fk REFERENCES parts_vendor(part_vendor_id)
,parts_status VARCHAR2(20)
,date_ordered DATE
,date_arrived DATE
,date_delivery_due DATE
,part_name VARCHAR2(20)
CONSTRAINT part_name_nn NOT NULL);
... is against parts_vendor(part_vendor_id). What the error is saying is that the vendor_id you're inserting, 95115995, doesn't exist in the parent parts_vendor table - which is true, you only insert records with part_vendor_id values 1, 2, 3 and 4.
The constraint is working as intended - it's stopping you putting a 'child' record in without its 'parent' existing. You either need to create a parts_vendor record for ID 95115995, or change the vendor_id value you're trying to insert into parts_order to one that already exists.

Related

Create primary key for table with period (Temporal Validity) in Oracle SQL

I have a question regarding to primary key for Oracle Table with Period.
I have created two tables like following:
create table el_temporal_try( -- Parent Table
id number(10) not null,
ColumnA varchar(10),
constraint el_temporal_try_pk primary key (id),
period for valid_period
);
create table el_temporal_try_son( -- Son Table
id number(10) not null,
ColumnA varchar(10),
parent_id number(10),
constraint el_temporal_try_FY foreign key (parent_id) references el_temporal_try(id),
period for valid_period
);
This script gone through successfully. However I have problem with inserting data:
I have executed following two insert statements into the parent table:
1st: statement
insert into el_temporal_try
(id, columnA,valid_period_start, valid_period_end)
values
(1,'A',sysdate - 10, sysdate - 9);
Result:
1 row inserted.
2nd: statement
insert into el_temporal_try
(id, columnA,valid_period_start, valid_period_end)
values
(1,'B',sysdate - 8, sysdate - 7);
Result
ORA-00001: unique constraint (PBSVW.EL_TEMPORAL_TRY_PK) violated
I understand it is because of the "ID" column. However, my issues because this two rows are for a different period, should it be allowed?
I was intended to use this period for feature to capture the change history of a record as an alternative to flashback. However, does it means that I should not use primary key at this situation?
Thanks in advance!
The problem is related to the id column like you said. it's not possible to add the registry because the primary key is unique, then your second insert statement references the same ID from the first. You need to change the ID always you insert a line.
On Oracle 12c, you can use the identity like this link.
https://www.oracletutorial.com/oracle-basics/oracle-identity-column/
in another version, you can use sequence and trigger to do this.
https://chartio.com/resources/tutorials/how-to-define-an-auto-increment-primary-key-in-oracle/
Thanks for everyone's help on this. This most likely means I cannot use Primary Key/Foreign Key to maintain the referential integrity between the parent and son for my situation within a particular timestamp, but I have to go for something else.
Thanks a lot!

INSERT statement conflicted with foreign key constraint?

I'm having issue with an assignment I'm working on right now. The question is:
Write an INSERT statement that adds this row to the Products table:
ProductID: The next automatically generated ID
CategoryID: 4
ProductCode: dgx_640
ProductName: Yamaha DGX 640 88-Key Digital Piano
Description: Long description to come.
ListPrice: 799.99
DiscountPercent: 0
DateAdded: Today’s date/time.
Use a column list for this statement.
And the answer I came up with is:
INSERT INTO Products(CategoryID, ProductCode, ProductName, Description, ListPrice, DiscountPercent, DateAdded)
VALUES (4, 'dgx_640', 'Yamaha DGX 640 88-Key Digital Piano', 'Long description to come.', 799.99, 0, SYSDATETIME())
But when I try to execute it, an error comes up saying
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Products__Catego__3B75D760". The conflict occurred in database "MyGuitarShop", table "dbo.Categories", column 'CategoryID'.
The statement has been terminated.
Any help would be appreciated
The error is very clear - you're trying to insert a value into the CategoryID column of Products which causes a violation of the foreign key constraint to the category table.
This means: you're trying to insert a value (4) into Products.CategoryID which does not exist in the Category table. The foreign key constraint's job is to prevent exactly this case - it will not allow you to do this - for good reason.
So basically: you need to ensure that the values you're inserting into foreign key columns do exist in the referenced table (Category) before you do the INSERT.
The reference may not need to be enforced.
Make a new Database Diagram and add your two tables. Right click the connection line going between them, choose properties.
Where it says 'Enforce Foreign Key Constraint' change it to No.
This fixed the issue for me.
It is also possible that the number you're trying to insert and reference is an auto number row as a primary key in the connected table. I can only assume this can cause as issue, vs having the column be it's own editable column value.
you are trying to insert a value in the foreign key that doesn't exist in the table it reference, in you'r case it's the CategoryID.
to solve this you need to insert number 4 in the CategoryID column in the table catego first

Insert into violation of PRIMARY or UNIQUE KEY constraint Firebird 2.5

I am trying to insert a few values in an existing table, but first it makes nothing and 2nd time it shows me this error message.
My Unique KEY consists of a FK of a higher table and a counter.
If I check my tables there is no entry but it does not accept my UNIQUE Key.
Anybody with some ideas?
My test SQL Code for inserting into the view (same result with table)
INSERT INTO V_BRESZ(BRES_ID_LINKKEY, Maskenkey)
VALUES(29, 60);
For example my error message is:
violation of PRIMARY or UNIQUE KEY constraint "UK_BRESZ" on table
"BRESZ". Problematic key value is ("MASKENKEY" = ' 60',
"BRES_ID_LINKKEY" = 29).
But there is no such entry in my table / view.

H2 Database Primary Key Violation

I am trying to make inserts on a table with a Primary key composed of 2 attributes. However when I try to make an insert and one of the attributes in the primary key is identical to one already inserted I get the following error:
Unique index or primary key violation: "CONSTRAINT_INDEX_CCC ON PUBLIC.ABWESENHEIT(DATUM) VALUES
Here is my table:
Create TABLE Abwesenheit (
s_id INTEGER NOT NULL REFERENCES Schueler(id) ON DELETE CASCADE,
entschuldigt BOOLEAN DEFAULT FALSE,
datum TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
kommentar VARCHAR(40),
kalendereintrag_id VARCHAR(40) REFERENCES Schoolsubject(name) ON DELETE CASCADE,
deleted BOOLEAN DEFAULT FALSE,
PRIMARY KEY (s_id,datum)
);
And here are 2 inserts which reproduce the problem:
insert into Abwesenheit (s_id, entschuldigt, kommentar,datum,kalendereintrag_id) values (1,'false','','2015-12-21 11:59:00.0','Geschichte');
insert into Abwesenheit (s_id, entschuldigt, kommentar,datum,kalendereintrag_id) values (2,'false','','2015-12-21 11:59:00.0','Geschichte');
Even though the "datum" attribute defaults to CURRENT_TIMESTAMP, I need to be able to insert custom timestamps (i.e. for retroactive entries)
.
Given the fact that the "s_id" is different in the two inserts they should work. However they do not. Any ideas on what might be causing the problem?
Thanks in advance!
The problem was caused by another table which was referencing my table, under the assumption that the dates in the table Abwesenheit were unique.

What is causing Foreign Key Mismatch error?

I have an sqlite database structured as follows:
CREATE TABLE IF NOT EXISTS Patient
( PatientId INTEGER PRIMARY KEY AUTOINCREMENT );
CREATE TABLE IF NOT EXISTS Event
(
PatientId INTEGER REFERENCES Patient( PatientId ),
DateTime TEXT,
EventTypeCode TEXT,
PRIMARY KEY( PatientId, DateTime, EventTypeCode )
);
CREATE TABLE IF NOT EXISTS Reading
(
PatientId INTEGER REFERENCES Patient( PatientId ),
DateTime TEXT REFERENCES Event (DateTime),
EventTypeCode TEXT REFERENCES Event (EventTypeCode),
Value REAL,
PRIMARY KEY( PatientId, DateTime, EventTypeCode )
);
I insert a Patient with Id #1
then I run:
INSERT INTO Event (PatientId, DateTime, EventTypeCode) VALUES (1, '2011-01-23 19:26:59', 'R')
which works
then I run:
INSERT INTO Reading (PatientId, DateTime, EventTypeCode, Value) VALUES (1, '2011-01-23 19:26:59', 'R', 7.9)
and it gives me a foreign key mismatch. Patient Id is '1' in all cases, and the datetime and typecodes match in the 2nd and 3rd queries. I do not understand what is mismatching, but I'm a bit new to actually defining foreign keys and i do not know what I am doing wrong.
I'm not familiar with SQLite but a little Google'ing turned up this. The documentation says
If the database schema contains
foreign key errors that require
looking at more than one table
definition to identify, then those
errors are not detected when the
tables are created. Instead, such
errors prevent the application from
preparing SQL statements that modify
the content of the child or parent
tables in ways that use the foreign
keys. Errors reported when content is
changed are "DML errors" and errors
reported when the schema is changed
are "DDL errors". So, in other words,
misconfigured foreign key constraints
that require looking at both the child
and parent are DML errors. The English
language error message for foreign key
DML errors is usually "foreign key
mismatch" but can also be "no such
table" if the parent table does not
exist. Foreign key DML errors are may
be
reported if:
The parent table does not exist, or
The parent key columns named in the foreign key constraint do not exist,
or
The parent key columns named in the foreign key constraint are not the
primary key of the parent table and
are not subject to a unique constraint
using collating sequence specified in
the CREATE TABLE, or
The child table references the primary key of the parent without
specifying the primary key columns and
the number of primary key columns in
the parent do not match the number of
child key columns.
I suspect you might be running into #3 in that list.
Also, while other DBs might support using a non-unique index as a foreign key reference, (see answers here), it's a bad design choice in my opinion. I would restructure so that either
Reading.PatientId references Event.PatientId so that the complete composite key from Event is referenced by Reading or,
Add an EventId auto-increment, primary key to the Event table and use that as the foreign key in the Reading table (so that you only have EventId and Value under Reading and you can get the PatientId, DateTime, EventTypeCode out of Event).
I'd suggest #2 so that you can avoid the redundancy of PatientId, DateTime and EventTypeCode in both Event and Reading.