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

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.

Related

No primary or candidate keys in the referenced table?

I keep getting an error:
There are no primary or candidate keys in the referenced table 'TProducts' that match the referencing column list in the foreign key 'TProducts_TCategories_FK'."
When trying to establish a relationship between my products table and categories table. I have checked the spelling multiple times but can't seem to figure out why I keep getting this error. The rest of my tables are fine, and I used the same method.
CREATE TABLE TCategories
(
intCategoryID INTEGER NOT NULL,
strCategoryName VARCHAR(255) NOT NULL,
CONSTRAINT TCategories_PK PRIMARY KEY (intCategoryID)
)
CREATE TABLE TProducts
(
intProductID INTEGER NOT NULL,
intVendorID INTEGER NOT NULL,
intCategoryID INTEGER NOT NULL,
strProductName VARCHAR(255) NOT NULL,
monCostofProduct MONEY NOT NULL,
monRetailCost MONEY NOT NULL,
intInventory INTEGER NOT NULL,
CONSTRAINT TProducts_PK PRIMARY KEY (intProductID)
)
ALTER TABLE TProducts
ADD CONSTRAINT TProducts_TCategories_FK
FOREIGN KEY (intCategoryID) REFERENCES TProducts (intCategoryID)
You are referencing to TProducts table and not TCategories table:
ALTER TABLE TProducts ADD CONSTRAINT TProducts_TCategories_FK
FOREIGN KEY ( intCategoryID ) REFERENCES TCategories( intCategoryID )

Translate the schema provided in into an “equivalent” relational schema (tables) in SQL

Person(p#,name,birthdate,nationality,gender)
Actor(p#,aguild#)
FK (p#) refs Person
Director(p#,dguild#)
FK (p#) refs Person
Writer(p#, wguild#)
FK (p#) refs Person
Studio(name)
ScreenPlay(title,year)
Authored(title,year,writer)
FK (title, year) refs ScreenPlay
FK (writer) refs Writer (p#)
Movie(title,studio,year,genre,director,length)
FK (studio) refs Studio (name)
FK (title, year) refs ScreenPlay
FK (director) refs Director (p#)
Cast(title,studio,year,role,actor,minutes)
FK (title, studio, year) refs Movie
FK (actor) refs Actor (p#)
Affiliated(director,studio)
FK (director) refs Director (p#)
FK (studio) refs Studio (name)
I am unable to make the table for the author, I get an error saying "does not conform to the description
of the parent key of table or nickname"
CREATE TABLE person (
p# int,
name varchar(255),
birthdate DATE,
nationality varchar(255),
gender varchar(255),
constraint person_pk
primary key (p#)
);
CREATE TABLE actor (
p# int,
aguild varchar(255),
constraint actor_pk   
primary key (p#),
constraint actor_fk_person
foreign key (p#) references person
);
CREATE TABLE director (
p# int,
dguild varchar(255),
constraint director_pk   
primary key (p#),
constraint director_fk_person
foreign key (p#) references person
);
CREATE TABLE writer (
p# int,
wguild varchar(255),
constraint writer_pk   
primary key (p#),
constraint writer_fk_person
foreign key (p#) references person
);
CREATE TABLE studio (
name varchar(255) not null,
constraint studio_pk   
primary key (name)
);
CREATE TABLE screenplay (
title varchar(255) not null,
year varchar(255) not null,
constraint screenplay_pk   
primary key (title, year)
);
CREATE TABLE authored (
title varchar(255) not null,
year varchar(255) not null,
writer varchar(255) not null,
constraint authored_pk
primary key (title,year,writer),
constraint authored_fk_titleyear
foreign key (title, year) references screenplay,
constraint authored_fk_writer
foreign key (writer) references writer (p#) on delete no action
);
CREATE TABLE movie (
title varchar(255) not null,
studio varchar(255) not null,
year varchar(255) not null,
genre varchar(255),
director varchar(255),
length varchar(255),
constraint movie_pk   
primary key (title, studio, year),
constraint movie_fk_studio
foreign key (studio) references studio(name),
constraint movie_fk_titleyear
foreign key (title, year) references screenplay,
constraint movie_director
foreign key (director) references director(p#)
);
CREATE TABLE cast (
title varchar(255) not null,
studio varchar(255) not null,
year varchar(255) not null,
role varchar(255) not null,
actor varchar(255) not null,
minutes varchar(255),
constraint cast_pk   
primary key (title, studio, year, role, actor),
constraint cast_fk_titlestudioyear
foreign key (title, studio, year) references movie,
constraint cast_fk_actor
foreign key (actor) references actor(p#)
);
CREATE TABLE affiliated (
director varchar(255) not null,
studio varchar(255) not null,
constraint affiliated_pk   
primary key (director, studio),
constraint affiliated_fk_director
foreign key (director) references director(p#)
constraint affiliated_fk_studio
foreign key (studio) references studio(name)
);
You have several elementary mistakes. You appear to be learning, so take the time to study basic rules of RDBMS and data modelling/normalisation.
It's unwise to use column names with special characters like # because it will give maintenance and usability issues. You are using "p#" to indicate a primary key that is a surrogate, but that is unwise, consider using a naming convention instead for column-names of surrogate key. For example : person_pk, actor_pk, director_pk, writer_pk.
Some of your tables use surrogate keys (p#) while others use natural keys(example studio.name). If you use natural-keys that are long (example varchar(255)), then child tables that use those natural-keys will use much more space and searches will be less efficient than if you use a surrogate key of type integer or bigint for the pk.
Next if you want a column to act as a primary key then it must be NOT NULL. some of your tables break this rule so will fail to create.
When you have a foreign key, its column(s) datatype(s) must match that of the relevant parent table column(s). Your example breaks that rule so you will get syntax errors.
authored_fk_writer needs to reference a key of writers but you have omitted any key field, and the relevant foreign key column is varchar(255) which does not correspond to the primary key of writer (which is int).
For some of your compound foreign keys that use natural-keys, the compound length exceeds documented limits. Consider normalising your model to use correct datatypes for the foreign key columns (i.e. don't duplicate the natural key in the child table, but instead use the surrogate key column of the parent table).
The clause 'references writer ()' is not correct in DB2. You must either not specify any columns including parentheses (the parent table must have PK in this case), or specify the corresponding columns of the parent table explicitly inside the parentheses (the parent table must have PK or Unique Constraint on them).
Check the REFERENCES clause syntax of the CREATE TABLE statement.

error: there is no unique constraint matching given keys for referenced table "incident"

I know that this question has been already answered a million of times, but I couldn't find any solution. Well I have these three tables on postgres sql.
CREATE TABLE user_account (
id SERIAL not null,
firstName VARCHAR(60) not null,
lastName VARCHAR(60) not null,
password VARCHAR(150) not null,
email VARCHAR(40) not null UNIQUE,
isVolunteer BOOLEAN,
complete BOOLEAN,
CONSTRAINT pk_user PRIMARY KEY (id));
CREATE TABLE incident (
id SERIAL not null,
patientId INTEGER not null,
incidentTime VARCHAR(10) not null,
latitude NUMERIC not null,
longitude NUMERIC not null,
city VARCHAR(60) not null,
state VARCHAR(60),
country VARCHAR(60),
complete BOOLEAN,
CONSTRAINT pk_incident PRIMARY KEY (id, patientId),
CONSTRAINT fk_incident FOREIGN KEY (patientId)
REFERENCES user_account (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE);
CREATE TABLE incident_has_volunteer (
incidentId INTEGER not null,
volunteerId INTEGER not null,
incidentTime VARCHAR(10) not null,
complete BOOLEAN,
CONSTRAINT pk_incident_has_volunteer PRIMARY KEY (incidentId, volunteerId),
CONSTRAINT fk_volunteer FOREIGN KEY (volunteerId)
REFERENCES user_account (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_incident FOREIGN KEY (incidentId)
REFERENCES incident (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE);
When I try to create the table incident_has_volunteer it throws the error there is no unique constraint matching given keys for referenced table "incident".
I tried to add on the third table and the patientId as a foreign key from table incident table but with no luck. I can't understand why it throws this error even if I have already set the primary keys on the incident table.
I'm not an expert in postgres, but I believe that the problem is while fk_incident is referencing incident.id, incident's primary key is made of id + patientId. Since incident.id is guaranteed to be unique only in combination with patientId, there's no way to ensure referential integrity.
I believe that if you add a unique constraint to incident.id (I'm assuming that it would be unique), your foreign key will be legal.
Very simply - one table of primary key acts as a foreign key for another table, so you must ensure that both key is referenced or not.
Simply you will not assign foreign key to the column of another table which does not have primary key. this is called as RDBMS.
Thanks

Are these FKs necessary -- and are they stopping me?

I'm having some difficulties with a database I'm creating for a summer camp, specifically with the PK and FK constraints. When I declare the FK constraint (e.g. FOREIGN KEY(PID) references Campers(CamperID)) I get an error running my code through pgAdmin (I'm using PostgreSQL). I understand that, for example, the Campers table is not yet created, and this is most likely part/all of the roadblock, however I feel like my FKs are still wrong somehow. To my understanding, a FK is a PK in another table -- but I feel like there is some redundancy or disconnect between my tables.
I've put the syntax for some of my CREATE statements below. I'm not sure if I'll get reprimanded for the quality of my (somewhat vague) question, but I feel a bit lost and would appreciate any help or advice. Thank you in advance!
DROP TABLE IF EXISTS People;
CREATE TABLE People (
PID VARCHAR(10) NOT NULL UNIQUE,
FName TEXT NOT NULL,
LName TEXT NOT NULL,
DOB DATE NOT NULL,
ArrivalDate DATE NOT NULL DEFAULT CURRENT_DATE,
DepartureDate DATE,
US_PhoneNum VARCHAR(11) NOT NULL,
StreetAddress VARCHAR(200) NOT NULL,
Sex GENDER NOT NULL,
ZIP VARCHAR(10) NOT NULL,
PRIMARY KEY(PID),
FOREIGN KEY(PID) REFERENCES Campers(CamperID),
FOREIGN KEY(PID) REFERENCES Counselors(CounselorID),
FOREIGN KEY(ZIP) REFERENCES Zip(ZIP)
);
DROP TABLE IF EXISTS Zip;
CREATE TABLE Zip (
ZIP VARCHAR(10) NOT NULL,
City TEXT NOT NULL,
State VARCHAR(2) NOT NULL,
PRIMARY KEY(ZIP)
);
DROP TABLE IF EXISTS Campers;
CREATE TABLE Campers (
CamperID VARCHAR(10) NOT NULL REFERENCES People(PID),
AgeGroup AGES NOT NULL,
CabinID VARCHAR(2) NOT NULL,
Bed BEDTYPES NOT NULL,
GroupID VARCHAR(3) NOT NULL,
PRIMARY KEY(CamperID),
FOREIGN KEY(CamperID) REFERENCES People(PID),
FOREIGN KEY(CabinID) REFERENCES Cabins(CabinID),
FOREIGN KEY(Bed) REFERENCES Beds(Bed),
FOREIGN KEY(GroupID) REFERENCES Groups(GroupID)
);
DROP TABLE IF EXISTS Counselors;
CREATE TABLE Counselors (
CounselorID VARCHAR(10) NOT NULL REFERENCES People(PID),
GroupID VARCHAR(3) NOT NULL,
CabinID VARCHAR(2) NOT NULL,
PRIMARY KEY(CounselorID),
FOREIGN KEY(GroupID) REFERENCES Groups(GroupID),
FOREIGN KEY(CabinID) REFERENCES Cabins(CabinID)
);
ERROR message for further clarification:
ERROR: relation "campers" does not exist
********** Error **********
ERROR: relation "campers" does not exist
SQL state: 42P01
There are more tables (obviously) which I can provide the create statements for, if needed.
You should really start here: Foreign key.
In the context of relational databases, a foreign key is a field (or
collection of fields) in one table that uniquely identifies a row of
another table.
What you are trying to do in your script is to create a circular link between People, Campers and Counselors. Having a Primary Key field also a Foreign Key mandates that IDs across all referenced tables are identical.
... and to create a Foreign Key the referenced table must already exist in the database. So you should start with the table that does not have any Foreign Keys and create tables that reference only those tables created previously. Alternatively you can create all tables without Foreign Keys and add them later, when all the tables are present.
... and to answer the question, Foreign Keys are never necessary, but they might help.

correcting errors in sql code

I am new to this website, i hope that i ask the question the right way
-- Create a Database table to represent the "FACT" entity.
CREATE TABLE FACT
(
Time_id DATE NOT NULL,
Area_id INTEGER NOT NULL,
Reported_crime_id INTEGER NOT NULL,
Crime_status VARCHAR(8) NOT NULL,
no_of_crime INTEGER NOT NULL,
Max_crime INTEGER NOT NULL,
Avg_crime INTEGER NOT NULL,
Min_crime INTEGER NOT NULL,
date_reported DATE NOT NULL,
-- Specify the PRIMARY KEY constraint for table "FACT".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_fact PRIMARY KEY (Time_id, Area_id, Reported_crime_id,
Crime_status)
);
-- Create a Database table to represent the "Crime_Dim" entity.
CREATE TABLE Crime_Dim
(
REPORTED_CRIME_ID INTEGER NOT NULL,
CRIME_TYPE_Desc VARCHAR(50),
DATE_REPORTED DATE NOT NULL,
Crime_type_id INTEGER NOT NULL,
-- Specify the PRIMARY KEY constraint for table "Crime_Dim".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_crime_dim PRIMARY KEY (REPORTED_CRIME_ID)
);
-- Create a Database table to represent the "Location_Dim" entity.
CREATE TABLE Location_Dim
(
AREA_ID INTEGER NOT NULL,
AREA_Name VARCHAR(30) NOT NULL,
Area_code INTEGER NOT NULL,
Force_id INTEGER NOT NULL,
-- Specify the PRIMARY KEY constraint for table "Location_Dim".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_location_dim PRIMARY KEY (AREA_ID)
);
-- Create a Database table to represent the "Time_Dim" entity.
CREATE TABLE Time_Dim
(
Time_id INTEGER NOT NULL,
day_id INTEGER NOT NULL,
Month_id INTEGER NOT NULL,
Year INTEGER,
-- Specify the PRIMARY KEY constraint for table "Time_Dim".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_time_dim PRIMARY KEY (Time_id)
);
-- Create a Database table to represent the "Reported_crime_dim" entity.
CREATE TABLE Reported_crime_dim
(
Crime_status VARCHAR(20) NOT NULL,
Date_reported DATE NOT NULL,
-- Specify the PRIMARY KEY constraint for table "Reported_crime_dim".
-- This indicates which attribute(s) uniquely identify each row of data.
CONSTRAINT pk_reported_crime_dim PRIMARY KEY (Crime_status)
);
-- i.e. tables may be referenced before they have been created. This method is therefore safer.
-- Alter table to add new constraints required to implement the "FACT_Time_Dim" relationship
-- This constraint ensures that the foreign key of table "FACT"
-- correctly references the primary key of table "Time_Dim"
ALTER TABLE FACT
ADD CONSTRAINT fk1_fact_to_time_dim FOREIGN KEY(Time_id) REFERENCES Time_Dim(
Time_id) ON DELETE RESTRICT ON UPDATE RESTRICT;
-- Alter table to add new constraints required to implement the "FACT_Location_Dim" relationship
-- This constraint ensures that the foreign key of table "FACT"
-- correctly references the primary key of table "Location_Dim"
ALTER TABLE FACT
ADD CONSTRAINT fk2_fact_to_location_dim FOREIGN KEY(AREA_ID) REFERENCES
Location_Dim(AREA_ID) ON DELETE RESTRICT ON UPDATE RESTRICT;
-- Alter table to add new constraints required to implement the "FACT_Crime_Dim" relationship
-- This constraint ensures that the foreign key of table "FACT"
-- correctly references the primary key of table "Crime_Dim"
ALTER TABLE FACT
ADD CONSTRAINT fk3_fact_to_crime_dim FOREIGN KEY(REPORTED_CRIME_ID) REFERENCES
Crime_Dim(REPORTED_CRIME_ID) ON DELETE RESTRICT ON UPDATE RESTRICT;
-- Alter table to add new constraints required to implement the "FACT_Reported_crime_dim" relationship
-- This constraint ensures that the foreign key of table "FACT"
-- correctly references the primary key of table "Reported_crime_dim"
ALTER TABLE FACT
ADD CONSTRAINT fk4_fact_to_reported_crime_dim FOREIGN KEY(Crime_status)
REFERENCES Reported_crime_dim(Crime_status) ON DELETE RESTRICT ON UPDATE
RESTRICT;
--------------------------------------------------------------
-- End of DDL file auto-generation
--------------------------------------------------------------
​
Could someone help me in correcting the errors in the sql code above? when i run the code as mentioned at the last few codes i need to create constraint to prevent Foreign keys in the Fact table and relate them back to their original table if i have got this right...
could someone correct the code and let me know plz
Following this answer, you have to remove ON DELETE RESTRICT and ON UPDATE RESTRICT.
There's no such option in Oracle.