I am getting an invalid foreign key value and I cannot figure out what it is, here is the error.
Executed as multiple statements.
STATEMENT 1:
DATABASE completed. 0 rows processed. Elapsed time = 00:00:00.047
STATEMENT 2:
Insert Statement failed. Failed [2700 : 23000] Referential constraint violation: invalid foreign key value.
This happens when I try to insert:
insert into SALE values (1,30.45,'2020-12-31','VMBNH',1,1);
into the SALE Table
Here is the table, and I am also including the inserts that I already put on the table.
CREATE TABLE EQUIPMENT_DETAIL
(
EquipDetailID INT NOT NULL,
Make VARCHAR(20) NOT NULL,
Equipment_Type VARCHAR(20) NOT NULL,
Model VARCHAR(20) NOT NULL,
PRIMARY KEY (EquipDetailID)
);
CREATE TABLE CUSTOMER
(
CustID INT NOT NULL,
CustName VARCHAR(40) NOT NULL,
CustCategory VARCHAR(20) NOT NULL,
PRIMARY KEY (CustID)
);
CREATE TABLE EQUIPMENT
(
SerialNo VARCHAR(20) NOT NULL,
LastInspectedDate DATE NOT NULL,
DateMade DATE NOT NULL,
EquipDetailID INT NOT NULL,
PRIMARY KEY (SerialNo),
FOREIGN KEY (EquipDetailID) REFERENCES EQUIPMENT_DETAIL(EquipDetailID)
);
CREATE TABLE SALE
(
SaleTransID INT NOT NULL,
Price DECIMAL(4,2) NOT NULL,
Sale_Date DATE NOT NULL,
SerialNo VARCHAR(20) NOT NULL,
CustID INT NOT NULL,
SRepID INT NOT NULL,
PRIMARY KEY(SaleTransID),
FOREIGN KEY (SerialNo) REFERENCES EQUIPMENT(SerialNo),
FOREIGN KEY (CustID) REFERENCES CUSTOMER(CustID),
FOREIGN KEY (SRepID) REFERENCES SALES_REP(SRepID)
);
CREATE TABLE RENTAL
(
Price DECIMAL(4,2) NOT NULL,
Rental_Date DATE NOT NULL,
RentTransID INT NOT NULL,
SerialNo VARCHAR(20) NOT NULL,
CustID INT NOT NULL,
SRepID INT NOT NULL,
PRIMARY KEY (RentTransID),
FOREIGN KEY (SerialNo) REFERENCES EQUIPMENT(SerialNo),
FOREIGN KEY (CustID) REFERENCES CUSTOMER(CustID),
FOREIGN KEY (SRepID) REFERENCES SALES_REP(SRepID)
);
CREATE TABLE SALES_REP
(
SRepID INT NOT NULL,
SRepLName VARCHAR(40) NOT NULL,
SRepFName VARCHAR(20) NOT NULL,
Rank_ID VARCHAR(20) NOT NULL,
Mentors_SRepID INT,
PRIMARY KEY (SRepID),
FOREIGN KEY (Mentors_SRepID) REFERENCES SALES_REP(SRepID)
);
insert into EQUIPMENT_DETAIL values (1,'CFT','Drill','B123');
insert into EQUIPMENT_DETAIL values (2,'CFT','Hammer','B124');
insert into EQUIPMENT_DETAIL values (3,'MKT','Saw','M123');
insert into EQUIPMENT_DETAIL values (4'MKT','Wrench','M124');
insert into EQUIPMENT_DETAIL values (5'SNP','Flat Head','S123');
insert into CUSTOMER values (1,'Jim Halpert','A');
insert into CUSTOMER values (2,'Michael Scott','B');
insert into EQUIPMENT values ('KDJHS','2021-01-12','2010-11-11',1);
insert into EQUIPMENT values ('VMBNH','2021-03-05','2007-12-12',2);
insert into EQUIPMENT values ('QIEIR','2021-03-05','2007-12-12',3);
insert into EQUIPMENT values ('PTPYO','2021-03-05','2007-12-12',4);
insert into EQUIPMENT values ('AGSGD','2021-03-05','2007-12-12',5);
I had to drop the foreign key constraint from SALE (SRepID)
Related
CREATE TABLE student
(
student_id INT PRIMARY KEY,
first_name VARCHAR(40) NOT NULL,
last_name VARCHAR(40) NOT NULL,
birth_day DATE NOT NULL,
sex VARCHAR(1) NOT NULL,
student_email_address VARCHAR(40) NOT NULL UNIQUE,
student_password VARCHAR(10) NOT NULL UNIQUE,
student_nick_name VARCHAR(10) NOT NULL,
student_qualification VARCHAR(10) NOT NULL,
student_documents VARCHAR(255) NOT NULL,
student_image VARCHAR(100) NOT NULL
);
CREATE TABLE student_feedback
(
sr_no BIGSERIAL PRIMARY KEY,
student_id INT NOT NULL,
feedback_type VARCHAR(10) NOT NULL,
feedback_text VARCHAR(200) NOT NULL,
FOREIGN KEY (student_id) REFERENCES student(student_id)
);
CREATE TABLE online_exam
(
exam_id INT PRIMARY KEY,
exam_title VARCHAR(20) UNIQUE NOT NULL,
exam_duration_min INT NOT NULL,
total_questions INT NOT NULL,
marks_per_right_answer INT NOT NULL,
marks_per_wrong_answer INT NOT NULL,
passing_marks INT NOT NULL,
exam_status VARCHAR(2)
);
CREATE TABLE exam_subjects
(
sub_id INT,
exam_id INT,
sub_name VARCHAR(20) NOT NULL,
sub_desc VARCHAR(20) NOT NULL,
UNIQUE(sub_id,exam_id),
PRIMARY KEY(sub_id,exam_id),
FOREIGN KEY (exam_id) REFERENCES online_exam(exam_id) ON DELETE CASCADE
);
CREATE TABLE sub_questions
(
sub_id1 INT,
ques_id INT,
ques_text VARCHAR(150) NOT NULL,
ques_attachments VARCHAR(255),
option_1 VARCHAR(20) NOT NULL,
option_2 VARCHAR(20) NOT NULL,
option_3 VARCHAR(20) NOT NULL,
option_4 VARCHAR(20) NOT NULL,
UNIQUE(sub_id1,ques_id),
PRIMARY KEY (sub_id1,ques_id),
FOREIGN KEY (sub_id1) REFERENCES exam_subjects(sub_id) ON DELETE CASCADE
);
CREATE TABLE ques_answers
(
ans_id INT,
ques_id INT,
ans VARCHAR(20) NOT NULL,
PRIMARY KEY (ans_id,ques_id),
FOREIGN KEY (ques_id) REFERENCES sub_questions(ques_id) ON DELETE CASCADE
);
CREATE TABLE exam_registration
(
student_id INT,
exam_id INT,
exam_date_time TIMESTAMP NOT NULL,
PRIMARY KEY (student_id,exam_id),
FOREIGN KEY (student_id) REFERENCES student(student_id) ON DELETE CASCADE,
FOREIGN KEY (exam_id) REFERENCES online_exam(exam_id) ON DELETE CASCADE
);
CREATE TABLE exam_result
(
student_id INT,
exam_id INT,
sub_id INT,
marks_scored INT NOT NULL,
correct_ques INT NOT NULL,
wrong_ques INT NOT NULL,
grade VARCHAR(10) NOT NULL,
PRIMARY KEY(student_id,exam_id,sub_id),
FOREIGN KEY (student_id) REFERENCES student(student_id) ON DELETE CASCADE,
FOREIGN KEY (exam_id) REFERENCES online_exam(exam_id) ON DELETE CASCADE,
FOREIGN KEY (sub_id) REFERENCES exam_subjects(sub_id) ON DELETE CASCADE
);
Output :
CREATE TABLE,
CREATE TABLE,
CREATE TABLE,
CREATE TABLE,
There is no unique constraint matching given keys for referenced table "exam_subjects", relation "sub_questions" do not exist,
CREATE TABLE,
There is no unique constraint matching given keys for referenced table "exam_subjects".
Why am I getting "there is no unique..." error in postgresql? How to solve it? Please help.
In your table exam_subjects the primary key is a compossed key (PRIMARY KEY(sub_id, exam_id))
Therefore, your table sub_questions must have both columns to create the constraint, otherwise you get the error about unique constraints (or you can create a unique field acting as primary key, and create a unique index on both columns sub_id and exam_id)
Source code for oracle 12c
CREATE TABLE CUSTOMER (
CustomerID Char(20) NOT NULL,
CustomerFirstName Char(20) NOT NULL,
CustomerLastName Char(25) NOT NULL,
CustomerAddress Char(45) NOT NULL,
CustomerEmail Char(100) NOT NULL,
CONSTRAINT Customer_PK Primary Key(CustomerID)
CREATE TABLE EMPLOYEE (
EmployeeID VarChar(10) NOT NULL,
EmployeeFName VarChar(20) NOT NULL,
EmployeeRole VarChar(30) NOT NULL, CONSTRAINT
Employee_PK Primary Key(EmployeeID)
CREATE TABLE PRODUCT (
ProductID VarChar(10) NOT NULL,
ProductName VarChar(20) NOT NULL,
ProductType VarChar(20) NOT NULL,
ProductPrice Number(8,2) NOT NULL,
CONSTRAINT Product_PK Primary Key(ProductID)
CREATE TABLE CUSTORDER (
CustOrderID VarChar(10) NOT NULL,
CustOrderDate Date NOT NULL,
CustShippingStatus VarChar(20) NOT NULL,
SupplierID VarChar(20) NOT NULL,
CONSTRAINT CustOrder_PK Primary Key (CustOrderID),
CONSTRAINT CustOrder_FK FOREIGN KEY(SupplierID)
REFERENCES SUPPLIER(SupplierID)
CREATE TABLE SUPPLIER ( SupplierID Char(10) NOT NULL,
SupplierName Char(20) NOT NULL,
SupplierAddress Char(45) NOT NULL,
CONSTRAINT Supplier_PK Primary Key (SupplierID)
CREATE TABLE INVOICE (
InvoiceID Char(20) NOT NULL,
TotalItems Int NOT NULL,
TotalCost Number(8,2) NOT NULL,
SalesDate Date NOT NULL,
PaymentType VarChar(10) NOT NULL,
ProductID VarChar(10) NOT NULL,
EmployeeID VarChar(10) NOT NULL,
CustomerID Char(20) NOT NULL,
SupplierID Char(10) NOT NULL,
CONSTRAINT Invoice_PK Primary Key(InvoiceID),
CONSTRAINT Invoice_Product_FK Foreign Key(ProductID)
REFERENCES PRODUCT(ProductID),
CONSTRAINT Invoice_Employee_FK Foreign Key(EmployeeID)
REFERENCES EMPLOYEE(EmployeeID),
CONSTRAINT Invoice_Customer_FK Foreign Key(CustomerID)
REFERENCES CUSTOMER(CustomerID),
CONSTRAINT Invoice_Supplier_FK Foreign Key(SupplierID)
REFERENCES SUPPLIER(SupplierID)
You need to align the datatype and length of the referencing column of each foreign key with the column it references in the source table.
In your code, SUPPLIER(SupplierID) is declared as Char(20). On the other hand, referencing column INVOICE(SupplierID) is Char(10) and CUSTORDER(SupplierID) is VarChar(20). If you make these two columns Char(20), you code just works.
Aside: the referenced table must exist at the time when the referencing table is created - your code createst CUSTORDER before SUPPLIER. However I assume that's a typo when writing the question, otherwise you would be getting a different error: ORA-00942: table or view does not exist.
You also have a missing right parentheses at the end of each and every create table statement: I would consider these typos too.
Demo on DB Fiddle
CREATE TABLE THREE_GIRLS_COFFEE_HUT
(
ShopName Char NOT NULL,
PhoneNumber Char(12) NOT NULL,
Address Char(20) NOT NULL,
City Char(20) NOT NULL,
State Char(2) NOT NULL,
ZipCode Char(5) NOT NULL,
CONSTRAINT ShopPK PRIMARY KEY (ShopName)
);
CREATE TABLE EMPLOYEE
(
EmployeeID Int NOT NULL IDENTITY(1,1),
EmployeeName Char(30) NOT NULL,
PhoneNumber Char(10) NOT NULL,
Address Char(20) NOT NULL,
City Char(20) NOT NULL,
State Char(2) NOT NULL,
ZipCode Char(5) NOT NULL,
EmployeeType Char(10) NOT NULL,
ShopName Char (25) FOREIGN KEY REFERENCES THREE_GIRLS_COFFEE_HUT (ShopName)
CONSTRAINT EmployeePK PRIMARY KEY(EmployeeID),
CONSTRAINT EmployeeAK1 UNIQUE(EmployeeName)
);
CREATE TABLE CUSTOMER
(
CustomerID Int NOT NULL IDENTITY(1000,1),
CustomerName Char(30) NULL,
PhoneNumber Char(10) NULL,
EmailAddress Char(30) NOT NULL,
CONSTRAINT CustomerPK PRIMARY KEY(CustomerID),
CONSTRAINT CustomerAK1 UNIQUE(EmailAddress)
);
CREATE TABLE [ORDER]
(
SalesOrderNumber INT NOT NULL IDENTITY (1500,1),
Date Numeric(6) NOT NULL,
Subtotal Numeric(6, 2) NOT NULL,
Tax Numeric(6, 2) NOT NULL,
Total Numeric(6, 2) NOT NULL,
CONSTRAINT OrderPK PRIMARY KEY (SalesOrderNumber),
CONSTRAINT EmpOrdFK FOREIGN KEY(EmployeeID)
REFERENCES EMPLOYEE(EmployeeID)
ON UPDATE CASCADE
ON DELETE NO ACTION,
CONSTRAINT CustOrdFK FOREIGN KEY (CustomerID)
REFERENCES CUSTOMER(CustomerID)
ON UPDATE NO ACTION
ON DELETE NO ACTION
);
CREATE TABLE PRODUCT
(
ProductNumber Int NOT NULL IDENTITY(2000,1),
ProductDescription Char(20) NOT NULL,
QuantityOnOrder Numeric(4) NOT NULL,
QuantityOnHand Numeric(4) NOT NULL,
OrderDate Date NOT NULL,
ExpirationDate Date NOT NULL,
CONSTRAINT ProductPK PRIMARY KEY(ProductNumber),
CONSTRAINT ValidExpDate CHECK (ExpirationDate > OrderDate)
);
CREATE TABLE MENU_ITEM (
ItemNumber Int NOT NULL IDENTITY(3000,1),
ItemDescription Char(30) NOT NULL,
ItemCost Numeric(6,2) NOT NULL,
ProductNumber Int FOREIGN KEY REFERENCES PRODUCT(ProductNumber)
CONSTRAINT MenuPK PRIMARY KEY(ItemNumber),
CONSTRAINT MenuAK1 UNIQUE(ItemDescription),
);
CREATE TABLE ORDER_LINE_ITEM (
SalesOrderNumber INT FOREIGN KEY REFERENCES [ORDER](SalesOrderNumber),
ItemNumber INT FOREIGN KEY REFERENCES MENU_ITEM(ItemNumber),
Quantity Numeric NOT NULL,
UnitPrice Numeric(6,2) NOT NULL,
ExtendedPrice Numeric (6,2) NOT NULL,
);
I got these errors and it will not process- I think I have problem with my foreign key but I am not sure.
Msg 1769, Level 16, State 1, Line 40
Foreign key 'EmpOrdFK' references invalid column 'EmployeeID' in referencing table 'ORDER'.
Msg 1750, Level 16, State 0, Line 40
Could not create constraint or index. See previous errors.
There's no column EmployeeID in the ORDER table, so:
EmpOrdFK FOREIGN KEY(EmployeeID) REFERENCES EMPLOYEE(EmployeeID)
which says, create a foreign key in which Order.EmployeeId references Employee.EmployeeId, can't work.
Did you want to add an EmployeeId column to Order?
(There's also no CustomerId in Order, so the next line
CONSTRAINT CustOrdFK FOREIGN KEY (CustomerID)
would have failed too, except it never got to run because of the first error.)
You probably want to add EmployeeId and CustomerId to the Order table.
When you are mapping foreign key from Order table to Employee table, you have to map on common column in both tables. If you look at order table, which is missing employeeId in
that table.
And also don't call it as ORDER table. ORDER is reserved keyword in SQL server.
References: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/reserved-keywords-transact-sql?view=sql-server-ver15
I am new to SQL and SQL Server. I am trying to implement a small database. However, I keep getting three errors.
Error #1:
String or binary data would be truncated
Error #2:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Formation__Locat__25869641"
Error #3:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__DATA__Classifica__2B3F6F97".
I've tried a variety of different changes and nothing seems to work. Can someone explain to me what I am doing wrong? Thanks
CREATE TABLE Location
(
LocationID CHAR(5) NOT NULL,
LocationName VARCHAR(75) NOT NULL,
PRIMARY KEY (LocationID)
);
CREATE TABLE Formation
(
FormationID CHAR(5) NOT NULL,
FormationName VARCHAR(75) NOT NULL,
RockType VARCHAR(75) NOT NULL,
LocationID INT NOT NULL,
PRIMARY KEY (FormationID),
FOREIGN KEY (LocationID) REFERENCES Location(LocationID)
);
CREATE TABLE Classification
(
ClassificationID CHAR(5) NOT NULL,
ClassificationType VARCHAR(75) NOT NULL,
ClassificationDescription VARCHAR(75) NOT NULL,
FormationID VARCHAR(5) NOT NULL,
PRIMARY KEY (ClassificationID),
FOREIGN KEY (FormationID) REFERENCES Formation(FormationID)
);
CREATE TABLE DATA
(
FossilID CHAR(5) NOT NULL,
FossilName VARCHAR(75) NOT NULL,
FossilType VARCHAR(75) NOT NULL,
CatalogueDate DATE NOT NULL,
ClassificationID VARCHAR(5) NOT NULL,
PRIMARY KEY (FossilID),
FOREIGN KEY (ClassificationID) REFERENCES Classification(ClassificationID)
);
INSERT INTO Location
VALUES ('001', 'Montana');
INSERT INTO Formation
VALUES ('R01', 'Hell Creek Formation', 'Cretaceous', 001);
INSERT INTO Classification
VALUES ('001', 'Saurischia', 'Brachiosauridae', 'Hell Creek Formation');
INSERT INTO DATA
VALUES ('F01', 'Brachiosaurus', 'Vertebrae', '01/MAY/2017', '001');
INT <> VARCHAR(5) <> CHAR(5). Column should be the same type:
CREATE TABLE Location (
LocationID CHAR(5) NOT NULL,
LocationName VARCHAR(75) NOT NULL,
PRIMARY KEY (LocationID)
);
CREATE TABLE Formation (
FormationID CHAR(5) NOT NULL,
FormationName VARCHAR(75) NOT NULL,
RockType VARCHAR(75) NOT NULL,
LocationID CHAR(5) NOT NULL, -- here
PRIMARY KEY (FormationID),
FOREIGN KEY (LocationID) REFERENCES Location(LocationID)
);
CREATE TABLE Classification (
ClassificationID CHAR(5) NOT NULL,
ClassificationType VARCHAR(75) NOT NULL,
ClassificationDescription VARCHAR(75) NOT NULL,
FormationID CHAR(5) NOT NULL, -- here
PRIMARY KEY (ClassificationID),
FOREIGN KEY (FormationID) REFERENCES Formation(FormationID)
);
CREATE TABLE DATA (
FossilID CHAR(5) NOT NULL,
FossilName VARCHAR(75) NOT NULL,
FossilType VARCHAR(75) NOT NULL,
CatalogueDate DATE NOT NULL,
ClassificationID CHAR(5) NOT NULL,
PRIMARY KEY (FossilID),
FOREIGN KEY (ClassificationID) REFERENCES Classification(ClassificationID)
);
DBFiddleDemo
And your insert statements:
INSERT INTO Location VALUES ('001', 'Montana');
INSERT INTO Formation VALUES ('R01', 'Hell Creek Formation', 'Cretaceous', '001'); --corrected
INSERT INTO Classification VALUES ('001', 'Saurischia', 'Brachiosauridae', 'R01'); --corrected
INSERT INTO DATA VALUES ('F01', 'Brachiosaurus', 'Vertebrae', '01/MAY/2017', '001');
Truncation error 'Hell Creek Formation' cannot fit CHAR(5). You need to refer PK. Also consider using:
INSERT INTO tab(col_name1, col_name2, ...)
VALUES(...)
DDL:
CREATE TABLE OSOBA
(
id INT PRIMARY KEY not null IDENTITY,
imie VARCHAR(30) not null,
nazwisko VARCHAR(40) not null,
zawod VARCHAR(30) not null,
dataUrodzenia DATE,
plec BIT not null,
narodowosc VARCHAR(30) not null,
);
CREATE TABLE OSOBISTOSCI
(
nazwaMiasta VARCHAR(30) not null,
id INT not null,
adres VARCHAR(50),
czy BIT,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES OSOBA,
FOREIGN KEY (nazwaMiasta) REFERENCES MIASTA,
);
CREATE TABLE ARCHITEKCI
(
id INT not null,
uprawnienia VARCHAR(30) UNIQUE,
styl VARCHAR(30) not null,
liczba INT not null,
PRIMARY KEY (id),
FOREIGN KEY (id) REFERENCES OSOBA,
);
And I have these insert statements:
-- these work fine
INSERT INTO OSOBA (imie,nazwisko,zawod,dataUrodzenia,plec,narodowosc) VALUES ('Lech', 'Wałęsa', 'Elektryk', '19430129', 1, 'Polak');
INSERT INTO OSOBISTOSCI (nazwaMiasta, id, adres, czy) VALUES ('Gdańsk', IDENT_CURRENT('OSOBA'), 'ul. Polanki', 0);
-- these throw the below error message
INSERT INTO OSOBA (imie,nazwisko,zawod,dataUrodzenia,plec,narodowosc) VALUES ('Marcia','Frank','Architekt','19570720','0','Niemiec');
INSERT INTO ARCHITEKCI (id,styl,liczba) VALUES (IDENT_CURRENT('OSOBA'),'Nowoczesny',8);
Error:
Msg 2627, Level 14, State 1, Line 124
Violation of UNIQUE KEY constraint 'UQ_ARCHITEK_982D973E2BA18BE7'. Cannot insert duplicate key in object 'dbo.ARCHITEKCI'. The duplicate key value is ().
As Aaron mentioned the IDENT_CURRENT is not very reliable. It would be better to use an OUTPUT clause. See the following example:
DECLARE #LatestID TABLE (ID INT);
INSERT INTO #OSOBA (imie,nazwisko,zawod,dataUrodzenia,plec,narodowosc)
OUTPUT INSERTED.ID INTO #LatestID
VALUES ('Marcia','Frank','Architekt','19570720','0','Niemiec');
INSERT INTO #ARCHITEKCI (id,styl,liczba) VALUES ((SELECT ID FROM #LatestID),'Nowoczesny',8);