INSERT statement conflicted with foreign key constraint? - sql

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

Related

How can I INSERT into this table?

I have set a trigger up which I need to test. To do this I need to carry out an insert into the tblSOLine table however when I do this I am getting an error which I assume relates to the way the PK/FKs are set up. Is there any way I could do an insert into this table without messing with the table relationships?
Here is what I tried:
INSERT INTO tblSOLine (SOHeaderID, ProductID, Quantity, NetSale, VAT)
VALUES (5364, 6, 6, NULL, NULL)
Here is the error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblSOLine_tblSOHeader".
The conflict occured in database "VintageSounds", table "dbo.tblSOHeader", column 'SOHeaderID'.
The error is saying that SOHeaderID = 5364 does not exist in SOHeader. You need to be sure that this value is what you intend.
You should not be getting an error if you attempt to insert this a headerid with this number, if the foreign key does not work. However, such ids are usually IDENTITY columns, so they are automatically generated. If you don't have a typo in the number, then perhaps you are confusing the number with something else, such as the customer number.

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

Why do I get a FK constraint error when the PK value exists in the referenced table

I'm trying to insert a record into a table with a Foreign Key Constraint. The constrained field is AccountID. I understand I can not insert records into the table if the value I'm inserting for AccountID does not exist in the table referenced by the constraint.
Below is an example of the insert statement I'm using:
INSERT INTO sometable (
AccountId
,TIdCode
)
VALUES (
'801143'
,2239754448
)
go
select *
from sometable
where TIdCode = 2239754448
My question is why am I getting a FK constraint error when the primary key value reference exists in the table referenced by the constraint.
I'm aware of how to disable then re-enable the constraint. However, I would like to understand why I'm getting this error.
Turns out the value was not in the table after all. I assumed the values from my production system were present in my test system. Thank you Damien_The _Unbeliever for asking a question that made me question my assumptions. Mr. Moose thank you as well for your insight.

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.

Create a one to many relationship using SQL Server

How do you create a one to many relationship using SQL Server?
Define two tables (example A and B), with their own primary key
Define a column in Table A as having a Foreign key relationship based on the primary key of Table B
This means that Table A can have one or more records relating to a single record in Table B.
If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:
ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id)
fk_b: Name of the foreign key constraint, must be unique to the database
b_id: Name of column in Table A you are creating the foreign key relationship on
b: Name of table, in this case b
id: Name of column in Table B
This is a simple example of a classic Order example. Each Customer can have multiple Orders, and each Order can consist of multiple OrderLines.
You create a relation by adding a foreign key column. Each Order record has a CustomerID in it, that points to the ID of the Customer. Similarly, each OrderLine has an OrderID value. This is how the database diagram looks:
In this diagram, there are actual foreign key constraints. They are optional, but they ensure integrity of your data. Also, they make the structure of your database clearer to anyone using it.
I assume you know how to create the tables themselves. Then you just need to define the relationships between them. You can of course define constraints in T-SQL (as posted by several people), but they're also easily added using the designer. Using SQL Management Studio, you can right-click the Order table, click Design (I think it may be called Edit under 2005). Then anywhere in the window that opens right-click and select Relationships.
You will get another dialog, on the right there should be a grid view. One of the first lines reads "Tables and Columns Specification". Click that line, then click again on the little [...] button that appears on the right. You will get this dialog:
The Order table should already be selected on the right. Select the Customer table on the left dropdown. Then in the left grid, select the ID column. In the right grid, select the CustomerID column. Close the dialog, and the next. Press Ctrl+S to save.
Having this constraint will ensure that no Order records can exist without an accompanying Customer record.
To effectively query a database like this, you might want to read up on JOINs.
This is how I usually do it (sql server).
Create Table Master (
MasterID int identity(1,1) primary key,
Stuff varchar(10)
)
GO
Create Table Detail (
DetailID int identity(1,1) primary key,
MasterID int references Master, --use 'references'
Stuff varchar(10))
GO
Insert into Master values('value')
--(1 row(s) affected)
GO
Insert into Detail values (1, 'Value1') -- Works
--(1 row(s) affected)
insert into Detail values (2, 'Value2') -- Fails
--Msg 547, Level 16, State 0, Line 2
--The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Detail__MasterID__0C70CFB4".
--The conflict occurred in database "Play", table "dbo.Master", column 'MasterID'.
--The statement has been terminated.
As you can see the second insert into the detail fails because of the foreign key.
Here's a good weblink that shows various syntax for defining FK during table creation or after.
http://www.1keydata.com/sql/sql-foreign-key.html
If you are not using SSMS then here is the syntax:
ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)
http://infogoal.com/sql/sql-add-foreignkey.htm
If you are talking about two kinds of enitities, say teachers and students, you would create two tables for each and a third one to store the relationship. This third table can have two columns, say teacherID and StudentId.
If this is not what you are looking for, please elaborate your question.