The INSERT statement conflicted with the FOREIGN KEY constraint" - sql

I'm trying to insert data into my SQL Server 2014 build and I keep getting this error. I tried searching all over the internet and at my whits end, I sort of get what people were saying but still having difficulty understanding what's wrong with my particular code.
All tables are empty without data. I cannot add data once the foreign keys are set. I read that both tables must be populated for this to work but how does that happen when I can't add anything? If I add data before the foreign key, then I'm unable to add foreign keys. Please help!
When trying to insert data into Gym row using the INSERT INTO I get this error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Gym__staffNo". The conflict occurred in database "FitnessApp", table "dbo.Staff", column 'staffNo'.
This also happens when trying to add data into the Equipment or Staff tables as well.
See code here:
Schema:
CREATE TABLE Gym
(
gymNo int NOT NULL IDENTITY(1,1),
staffNo int NOT NULL,
streetAddress varchar(100) NOT NULL,
streetAddress2 varchar(100) NULL,
city varchar(50) NOT NULL,
state char(2) NOT NULL,
zip char(5) NOT NULL,
phone char(10) NOT NULL
) ON [fitnessPlusGroup1];
CREATE TABLE Staff
(
staffNo int NOT NULL IDENTITY(1,1),
gymNo int NOT NULL,
position varchar(50) NOT NULL,
firstName varchar(50) NOT NULL,
lastName varchar(50) NOT NULL,
streetAddress varchar(100) NOT NULL,
streetAddress2 varchar(100) NULL,
city varchar(50) NOT NULL,
state char(2) NOT NULL,
zip char(5) NOT NULL,
phone char(10) NOT NULL,
hireDate date NOT NULL
) ON [fitnessPlusGroup1];
CREATE TABLE Member
(
memberNo int NOT NULL IDENTITY(1,1),
gymNo int NOT NULL,
firstName varchar(30) NOT NULL,
lastName varchar(30) NOT NULL,
streetAddress varchar(100) NOT NULL,
streetAddress2 varchar(100) NULL,
city varchar(50) NOT NULL,
state char(2) NOT NULL,
zip char(5) NOT NULL,
phone char(10) NOT NULL,
memberSince date NOT NULL,
scheduleID int NULL
) ON [fitnessPlusGroup1];
CREATE TABLE Schedule
(
scheduleID int NOT NULL IDENTITY(1,1),
staffNo int NOT NULL,
trainDate date NOT NULL,
trainTime time(0) NOT NULL
) ON [fitnessPlusGroup1];
CREATE TABLE Equipment
(
equipNo int NOT NULL IDENTITY(1,1),
gymNo int NOT NULL,
staffNo int NOT NULL,
name varchar(50) NOT NULL,
quantity int NOT NULL
) ON [fitnessPlusGroup1];
Foreign key relationships setup:
ALTER TABLE Gym
ADD FOREIGN KEY (staffNo) REFERENCES Staff(staffNo);
ALTER TABLE Staff
ADD FOREIGN KEY (gymNo) REFERENCES Gym(gymNo);
ALTER TABLE Member
ADD FOREIGN KEY (gymNo) REFERENCES Gym(gymNo);
ALTER TABLE Member
ADD FOREIGN KEY (scheduleID) REFERENCES Schedule(scheduleID);
ALTER TABLE Schedule
ADD FOREIGN KEY (staffNo) REFERENCES Staff(staffNo);
ALTER TABLE Equipment
ADD FOREIGN KEY (gymNo) REFERENCES Gym(gymNo);
ALTER TABLE Equipment
ADD FOREIGN KEY (staffNo) REFERENCES Staff(staffNo);
The insert commands that give errors:
INSERT INTO Gym(staffNo, streetAddress, streetAddress2, city, state, zip, phone)
VALUES (1, '7300 W Greens Rd', NULL, 'Houston', 'TX', '77064', '2818946151');
Any help would be much appreciated sorry if this seems like a bit much and I hope I provided all the info I could..

I think the problem is in your table design. Take these two FKEY, as an exmpale:
ALTER TABLE Gym
ADD FOREIGN KEY (staffNo) REFERENCES Staff(staffNo);
ALTER TABLE Staff
ADD FOREIGN KEY (gymNo) REFERENCES Gym(gymNo);
You cannot add a record to Gym until you've added the supporting staffNo to Staff. But you cannot add a record to Staff until you've added the supporting gymNo to Gym. These keys prevent you populating either table, as both require records to be present in the other.
Why is this? Because an FKey is like a promise. It guarantees that the value in column x can always be found in table y. In order to fulfill this promise table y must be populated first. But when you have a circular reference, back to the original table, this can never be achieved.
Here is one possible solution. You could remove the staffNo from Gym and GymNo from Staff. Then add a new table StaffGym. This table would have two fields staffNo and gymNo. It would be populated after Staff and Gym, providing a bridge between the two. This is called a cross reference table, or sometimes xref for short.

You say:
All tables are empty without data.
So there is no staffNo with id = 1 in your Staff. You've got a foreign key constraint so you can only reference items that exist. So you first need to populate the lookup data in Staff before you can link to it with an ID.
Also, remove one of the constraint between Staff and Gym, you have this:
ALTER TABLE Gym
ADD FOREIGN KEY (staffNo)
REFERENCES Staff(staffNo);
ALTER TABLE Staff
ADD FOREIGN KEY (gymNo)
REFERENCES Gym(gymNo);
When you only need one of these. I'd say remove it from Gym, as a Gym could have many staff I'd assume, and also remove the StaffNo column from Gym. As this is preventing you from creating one without the other. Once you've removed that link, you should insert data in the correct order.
The order of the inserts is key. If you remove the column I suggested above, you should insert in the following order based on your constraints:
Gym
Staff (requires gym record)
Schedule (requires staff record)
Member (requires schedule record)
Equipment (requires gym and staff record)

Related

Can we update a record that is defined as a foreign key of a unique record define in a different table?

I am new to PostgreSQL and how i can update the records while they are related with a foreign key definition.
I am getting an error and that would be great if you can guide me with any hints
Let's say we have two different tables like below :
CREATE TABLE IF NOT EXISTS student
(
id_num VARCHAR(40) NOT NULL REFERENCES registered(student_id),
first_name VARCHAR(32) NOT NULL,
last_name VARCHAR(32) NOT NULL,
birthdate DATE NOT NULL,
PRIMARY KEY(id_num)
);
CREATE TABLE IF NOT EXISTS registered
(
student_id VARCHAR(40) NOT NULL UNIQUE,
paid_tuition BOOL NOT NULL,
PRIMARY KEY(paid_tuition)
);
Based on my understating i need to fill the registered table and then try to insert values to the student table that their id match the student_id value in registered table.
But when I try it I get the following error?
Any idea or recommendation?
Message:"update or delete on table "registered" violates foreign key
constraint "student_id_num_id_fkey" on table "student"",
Detail:"Key (id_num)=(idNum-1) is still referenced from table
"student".", Hint:"", Position:0, InternalPosition:0,
InternalQuery:"", Where:"", SchemaName:"", TableName:"student",
ColumnName:"", DataTypeName:"",
ConstraintName:"student_id_num_id_fkey", File:"ri_triggers.c",
Line:2490, Routine:"ri_ReportViolation"}
seems like you are linking tables in opposite direction , to me it makes more sense that "registered" table has been linked to student table by fk studentid .
also in your "student" table definition you are saying that column "id" is primary key while no "id" column has been declared.
so here is what I mean:
CREATE TABLE IF NOT EXISTS student
(
id_num VARCHAR(40) NOT NULL REFERENCES registered(student_id),
first_name VARCHAR(32) NOT NULL,
last_name VARCHAR(32) NOT NULL,
birthdate DATE NOT NULL,
PRIMARY KEY(id_num)
);
CREATE TABLE IF NOT EXISTS registered
(
student_id VARCHAR(40) NOT NULL REFERENCES student(id_num)
paid_tuition BOOL NOT NULL,
PRIMARY KEY(id_num)
);

ERROR: violates foreign key constraint, key is not present in parent table (but it is??)

I know this question has been asked many times, but none of the answers have solved my issue.
I am creating a database for a uni assignment, using PostgreSQL through pgadmin 4, and I have a table named "staff" populated with staff members with a primary key of "staffid". I then have another table named "client_international", which includes a foreign key of "staffid" which relates to the staff tables primary key.
When trying to insert into the client table, I am getting the following error:
ERROR: insert or update on table "client_international" violates foreign key constraint "intclient_staff_fkey"
DETAIL: Key (staffid)=(100000024) is not present in table "staff".
SQL state: 23503
I am certain that that '100000024' key is in the staff table.. yet I still get the error. Any suggestions? Below I will paste the code I used to create the staff and client tables, in case anyone notices an error in them.
Staff table:
CREATE SEQUENCE staff_seq
start 100000000
increment 1;
CREATE TABLE staff
(
staffid integer default nextval('staff_seq'),
firstname varchar(20) NOT NULL,
lastname varchar(20) NOT NULL,
"position" varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,
email varchar(100) NOT NULL,
"location" integer NOT NULL,
CONSTRAINT staff_pkey PRIMARY KEY (staffid)
);
Client table:
CREATE SEQUENCE client_seq
start 200000000
increment 1;
CREATE TABLE client
(
clientid integer default nextval('client_seq'),
company varchar(100) NOT NULL,
sector varchar(100) NOT NULL,
pointofcontact varchar(20) NOT NULL,
mobile varchar(20) NOT NULL,
email varchar(100) NOT NULL,
approvalstatus boolean default (false),
"location" integer NOT NULL,
staffid integer NOT NULL,
CONSTRAINT client_pkey PRIMARY KEY (clientid)
);
CREATE TABLE client_international
(
CONSTRAINT client_international_pkey PRIMARY KEY (clientid)
) INHERITS ("client");
ALTER TABLE client
ADD CONSTRAINT client_location_fkey FOREIGN KEY ("location") REFERENCES "location" (locationid),
ADD CONSTRAINT client_staff_fkey FOREIGN KEY (staffid) REFERENCES staff (staffid);
ALTER TABLE client_international
ADD CONSTRAINT intclient_location_fkey FOREIGN KEY ("location") REFERENCES "location" (locationid),
ADD CONSTRAINT intclient_staff_fkey FOREIGN KEY (staffid) REFERENCES staff (staffid);
I get the error when running the following statements:
INSERT INTO client_international(company, sector, pointofcontact, mobile, email, approvalstatus, "location", staffid)
VALUES ('Moores Dogs', 'Border Patrol', 'Carol Moore', '07911 653453', 'jenkinsj#k9solutions.co.uk', 'false', '500000001', '100000024');
Here's a screenshot of the entry in the staff table, showing that it's definitely in there:
Foreign keys aren't "inherited".
Quote from the manual
A serious limitation of the inheritance feature is that [...] foreign key constraints only apply to single tables, not to their inheritance children. This is true on both the referencing and referenced sides of a foreign key constraint.
(emphasis mine)
So what you are trying to do, simply isn't supported.

SQL: Foreign key references a composite primary key

I'm new to SQL and there are a lot of things going on that I still don't seem to quite understand. I have the following table
CREATE TABLE Person
(
First_Name varchar(20) NOT NULL,
Name varchar(20) NOT NULL,
Address varchar(50) NOT NULL,
PRIMARY KEY (First_Name, Name, Address)
);
I know want to create another table that has the primary key from the table Person as foreign key and also as primary key:
CREATE TABLE Purchase
(
No_Installments int,
Rate int,
Person varchar(50) NOT NULL PRIMARY KEY,
CONSTRAINT PFK
FOREIGN KEY (Person) REFERENCES Person (First_Name, Name, Address)
);
For some reason this doesn't work and I get an error every time. I've already looked up the other threads here on stackoverflow, but they don't really seem to help me. What am I doing wrong?
If you have a compound PK made up from three columns, then any child table that wants to establish a foreign key relationship must ALSO have all those 3 columns and use all 3 columns to establish the FK relationship.
FK-PK relationship is an all or nothing proposal - you cannot reference only parts of a primary key - either you reference all columns - or you don't reference.
CREATE TABLE Purchase
(
No_Installments int,
Rate int,
Person varchar(50) NOT NULL PRIMARY KEY,
First_Name varchar(20) NOT NULL,
Name varchar(20) NOT NULL,
Address varchar(50) NOT NULL,
CONSTRAINT PFK
FOREIGN KEY (First_Name, Name, Address)
REFERENCES Person (First_Name, Name, Address)
);
Have an integer primary key, using identity, auto_increment, serial or whatever for your database:
CREATE TABLE Person (
PersonId int identity PRIMARY KEY
First_Name varchar(20) NOT NULL,
Name varchar(20) NOT NULL,
Address varchar(50) NOT NULL,
CONSTRAINT unq_person_3 UNIQUE (First_Name, Name, Address)
);
Then use the identity column for the reference:
CREATE TABLE Purchase (
PurchaseId int identity PRIMARY KEY,
No_Installments int,
Rate int,
PersonId int,
CONSTRAINT PFK
FOREIGN KEY (PersonId) REFERENCES Person (PersonId)
);
Notes:
You really don't want to have to deal with a composite primary key. Have you thought about what the joins will look like?
You don't want a primary key where the values are subject to change. What happens when someone changes his/her name? When someone moves?
Person should not be the primary key in Purchases. Are you only allowing someone to make one purchase?
As noted initially, how you generate such a column varies by database; identity happens to be the way that SQL Server does this.
You probably want to assign a unique ID to each person, not relying on their name to be unique or for an address to be required. That ID will be your Primary key and foreign key. Your purchase table should also have its own id for its primary key -- otherwise because primary keys must be unique, each person can only have one purchase.
CREATE TABLE Person (
id serial NOT NULL,
First_Name varchar(20) NOT NULL,
Name varchar(20) NOT NULL,
Address varchar(50) NOT NULL,
PRIMARY KEY (id));
CREATE TABLE Purchase (
id serial NOT NULL,
No_Installments int,
Rate int,
Person int NOT NULL,
FOREIGN KEY (Person) REFERENCES Person (id),
PRIMARY KEY (id));

SQL Constraints Confusion

I'm in a bit of a mix right now, I have a Table called Avatars, which has a foreign key called Family. Now, in the family table, I have two Foreign Keys called Mother and Father - Now this is the confusing bit, in both the Mother and Father Tables, there is a Foreign key called Avatar_ID which is of course the Primary Key to the Avatars table. I'm not sure if that's even allowed in SQL PLUS.
Whenever I try and enter the tables 'Family, Mother or Father', I keep getting the error:ORA-02291: integrity constraint (SG304.FK_FATHER_ID) violated - parent key not found.
Is there any way around this? Or will I have to change my code completely? A sample of the code is below.
CREATE TABLE Avatars (
Avatar_ID VARCHAR(10) NOT NULL,
Avatar_Name VARCHAR(30),
AvA_DOB DATE,
Age VARCHAR(30),
Gender VARCHAR(30),
Strength_Indicated INT,
Hoard INT,
Avatar_Level VARCHAR(30),
Skill VARCHAR(30),
Original_Owner VARCHAR(30),
Family_ID VARCHAR(10) NOT NULL,
Species_ID VARCHAR(10) NOT NULL,
Inventory_ID VARCHAR(30) NOT NULL,
Weapon_ID VARCHAR(10),
Player_ID VARCHAR(10) NOT NULL,
PRIMARY KEY (Avatar_ID));
CREATE TABLE Family (
Family_ID VARCHAR(10) NOT NULL,
Mother_ID VARCHAR(10) NOT NULL,
Father_ID VARCHAR(10) NOT NULL,
primary key(Family_ID)
);
CREATE TABLE Mother (
Mother_ID VARCHAR(10) NOT NULL,
Avatar_ID VARCHAR(10) NOT NULL,
primary key(Mother_ID)
);
CREATE TABLE Father (
Father_ID VARCHAR(10) NOT NULL,
Avatar_ID VARCHAR(10) NOT NULL,
primary key(Father_ID)
);
ALTER TABLE Avatars
ADD CONSTRAINT fk_Family_ID
FOREIGN KEY (Family_ID)
REFERENCES Family(Family_ID);
ALTER TABLE Family
ADD CONSTRAINT fk_Mother_ID
FOREIGN KEY (Mother_ID)
REFERENCES Mother(Mother_ID);
ALTER TABLE Family
ADD CONSTRAINT fk_Father_ID
FOREIGN KEY (Father_ID)
REFERENCES Father(Father_ID);
ALTER TABLE Father
ADD CONSTRAINT fk_Avatar_ID
FOREIGN KEY (Avatar_ID)
REFERENCES Avatars(Avatar_ID);
ALTER TABLE Mother
ADD CONSTRAINT fk_Avatars_ID
FOREIGN KEY (Avatar_ID)
REFERENCES Avatars(Avatar_ID);
INSERT INTO Avatars (Avatar_ID,Avatar_Name,AvA_DOB,Age,Gender,Strength_Indicated,Hoard,Avatar_Level, Skill, Original_Owner, Family_ID,Species_ID,Inventory_ID,Player_ID) VALUES
('Ava01','Verda','20-JAN-2014','1 year 2 months','Female','100','20','Master','Leader',' - ',' - ','DRA1','MasterInventory','Player07');
Thanks in advance for any help given! (:
Foreign key refers to a record in parent table. In your INSERT statement you are inserting value ' - ' into a column parent_id. In this error message oracle informs you that there is no record with value ' - ' in a column family_id of a table family. As I can understand, you are trying to use ' - ' as 'absence of value'. There is special value for that - NULL. So you need to write your statement as:
INSERT INTO Avatars (Avatar_ID, Avatar_Name, AvA_DOB,
Age, Gender, Strength_Indicated, Hoard, Avatar_Level, Skill,
Original_Owner, Family_ID, Species_ID, Inventory_ID, Player_ID)
VALUES ('Ava01', 'Verda', '20-JAN-2014', '1 year 2 months' ,'Female',
'100', '20', 'Master', 'Leader', NULL, NULL, 'DRA1',
'MasterInventory', 'Player07');
Also I can recommend some changes to your schema. First of all, use number data type for primary keys - it allows you to use sequences to generate unique values. Also, I don't know details of the problem, but "family relations" in your tables look a bit complicated. You can describe it in a single table:
create table family_tree (
person_id number primary key,
father_id number,
mother_id number,
sex char(1),
name varchar2(50),
family_name varchar2(50));
add constraint fk_mother_id foreign key (mother_id)
references family_tree (person_id);
add constraint fk_father_id foreign key (father_id)
references family_tree (person_id);

Type matches correctly, but why " #1215 - Cannot add foreign key constraint" keeps poping out?

This is my first table "address".
create table address(
street varchar(32) not null,
city varchar(32) not null,
state varchar(32) not null,
zip_code varchar(32) not null,
primary key(zip_code)
)
This is my second table "customer".
create table customer(
customer_id integer not null,
name varchar(32) not null,
primary key(customer_id)
)
This is my relational table about above two tables. But why cannot I make it? The type matches well. So please.
create table cus_live(
customer_id integer not null,
zip_code varchar(32) not null,
primary key(customer_id, zip_code),
foreign key(customer_id) references customer,
foreign key(zip_code) references address
)
This is the correct way to create a foreign key constraint:
create table cus_live(
cus_live_id int not null,
customer_id int not null,
address_id int not null,
primary key(cus_live_id),
foreign key(customer_id) references customer (customer_id),
foreign key(address_id) references address (address_id)
)
Notice the changes I made:
After references [tableName], added the key name in parentheses. This will tell SQL which column is referenced in the foreign key constrant.
Changed the primary key of the table to its own unique id rather than a composite of two columns. Usually this is better practice.
Changed primary key of address table to address_id instead of zipcode. Otherwise you would have conflicts if two customers have the same zipcode but different addresses within that zipcode.
Made your id's integers instead of strings.
Also, note that this is all assuming that cus_live has some other columns that you have excluded (and cannot be included on either the address or customer table) and hence warrants having this third table in the first place. Otherwise you could just put address_id on the customer table like this:
create table address(
address_id int not null,
street varchar(32) not null,
city varchar(32) not null,
state varchar(32) not null,
zip_code varchar(32) not null,
primary key(address_id)
)
create table customer(
customer_id int not null,
name varchar(32) not null,
address_id int not null,
primary key(customer_id)
foreign key(address_id) references address (address_id)
)