ORA-02270: no matching unique or primary key for this column-list - sql

I have the following SQL code
CREATE TABLE EMPLOYEES
(
empID NUMBER NOT NULL,
ssn CHAR(10) NOT NULL,
fname VARCHAR(20) NOT NULL,
minit VARCHAR(15),
lname VARCHAR(30) NOT NULL,
gender CHAR(2),
email VARCHAR(40),
street VARCHAR(40),
postalCode NUMBER,
city VARCHAR(20),
country VARCHAR(20),
job VARCHAR(20),
salary NUMBER(*,2),
birthdate DATE,
specialization VARCHAR(30),
username VARCHAR(25),
password VARCHAR(25),
levelOfClearance VARCHAR(20),
PRIMARY KEY (empID),
UNIQUE (ssn)
);
CREATE TABLE PATIENTS
(
patientID NUMBER NOT NULL,
healthInsID NUMBER,
fname VARCHAR(20) NOT NULL,
minit VARCHAR(15),
lname VARCHAR(30) NOT NULL,
gender CHAR(1),
email VARCHAR(40),
street VARCHAR(40),
postalCode CHAR(4),
city VARCHAR(20),
country VARCHAR(20),
PRIMARY KEY (patientID),
FOREIGN KEY (healthInsID) REFERENCES HEALTH_INSURANCES (healthInsID)
ON DELETE SET NULL
);
CREATE TABLE APPOINTMENTS
(
appointmentID NUMBER NOT NULL,
empID NUMBER NOT NULL,
appointmentDate DATE,
cost NUMBER(*,2),
patientID NUMBER,
PRIMARY KEY (appointmentID),
FOREIGN KEY (empID) REFERENCES EMPLOYEES (empID)
ON DELETE SET NULL,
FOREIGN KEY (patientID) REFERENCES PATIENTS
ON DELETE SET NULL
);
CREATE TABLE SYMPTOMS
(
appointmentID NUMBER NOT NULL,
description VARCHAR(100),
PRIMARY KEY (appointmentID),
FOREIGN KEY (appointmentID) REFERENCES APPOINTMENTS (appointmentID)
ON DELETE SET NULL
);
The first 3 tables are created without a problem, but the last one give me the error "ORA-02270: no matching unique or primary key for this column-list". I have searched a lot but could not find any solution yet.

Not sure but I think the problem probably is with last line in your symptoms table
CREATE TABLE SYMPTOMS
(
appointmentID NUMBER NOT NULL, <-- it's NOT NULL
description VARCHAR(100),
PRIMARY KEY (appointmentID),
**FOREIGN KEY (appointmentID) REFERENCES APPOINTMENTS (appointmentID)
ON DELETE SET NULL** <-- here you are saying -- set to null on delete
);
You are trying to null the appointmentID which you have declared as non null. This doesn't looks correct. I tried creating the same table with on delete cascade and it worked fine.
(OR)
Try creating your SYMPTOMS table like below
CREATE TABLE SYMPTOMS
(
appointmentID number NOT NULL,
description VARCHAR(100),
FK_APT_APTID number null,
PRIMARY KEY (appointmentID),
FOREIGN KEY (FK_APT_APTID) REFERENCES APPOINTMENTS (appointmentID)
ON DELETE set null
);
See this sample fiddle
http://sqlfiddle.com/#!3/826dd

The problem is with the SYMPTOMS table, your PK can be set to null (which is not possible)
I suggest you'll do the following:
Add a symptom ID column as a PK (or set the combination of description and appointmentID as PK)
Set on delete cascade or don't set a delete policy: this will cause an error if you delete an appointment and will raise an exception that you'll need to handle in your code.
sql fiddle: http://sqlfiddle.com/#!4/67d4b
CREATE TABLE SYMPTOMS
(
SymptomID NUMBER NOT NULL,
appointmentID NUMBER NOT NULL,
description VARCHAR(100),
PRIMARY KEY (appointmentID),
FOREIGN KEY (appointmentID) REFERENCES APPOINTMENTS (appointmentID)
);

Related

ERROR :ORA-02264: name already used by an existing constraint

create table ward
(
wnum int primary key,
wname varchar(30),
phoneno int,
wloc varchar(50),
chnursename varchar(20) constraint ward_fk references charge_nurse
);
create table charge_nurse
(
chnurse varchar(20) constraint charge_nurse_pk primary key,
stnum int constraint charge_nurse_fk references staff
);
create table staff
(
stname varchar(20),
stnum int constraint staff_pk primary key,
addr varchar(20),
phoneno int,
stposition varchar(30),
specality varchar(30) unique,
shift varchar(10),
noofhoursperweek int
);
create table generalsupplies
(
itnum int constraint generalsupplies_pk primary key,
itname varchar(20) unique,
quantityinstock int,
reorder varchar(10),
despt varchar(10),
costperunit int
);
create table pharmasupplies
(
dnum int constraint pharmasupplies_pk primary key,
dname varchar(30) unique,
despt varchar(20),
dosage_Mg int,
quantityinstock int,
reorder varchar(10),
costperunit int
);
While creating the below table I am facing problem:
ORA-02264: name already used by an existing constraint
create table centralsupplies
(
wardnum int constraint centralsupplies_fk references ward,
itemnum int constraint centralsupplies_fk references generalsupplies,
drugnum int constraint centralsupplies_fk references pharmasupplies,
quantity_required varchar(20),
staffname varchar(10) references staff(stname),
staffnum int constraint centralsupplies_fk references staff,
regnum int unique,
dateord date,
daterec date
);
How do I solve this problem?
You use 3 times the same constraint name centralsupplies_fk in your centralsupplies table.
3 constraints = 3 constraint names
Your create table statement has four foreign keys all called centralsupplies_fk. That is not allowed: constraint names must be unique within a schema. You must give each one a different name.
It is usual practice to include the referenced table in the key name. So
create table centralsupplies
(
wardnum int constraint centralsupplies_ward_fk references ward,
itemnum int constraint centralsupplies_generalsupplies_fk references generalsupplies,
drugnum int constraint centralsupplies_pharmasupplies_fk references pharmasupplies,
quantity_required varchar(20),
staffname varchar(10) references staff(stname),
staffnum int constraint centralsupplies_staff_fk references staff,
regnum int unique,
dateord date,
daterec date
)
Also you have another foreign key constraint on STAFFNAME which you have not named. You do not need to name constraints, the system will generate a unique one for you, but it's generally a good idea to name them, not least because it is easier to diagnose relational integrity error messages with meaningfully named constraints.
However, in this case the correct solution is to drop the STAFFNAME column. You already have a foreign on the STAFF table, and you should join to that table whenever you need to display a value for STAFFNAME. Besides you do not have a unique constraint on staff.stname column, so the foreign key statement will fail: foreign keys can only reference primary or unique keys.

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));

The INSERT statement conflicted with the FOREIGN KEY constraint"

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)

PSQL Error there is no unique constraint matching given keys for referenced table

I have a baseball database. I'm getting the error Error there is no unique constraint matching given keys for referenced table pitcher.
Here's the schema
CREATE TABLE Teams(
Name varchar(30) NOT NULL Primary Key,
Record varchar(10)
);
CREATE TABLE Player(
Name varchar(30) NOT NULL,
Num int NOT NULL,
TeamName varchar(22) references Teams(Name),
PRIMARY KEY(Name, Num, TeamName),
Constraint NumCheck Check (Num < 100 and Num > -1)
);
CREATE TABLE Pitcher(
PHanded varchar(10),
PName varchar(30),
PTeamName varchar(30),
PNum int,
PRIMARY KEY(PName, PTeamName, PNum),
foreign key (PName, PTeamName, PNum) references Player(Name, TeamName, Num)
);
CREATE TABLE PosPlayer(
PPHanded varchar(10),
Position varchar(2),
PPName varchar(30),
PPNum int,
BTeamName varchar(30),
PRIMARY KEY(PPName, PPNum, BTeamName),
foreign key (PPName, PPNum, BTeamName) references Player(Name, Num, TeamName)
);
CREATE TABLE Games(
Id int Primary Key,
SchedDate DATE,
PlayedDate DATE,
HomeName varchar(30),
VisitName varchar(30),
Winner varchar(30)
);
CREATE TABLE Pitches
(
PID int,
Outcome varchar(10),
Bcount int,
Scount int,
Runners int,
Type varchar(10),
Speed int,
Pitchnum int,
PitName varchar(30) references Pitcher(PName),
PitNum int references Pitcher(PNum),
PitTeamName varchar(30) references Pitcher(PTeamName),
BatName varchar(30) references PosPlayer(PPName),
BatNum int references PosPlayer(PPNum),
BatTeamName varchar(30) references PosPlayer(BTeamName),
HomeTName varchar(30),
VisitTName varchar(30),
GId int references Games(Id),
foreign key (PitName, PitNum, PitTeamName) references Pitcher (PName, PNum, PTeamName),
foreign key (BatName, BatNum, BatTeamName) references PosPlayer (PPName, PPNum, BTeamName),
Primary Key(PID, PitName, PitNum, PitTeamName, BatName, BatNum, BatTeamName, GID),
Constraint Balls Check (Bcount > -1 and Bcount < 4),
Constraint Scount Check (Scount > -1 and Scount < 3)
);
In the other threads I looked up it was suggested to add a unique identifier, but in this schema it is possible to have the same name and be on the same team. How do I fix this?
The lines
CREATE TABLE Pitches
(
{...}
PitName varchar(30) references Pitcher(PName),
PitNum int references Pitcher(PNum),
PitTeamName varchar(30) references Pitcher(PTeamName),
BatName varchar(30) references PosPlayer(PPName),
BatNum int references PosPlayer(PPNum),
BatTeamName varchar(30) references PosPlayer(BTeamName),
{...}
)
are almost certainly the ones causing you grief. You're trying in each case to reference a nonunique column in the referenced table, and that just won't work.
The good news is that you don't need these references clauses, as they're taken care of by the table-level FOREIGN KEY clauses, each of which references a group of columns whose concatenated values are unique, due to being a composite primary key.

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);