Parent Keys Not Found? - sql

One of the classic questions...
But I really can't find where the issue is in the parent table. I am currently working on a mini-version of the IMDB database. Our teacher tasked us with taking the original database we were given and make it into a smaller, and smarter version. It should follow this diagram:
I have so far successfully made the COMPANY_NAME, MOVIE_COMPANY, MOVIE, GENRE and PLOT tables and is currently making KEYWORD. The table itself now exists, but I cannot place the Foreign constraint which indicates that the MOVIE_ID present in keyword is from the parent table MOVIE. I keep getting the following error:
ALTER TABLE KEYWORD
ADD CONSTRAINT FK_MOVIE_ID_KEYWORD
FOREIGN KEY (MOVIE_ID)
REFERENCES MOVIE (ID)
Error report -
SQL Error: ORA-02298: cannot validate (DB_031.FK_MOVIE_ID_KEYWORD) - parent keys not found
02298. 00000 - "cannot validate (%s.%s) - parent keys not found"
*Cause: an alter table validating constraint failed because the table has
child records.
*Action: Obvious <-- especially this part is annoying
I have looked around at similar questions and then checked my statement a few times, but I have so far been unable to see why this fails. The GENRE and PLOT tables are both empty in terms of data, as they are made for future expansion of the database. But KEYWORD already have a collection of KEYWORD, MOVIE_ID pairs.
EDIT: Request Schemas

You are referencing to wrong col for parent reference....it should be MOVIE_ID rather than ID ( which u have done )
try it this way :
ALTER TABLE KEYWORD
ADD CONSTRAINT FK_MOVIE_ID_KEYWORD
FOREIGN KEY (MOVIE_ID)
REFERENCES MOVIE (MOVIE_ID) /* <- notice this */
EDIT
Only possible reason i can think of is that you table contains non-matching data....that's why you are having an error due to mismatch!!
To simplyfy....your MOVIE_ID contains value which do not exist in the ID column of the other table....so because of mismatch at the time of setting up constraint,its popping the error!!
Solution : Validate the data in your tables ( updating / deleting non-matching columns in either tables ) in relation to the id's you need to set up...then apply the constraint and it should work!!

Related

Error with adding foreign key constraints?

I am trying to create a FOREIGN KEY on the MAJORS table that references major in the MAJOR_DESCRIP table. In other words, I want to have a constraint that prevents someone from entering a major that doesn’t have a record in the MAJOR _DESCRIP table. I am new to primary and foreign keys so I'm not sure what exactly is wrong here. I will provide table data for both below along with what command I'm trying to run and the error message it throws back. Thank you in advance.
Here is the code I am trying to use to accomplish this:
ALTER TABLE MAJORS
ADD CONSTRAINT MAJORS_FK FOREIGN KEY (Major) references MAJOR_DESCRIP(Major);
The error Oracle Apex spits back is -
The issue here could be that there would be some values available in MAJOR field of MAJORS table which would have been unavailable in MAJOR field of MAJOR_DESCRIP table.
Thus, when you try putting the constraint, your constraint is not getting satisfying because of which you are facing this error.
The best possible solution will be to wipe out data from your MAJORS table and then add the constraint, thereafter adding the correct data.
The Oracle 12c Database SQL Reference contains the following statement:
A foreign key constraint requires values in one table to match values in another table.
Therefore, to fix the error you must do one of the following actions before adding the constraint.
Solution 1: Add data to MAJOR_DESCRIP
Add 3 rows into the MAJOR_DESCRIP table for Economics, Geology and Criminal Justice:
INSERT INTO MAJOR_DESCRIP (MAJOR, DESCRIPTION, YRTTRM) VALUES ('Economics', 'Get rich quick', '201801');
INSERT INTO MAJOR_DESCRIP (MAJOR, DESCRIPTION, YRTTRM) VALUES ('Geology', 'Rocks are fun', '201801');
INSERT INTO MAJOR_DESCRIP (MAJOR, DESCRIPTION, YRTTRM) VALUES ('Criminal Justice', 'Crooks and lawyers', '201801');
COMMIT;
Solution 2: Remove data from MAJOR
Delete the rows from MAJOR which reference which reference Economics, Geology and Criminal Justice, which are used by STUDENT_IDs 900374912 and 900374913:
DELETE FROM MAJOR
WHERE MAJOR IN ('Economics', 'Geology', 'Criminal Justice');
COMMIT;
Then you will be able to add the MAJOR_FK constraint.
Remove Major Column value from Majors Table then add foreign key constraint

What would be the best way to link these two tables

I have two tables in a database, both of which are derived from official government reference tables originally supplied in spreadsheet form.
The structure of these two tables are illustrated below.
Table 1 (Species Codes)
Table 2 (Allowed presentation codes)
When I try and create a relationship between the first and the second (so as to make full use of the ability to look up values in the second table I get the following error when trying to link speciescodes.FAOCode to allowedstates.ErsSpeciesCodes).
'SpeciesCodeLookup' table saved successfully
'AllowedPresentationAndStateCodesLookup' table
- Unable to create relationship 'FK_AllowedPresentationAndStateCodesLookup_SpeciesCodeLookup'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_AllowedPresentationAndStateCodesLookup_SpeciesCodeLookup". The conflict occurred in database "FishTrackerPro", table "dbo.SpeciesCodeLookup", column 'FAOCode'.
Can anyone enlighten me as to
1) why is this error occurring
2) is there a way (by altering one or other table where such a relation might be established?
It seems you are getting this issue because referential integrity is not met. I.e Foreign key table must not have values which does not exists in primary key table.
Check these links :
Alter table conflicted with foreign key constraint
SQL conflicted with the FOREIGN KEY constraint

Integrity Constraint Invalid Identifier SQL

I am new to SQL and I am currently have an issue with a constraint I am trying to put on one of my columns.
My database models an art gallery and paintings can either be in the gallery or on loan to another gallery. Obviously it can't be both so I was trying to put a constraint on my on_loan table when creating it to stop the painting ID (P_id) of my on_loan table being the same as the P_id in my in_gallery table. This is what I have done so far:
create table in_gallery (
P_id NUMBER (10) CONSTRAINT PK_IN_GALLERY PRIMARY KEY,
CONSTRAINT IN_GALLERY_FK FOREIGN KEY(P_id) REFERENCES painting(P_id) ON DELETE CASCADE);
create table on_loan (
P_id NUMBER (10),
CONSTRAINT BOOK_IS_IN_GALLERY CHECK(P_id != in_gallery(P_id)));
This comes up with the error:
ERROR at line 3:
ORA-00904: "IN_GALLERY": invalid identifier
How would i fix this error?
Thanks.
You can't reference another table like that in a check constraint.
Check the answers to the question here for some solutions. You could achieve this with a user defined function.
EDIT: Also based on the little bit of information from your post I don't think you have a correct normalized database model. You could have a Gallery table and a Painting table with a relation between the two.

ON UPDATE CASCADE with two columns in a single table in SQL Server [duplicate]

I have a database table called Lesson:
columns: [LessonID, LessonNumber, Description] ...plus some other columns
I have another table called Lesson_ScoreBasedSelection:
columns: [LessonID,NextLessonID_1,NextLessonID_2,NextLessonID_3]
When a lesson is completed, its LessonID is looked up in the Lesson_ScoreBasedSelection table to get the three possible next lessons, each of which are associated with a particular range of scores. If the score was 0-33, the LessonID stored in NextLessonID_1 would be used. If the score was 34-66, the LessonID stored in NextLessonID_2 would be used, and so on.
I want to constrain all the columns in the Lesson_ScoreBasedSelection table with foreign keys referencing the LessonID column in the lesson table, since every value in the Lesson_ScoreBasedSelection table must have an entry in the LessonID column of the Lesson table. I also want cascade updates turned on, so that if a LessonID changes in the Lesson table, all references to it in the Lesson_ScoreBasedSelection table get updated.
This particular cascade update seems like a very straightforward, one-way update, but when I try to apply a foreign key constraint to each field in the Lesson_ScoreBasedSelection table referencing the LessonID field in the Lesson table, I get the error:
Introducing FOREIGN KEY constraint 'c_name' on table 'Lesson_ScoreBasedSelection' may cause cycles or multiple cascade paths.
Can anyone explain why I'm getting this error or how I can achieve the constraints and cascading updating I described?
You can't have more than one cascading RI link to a single table in any given linked table. Microsoft explains this:
You receive this error message because
in SQL Server, a table cannot appear
more than one time in a list of all
the cascading referential actions that
are started by either a DELETE or an
UPDATE statement. For example, the
tree of cascading referential actions
must only have one path to a
particular table on the cascading
referential actions tree.
Given the SQL Server constraint on this, why don't you solve this problem by creating a table with SelectionID (PK), LessonID, Next_LessonID, QualifyingScore as the columns. Use a constraint to ensure LessonID and QualifyingScore are unique.
In the QualifyingScore column, I'd use a tinyint, and make it 0, 1, or 2. That, or you could do a QualifyingMinScore and QualifyingMaxScore column so you could say,
SELECT * FROM NextLesson
WHERE LessonID = #MyLesson
AND QualifyingMinScore <= #MyScore
AND #MyScore <= QualifyingMaxScore
Cheers,
Eric

Not able to add column value

I have project which contain 4 tables among these shedule table Session column i am not able to add vaue,,this table contain
three foriegn key from two tables(in which single table has two foreign keys here) i added values here..Any one
has any idea about this..Actually my intention is to remove the error "the insert statement conflicted with the foreign key constraint sql server"
Table Shedule contains session number as primary key,,it is used as foreign key in Q&A table.Table Q&A contains Question num
as primary key .Table Employee contain Employeeid as primary key which is used as foriegn key in Q&A table two times foriegn
key as in Shedule table .Table Topic contain Topicid as primary key which is used forign key in Shedule table ans Q&A table
Here my problem is i cant add values for session column in Shedule table(which is a primary key)
second is whenever i insert values in Q&A table i am getting error like this
Error Message: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_QandA_Schedule". The conflict occurred in database "secon", table "dbo.Schedule", column 'Session_No'.
The statement has been terminated.
the insert statement conflicted with
the foreign key constraint sql server
Obviously, you're trying to insert some value into one of the foreign-key fields that isn't a valid value in the referenced table.
You say you have three columns - check each of those against the tables they reference - shouldn't be too hard to figure out which one is not valid - and then use a valid value instead. That's the whole point of referential integrity - make sure you don't insert invalid data into your tables!
The Error means what it says. That is, it doesn't have a column according to that id in a parent table.
To be more specific, please show us tables and INSERT statement.
UPDATE: If I got you right:
1) You try to INSERT a row into table Shedule, right?
If so, you need to have the Employeeid in table Employee and a Topicid in table Topic, that you're trying to INSERT.
I suppose, you don't have a valid Q&A foreign key value, according to error message. That means, the Q&A foreign key value you're trying to add in your INSERT statement must exist in Q&A Table.
2) You try to INSERT a row into table Q&A?
For this table you need to have valid Employeeid (2 of them?), Topicid and Session_number.
P.S. But I can't tell what's your problem if you don't show us INSERT statements.
I used a Cascade rule. It's working temporarily, but I don't know the consequences.