SSMS Build: "The INSERT statement conflicted with the FOREIGN KEY constraint" - sql-server

I'm getting this error even thought I think my table correctly references a primary key. The Constituent_Gift table references 5 foreign keys but only triggers this error for the Gift table. I can't see why the Category table would work but the Gift table wouldn't. The exact error message is:
Msg 547, Level 16, State 0, Line 12
The INSERT statement conflicted with the FOREIGN KEY constraint "fk_giftid". The conflict occurred in database "SusanCurtis", table "dbo.Gift", column 'Gift_ID'.
Code:
CREATE TABLE Category
(
Category_ID NCHAR(4) CONSTRAINT pk_categoryid PRIMARY KEY,
Category_Description NVARCHAR(50) CONSTRAINT nn_categorydescription NOT NULL
);
CREATE TABLE Gift
(
Gift_ID NCHAR(1) CONSTRAINT pk_giftid PRIMARY KEY,
Gift_Description NVARCHAR(20) CONSTRAINT nn_giftdescription NOT NULL,
);
CREATE TABLE Constituent_Gift
(
Constituent_Gift_ID NCHAR(6) CONSTRAINT pk_constituentgift PRIMARY KEY,
Constituent_ID NCHAR(6) CONSTRAINT fk_constituentid FOREIGN KEY
REFERENCES Constituent(Constituent_ID),
Gift_ID NCHAR(1) CONSTRAINT fk_giftid FOREIGN KEY
REFERENCES Gift(Gift_ID),
Fund_ID NCHAR(4) CONSTRAINT fk_fundid FOREIGN KEY
REFERENCES Fund(Fund_ID),
Event_ID NCHAR(2) CONSTRAINT fk_eventid FOREIGN KEY
REFERENCES [Event](Event_ID),
Category_ID NCHAR(4) CONSTRAINT fk_categoryid FOREIGN KEY
REFERENCES Category(Category_ID),
Note NVARCHAR(2000),
Gift_Amount MONEY CONSTRAINT nn_giftamount NOT NULL,
Deductible_Amount MONEY,
Gift_Date Date,
Payment_Type NVARCHAR(30),
Anonymous_Gift BIT
);
Does anyone know why this is happening?

Well, the error message really says it all: obviously, that INSERT (which unfortunately you haven't shown) is trying to insert a value that violates the foreign key constraint fk_giftid - that's the foreign key between Constituent_Gift.Gift_ID and Gift.Gift_ID - which means you're trying to insert a row into Constituent_Gift with a value for Gift_ID that doesn't exist in the referenced Gift table.
And that's the whole point of a foreign key constraint - ensure you only ever insert valid data - that is present in the referenced table (here Gift).
Fix that value to be something that is present in the Gift table - and you should be fine.

what data are you going to insert?
I also miss the schema for the table 'Constituent'
Constituent_ID NCHAR(6) CONSTRAINT fk_constituentid FOREIGN KEY
REFERENCES Constituent(Constituent_ID),

Related

SQL Server why am I getting error for creating foreign key constraint for no matching key in referenced table?

I get this error from SQL Server:
Msg 1776, Level 16, State 0, Line 64
There are no primary or candidate keys in the referenced table 'Orders' that match the referencing column list in the foreign key 'FK_Cart_Orders'.
However, the OrderID column is in the Orders table, so I cannot understand why the error says there is no matching keys in the Orders table. I am obviously doing something wrong but do not know what it is.
My code is fairly short and is:
CREATE DATABASE TestMattressSite
GO
USE TestMattressSite
GO
CREATE TABLE Mattresses
(
MattressID INT IDENTITY NOT NULL,
)
GO
CREATE TABLE Customers
(
CustomerID INT IDENTITY NOT NULL,
)
GO
CREATE TABLE Orders
(
OrderID BIGINT IDENTITY NOT NULL,
CustomerID INT NOT NULL,
)
CREATE TABLE Cart
(
OrderID BIGINT NOT NULL,
MattressID INT NOT NULL,
CustomerID INT NOT NULL
)
GO
ALTER TABLE Mattresses
ADD CONSTRAINT PK_Mattresses PRIMARY KEY (MattressID)
GO
ALTER TABLE Customers
ADD CONSTRAINT PK_Customers PRIMARY KEY (CustomerID)
GO
ALTER TABLE Orders
ADD CONSTRAINT PK_Orders PRIMARY KEY (OrderID, CustomerID)
GO
ALTER TABLE Cart
ADD CONSTRAINT PK_Cart PRIMARY KEY (OrderID, MattressID)
GO
ALTER TABLE Orders
ADD CONSTRAINT FK_Orders_Customers
FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID)
GO
ALTER TABLE Cart
ADD CONSTRAINT FK_Cart_Mattresses
FOREIGN KEY (MattressID) REFERENCES Mattresses (MattressID),
CONSTRAINT FK_Cart_Orders
FOREIGN KEY (OrderID) REFERENCES Orders (OrderID),
CONSTRAINT FK_Cart_Customers
FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID)
GO
Can someone please take a look and point out my error?
Since your Orders table have primary key on two columns OrderID and CustomerID, its a composite primary key so when you want to reference this key as foreign key any table, you need to define all the column of composite primary key, like below.
ALTER TABLE Cart ADD
CONSTRAINT FK_Cart_Mattresses FOREIGN KEY (MattressID) REFERENCES Mattresses (MattressID),
CONSTRAINT FK_Cart_Orders FOREIGN KEY (OrderID, CustomerID) REFERENCES Orders (OrderID, CustomerID),
CONSTRAINT FK_Cart_Customers FOREIGN KEY (CustomerID) REFERENCES Customers (CustomerID)
GO
Or,
If you want your foreign key to have only one column OrderID, change your primary key like this:
ALTER TABLE Orders ADD
CONSTRAINT PK_Orders PRIMARY KEY (
OrderID
)
GO
With this, you current query will work as it is.
There already a question on this, refer this link.

Foreign Key Constraint does not exist ERROR

I keep getting this error in my psql database;
bikefacility=# ERROR: syntax error at or near "c"
bikefacility-# LINE 1: c
bikefacility-# ^
bikefacility-# bikefacility=# ALTER TABLE bicycle ADD CONSTRAINT fk_maintenance_contact_person FOREIGN KEY (maintenance_contact_person) REFERENCES maintenance(maintenance_contact_person);
ERROR: syntax error at or near "ERROR"
LINE 1: ERROR: syntax error at or near "c"
^
bikefacility=# ERROR: column "maintenance_contact_person" referenced in foreign key constraint does not exist
bikefacility-# bikefacility=# ALTER TABLE bicycle ADD CONSTRAINT fk_rental_period FOREIGN KEY (rental_period) REFERENCES rental(rental_period);
ERROR: syntax error at or near "ERROR"
LINE 1: ERROR: column "maintenance_contact_person" referenced in fo...
^
bikefacility=# ERROR: column "rental_period" referenced in foreign key constraint does not exist
bikefacility-# bikefacility=# ALTER TABLE bicycle ADD CONSTRAINT fk_terminal_id FOREIGN KEY (terminal_id) REFERENCES terminal(terminal_id);
ERROR: syntax error at or near "ERROR"
LINE 1: ERROR: column "rental_period" referenced in foreign key con...
^
bikefacility=# ERROR: column "terminal_id" referenced in foreign key constraint does not exist
This is my code. I've created the same style of foreign keys within the code as you can see here.
CREATE TABLE member (
member_id INTEGER PRIMARY KEY,
member_fname VARCHAR(15) NOT NULL,
member_lname VARCHAR(15) NOT NULL,
member_status VARCHAR(15) NOT NULL,
member_address VARCHAR(10) NOT NULL,
member_email VARCHAR(30) NOT NULL
);
CREATE TABLE bicycle (
bicycle_id INTEGER PRIMARY KEY,
bicycle_brand VARCHAR(25) NOT NULL,
bicycle_model VARCHAR(25) NOT NULL,
bicycle_colour VARCHAR(15) NOT NULL,
bicycle_type VARCHAR(20) NOT NULL,
bicycle_size VARCHAR(10) NOT NULL,
bicycle_availability VARCHAR(20) NOT NULL
);
ALTER TABLE bicycle ADD CONSTRAINT fk_bicycle_pickup_date FOREIGN KEY (bicycle_pickup_date) REFERENCES rental(bicycle_pickup_date) >MATCH FULL;
ALTER TABLE bicycle ADD CONSTRAINT fk_maintenance_contact_person FOREIGN KEY (maintenance_contact_person) REFERENCES maintenance(maintenance_contact_person);
ALTER TABLE bicycle ADD CONSTRAINT fk_terminal_id FOREIGN KEY (terminal_id) REFERENCES terminal(terminal_id);
ALTER TABLE bicycle ADD CONSTRAINT fk_rental_period FOREIGN KEY (rental_period) REFERENCES rental(rental_period);
CREATE TABLE sponsor (
sponsor_id INTEGER PRIMARY KEY,
sponsor_name VARCHAR(15) NOT NULL,
sponsor_contact VARCHAR(30) NOT NULL,
sponsor_period DATE NOT NULL,
sponsor_address VARCHAR(50) NOT NULL,
sponsor_fee DECIMAL (6, 2) NOT NULL
);
CREATE TABLE terminal (
terminal_id INTEGER PRIMARY KEY,
terminal_address VARCHAR(50) NOT NULL,
terminal_minstorage VARCHAR(50) NOT NULL,
terminal_maxstorage VARCHAR(50) NOT NULL
);
CREATE TABLE rental (
rental_no INTEGER PRIMARY KEY,
rental_period DATE NOT NULL,
bicycle_pickup_date DATE NOT NULL
);
It says that the columns don't exist but I know they do because they're right there! Can someone help me out, please? Thanks in advance!
The grammar of the the foreign keys are incorrect for postgresql. For instance, ALTER TABLE bicycle ADD CONSTRAINT fk_terminal_id FOREIGN KEY (terminal_id) REFERENCES terminal(terminal_id); requires there to be a field in bicycles, named terminal_id as the former terminal_id in your query refers to bicycle table, which should reference terminal_id in the terminal table.
Here is a short tutorial of foreign keys. https://www.postgresqltutorial.com/postgresql-foreign-key/
Best regards,
Bjarni
Your schema is quite messed up.
There's no table maintenance yet you try to make a reference to it.
The foreign table like rental must be created before you make a fk reference to it.
You must have the named fields in the table where you make the reference from. There are no fields bicycle_pickup_date, maintenance_contact_person, terminal_id or rental_period in table bicycle.
Your fk references in general sound odd. Do you really want that each bicycle could have only only one rental, ever? Maybe you meant that a rental references to a single bicycle?
Also, your naming convention is quite redundant. There's no need to repeat table name in each field name, that just adds unneeded clutter in your code.

Why am I getting an error 'Invalid table name', When i am trying to create another table with foreign key with the primray key of the first table

There is a parent table with the name of "SALESPERSON123" with primary key "SSN"
SQL> DESC SALESPERSON123;
Name Null? Type
----------------------------------------- -------- ----------------------------
SSN NOT NULL VARCHAR2(30)
NAME VARCHAR2(30)
START_YR NUMBER
DEPT_NO VARCHAR2(30)
I want to create another table "Trip" in which I want to make "SSN" the foreign key, but i am getting following error.
SQL> CREATE TABLE TRIP
2 (
3 TRIP_ID VARCHAR2(30),
4 SSN VARCHAR2(30),
5 FROM_CITY VARCHAR2(30),
6 TO_CITY VARCHAR2(30),
7 DEP_DATE NUMBER,
8 RETURN_DATE NUMBER,
9 FOREIGN KEY (SSN) REFERENCES TO SALESPERSON123(SSN),
10 PRIMARY KEY (TRIP_ID)
11 );
FOREIGN KEY (SSN) REFERENCES TO SALESPERSON123(SSN),
*
ERROR at line 9:
ORA-00903: invalid table name
I tried to multiple time, by deleting and again creating the parent table but no there is no avail.
Remove TO. It must be:
FOREIGN KEY (SSN) REFERENCES SALESPERSON123(SSN),
instead of
FOREIGN KEY (SSN) REFERENCES TO SALESPERSON123(SSN),
A foreign key is a way to enforce referential integrity within your Oracle database. A foreign key means that values in one table must also appear in another table.
The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table.
A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
);

Error: invalid identifier 00904. 00000 - "%s: invalid identifier for foreign key constraint

Does anyone know why my two tables in SQL developer produce the error of:
Error report - SQL Error: ORA-00904: "CLIENT_ID": invalid identifier 00904. 00000 - "%s: invalid identifier".
I know it is to do with the constraints for the foreign keys but don't know why:
CREATE TABLE person
( person_id NUMBER(4) not null,
person_name VARCHAR(50),
person_surname VARCHAR(50),
person_contact_number NUMBER(11),
person_address VARCHAR2(50),
person_postcode VARCHAR2(50),
fk_boss_id NUMBER(4),
CONSTRAINT person_id_pk PRIMARY KEY (person_id),
CONSTRAINT boss_id FOREIGN KEY (boss_id) REFERENCES boss (boss_id)
);
CREATE TABLE boss
( boss_id NUMBER(4) not null,
boss_name VARCHAR(50),
fk_person_id NUMBER(4),
CONSTRAINT boss_pk PRIMARY KEY (boss_id),
CONSTRAINT person_id FOREIGN KEY (person_id) REFERENCES person (person_id)
);
Your foreign key constraints say that the columns person.boss_id and boss.person_id are foreign keys, but neither table has a column by that name. It looks as though you've swapped the names of the FK columns with those of the FK constraints.
The FOREIGN KEY clause of the CONSTRAINT declaration must reference a column that exists in the declaring table. For instance, in the table boss you would have
...
person_id NUMBER(4),
...
CONSTRAINT fk_person_id FOREIGN KEY (person_id) REFERENCES person (person_id)
...
(Also, if your error message begins ORA then you're using Oracle, not MySQL, and if it refers to a column called CLIENT_ID then it's complaining about a third table which is neither of the ones you posted.)

Foreign Key error SQL Server

I have three tables that are to be connected using a foreign key.
CREATE TABLE customer
(
customerID INT,
lastname VARCHAR(70) NOT NULL,
firstname VARCHAR(70) NOT NULL,
phone VARCHAR(10) CONSTRAINT phoneCheck CHECK ((phone LIKE '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]')),
category VARCHAR(1) NOT NULL CONSTRAINT categoryDefault DEFAULT 'A',
CONSTRAINT categoryCheck CHECK (category IN ('A', 'B', 'C')),
CONSTRAINT customerPK
PRIMARY KEY (customerID)
)
CREATE TABLE booking
(
customerID INT,
packageCode VARCHAR(6) UNIQUE,
bookingDate DATE NOT NULL DEFAULT GETDATE(),
amountPaid MONEY CONSTRAINT amountPaidDefault DEFAULT 0.00,
CONSTRAINT bookingPK
PRIMARY KEY (customerID),
CONSTRAINT bookingFK
FOREIGN KEY (customerID)
REFERENCES customer (customerID)
ON DELETE CASCADE
);
CREATE TABLE package
(
packageCode VARCHAR(6),
destination VARCHAR(70),
CONSTRAINT packageCodeCheck CHECK (packageCode LIKE ('YFK%')),
price MONEY NOT NULL CONSTRAINT priceCheck CHECK ((price BETWEEN 1000 AND 10000)),
passportRequired VARCHAR(1) NOT NULL CONSTRAINT passportRequiredDefault DEFAULT 'Y',
CONSTRAINT passportCheck CHECK (passportRequired IN ('Y', 'N')),
CONSTRAINT packagePK
PRIMARY KEY (packageCode),
CONSTRAINT packageFK
FOREIGN KEY (packageCode)
REFERENCES booking (packageCode)
ON DELETE CASCADE
)
I got the Foreign key between customer and booking set properly, its purpose is to delete all associated bookings with that customer. I am currently trying to do the same between package and bookings, When a package record is deleted, it should also delete the corresponding records. I continue to get the error
The INSERT statement conflicted with the FOREIGN KEY constraint
"packageFK". The conflict occurred in database "travel", table
"dbo.booking", column 'packageCode'.
Im not quite sure what this is referencing as I have encountered this error before and fixed it, unfortunately... I cannot in this case.
All help is greatly appreciated.
Thanks,
Bryan
Since you want to delete all booking rows when a package is deleted, the package table must be the primary table and the booking table must reference the package table. Remove the foreign key constraint from the table and add the following to the bookings table:
CONSTRAINT booking_packageFK
FOREIGN KEY (packageCode)
REFERENCES package (packageCode)
ON DELETE CASCADE
You should also remove the UNIQUE constraint from the packageCode on the booking table.
I don't think you have your foreign key relationship set up correctly even between Customer and Booking.
In your Create Table customer following tells the server that CustomerId is the Primary Key in customer table:
CONSTRAINT customerPK
PRIMARY KEY (customerID)
In your Create Table booking following tells the server that CustomerId is the Primary Key as well as a Foreign Key that references customer:
CONSTRAINT bookingPK
PRIMARY KEY (customerID),
CONSTRAINT bookingFK
FOREIGN KEY (customerID)
REFERENCES customer (customerID)
ON DELETE CASCADE
Similarly in your package table you have set packageCode as both primary and foreign key.
What I think you need is:
CustomerId in Customer table should be the primary key
There should be a BookingId and a CustomerId in the Booking table. BookingId will be the primary key and CustomerId will be the foreign key that references Customer.
There should be a BookingId in the Package table. It will be a foreign key that references Booking.

Resources