Error with adding foreign key constraints? - sql

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

Related

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 tables with primary and foreign key at same time

Very new to SQL and have spent a day on this already.
Here are my two tables:
Centre(cid, name, location, nurse_supervisor)
Nurse(nid, name, centre_id, certificate)
I have a big problem. The (nurse_supervisor) in Centre is a foreign key to Nurse (nid).
The (centre_id) in Nurse is a foreign key to (Centre cid).
I can't figure out how to populate these tables. I have tried:
INSERT ALL, which produces "A foreign key value has no matching primary key value"
I have tried removing the foreign key constraints and adding them after populating the tables but when I do that it says I can't add a constraint to tables with preexisting data.
I tried removing NOT NULL - but realized that was silly as the constraints will be enforced anyways.
Everything I look through says populate the parent table first and then the child, but these tables are linked to each other.
I am using SQL developer.
This is a poor schema design, but one way to get around it would be to:
Make both centre_id and nurse_supervisor columns NULL in the two table definitions
Insert all rows into both tables, but with NULL for those two columns
Update centre_id to the correct value for each row in the Nurse table
Update nurse_supervisor to the correct value for each row in the Centre table

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

Error Adding Multiple FK Relationship in SQL Server 2008

Consider we have two tables ProductType and ProductSizeGroup as below
ProductType
Id
Name
MaleSizeGroupId
FemaleSizeGroupId
ChildSizeGroupId
ProductSizeGroup
Id
Name
Each of MaleSizeGroupId, FemaleSizeGroupId and ChildSizeGroupId fields should be FKs to ProductSizeGroup.Id.
I add one using the following statement:
ALTER TABLE [dbo].[ProductType]
WITH CHECK ADD CONSTRAINT
[FK_ProductType_ProductSizeGroup_Male] FOREIGN KEY([MaleGroupId])
REFERENCES [dbo].[ProductSizeGroup] ([Id])
This works fine. I try to add the next using
ALTER TABLE [dbo].[ProductType]
WITH CHECK ADD CONSTRAINT
[FK_ProductType_ProductSizeGroup_Female] FOREIGN KEY([FemaleGroupId])
REFERENCES [dbo].[ProductSizeGroup] ([Id])
But I get the error:
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_ProductType_ProductSizeGroup_Female". The conflict
occurred in database "dbname", table "dbo.ProductSizeGroup", column
'Id'.
So there is conflict.. but what conflict? What should I be looking for?
That just means: there are rows in your table ProductType that have values in the FemaleGroupId column which do not exist in the referenced table (ProductSizeGroup).
It's not a problem per se - you can totally have multiple columns going from one table to another.
The problem is with the existing data - you have data in there that doesn't live up to that FK constraint. Fix that data and you should be fine.
To find those offending rows, use a query like this:
SELECT *
FROM [dbo].[ProductType]
WHERE FemaleGroupId NOT IN (SELECT DISTINCT Id FROM [dbo].[ProductSizeGroup])
That will list all offending rows - update their attribute and get going again!

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