referencing keys oracle, could be foreign key issue - sql

I keep having an issue where I'm trying to load all my tables into a database.
Whenever I try load a table which references "paper_code" I keep getting problem errors, which then don't create the table.
I've been trying to nail out the errors and have got some papers loading, but it seems only the tables that reference papers(paper_code) are having issues.
code:
DROP TABLE contacts;
DROP TABLE gender;
DROP TABLE lecture_location;
DROP TABLE enrols;
DROP TABLE teaches;
DROP TABLE staff;
DROP TABLE student;
DROP TABLE papers;
DROP TABLE departments;
CREATE TABLE departments
(dept_id INT PRIMARY KEY,
dept_location VARCHAR2(25) NOT NULL,
dept_name VARCHAR2(25) NOT NULL);
INSERT INTO departments VALUES
(01, 'ALBANY STREET', 'COMPUTER SCIENCE');
INSERT INTO departments VALUES
(02, 'UNION STREET', 'MUSIC');
INSERT INTO departments VALUES
(03, 'HOWE STREET', 'ANATOMY');
INSERT INTO departments VALUES
(04, 'ANZAC AVENUE', 'THEATRE');
CREATE TABLE papers
(paper_code INT,
EFTS INT NOT NULL,
dept_id INT REFERENCES departments(dept_id),
PRIMARY KEY(paper_code, dept_id));
INSERT INTO papers VALUES
(160, 0.18, 01);
INSERT INTO papers VALUES
(241, 0.18, 02);
INSERT INTO papers VALUES
(344, 0.18, 03);
INSERT INTO papers VALUES
(444, 0.18, 04);
CREATE TABLE student
(student_id INT PRIMARY KEY,
fname CHAR(11) NOT NULL,
lname CHAR(11) NOT NULL,
degree CHAR(15) NOT NULL);
INSERT INTO student VALUES
(172384, 'Michael', 'McDonald', 'BSc');
INSERT INTO student VALUES
(849294, 'Matthew', 'Brockie', 'BA');
INSERT INTO student VALUES
(384583, 'Daniel', 'Anderson', 'BSc');
CREATE TABLE staff
(staff_id INT PRIMARY KEY,
dept_id INT REFERENCES departments(dept_id),
fname CHAR(15) NOT NULL,
lname CHAR(15) NOT NULL);
INSERT INTO staff VALUES
(31, 01, 'Tony', 'Michaels');
INSERT INTO staff VALUES
(32, 01, 'Steph', 'Cardy');
INSERT INTO staff VALUES
(33, 02, 'Alex', 'Freeland');
INSERT INTO staff VALUES
(34, 02, 'Sam', 'Stewart');
INSERT INTO staff VALUES
(35, 03, 'Monique', 'Cardy');
INSERT INTO staff VALUES
(36, 03, 'Bayan', 'Zach');
CREATE TABLE teaches
(paper_code INT,
staff_id INT REFERENCES staff(staff_id),
dept_id INT,
PRIMARY KEY(paper_code, staff_id, dept_id),
FOREIGN KEY (paper_code, dept_id) REFERENCES papers(paper_code, dept_id));
INSERT INTO teaches VALUES
(160, 32, 01);
INSERT INTO teaches VALUES
(241, 31, 01);
INSERT INTO teaches VALUES
(344, 33, 02);
INSERT INTO teaches VALUES
(241, 34, 03);
INSERT INTO teaches VALUES
(444, 35, 03);
INSERT INTO teaches VALUES
(444, 36, 04);
CREATE TABLE enrols
(paper_code INT REFERENCES papers(paper_code),
student_id INT REFERENCES student(student_id),
date_enrolled DATE,
PRIMARY KEY(paper_code, student_id));
INSERT INTO enrols VALUES
(160, 172384, TO_DATE('22-Mar-1994', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(444, 849294, TO_DATE('14-Jul-1992', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(444, 172384, TO_DATE('23-Mar-1992', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(160, 384583, TO_DATE('07-Aug-1992', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES --fix
(160, 172384, TO_DATE('30-Jul-1994', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(241, 849294, TO_DATE('08-Sep-1995', 'dd-mon-yyyy'));
INSERT INTO enrols VALUES
(241, 384583, TO_DATE('25-Dec-1996', 'dd-mon-yyyy'));
CREATE TABLE lecture_location
(paper_code INT REFERENCES papers(paper_code),
dept_id INT REFERENCES departments(dept_id),
lecture_loc VARCHAR2(15),
PRIMARY KEY(paper_code, dept_id, lecture_loc));
INSERT INTO lecture_location VALUES
(160, 'ARCHWAY');
INSERT INTO lecture_location VALUES
(241, 'CASTLE');
CREATE TABLE gender
(student_id INT PRIMARY KEY REFERENCES student(student_id),
gender CHAR(9) NOT NULL);
INSERT INTO gender VALUES
(172384, 'Female');
INSERT INTO gender VALUES
(384583, 'Male');
CREATE TABLE contacts
(contact_details INT,
staff_id INT REFERENCES staff(staff_id),
PRIMARY KEY(contact_details, staff_id));
INSERT INTO contacts VALUES
(022017456, 31);
INSERT INTO contacts VALUES
(034737447, 31);
INSERT INTO contacts VALUES
(02285756, 32);
INSERT INTO contacts VALUES
(034735858, 32);
INSERT INTO contacts VALUES
(034552097, 33);
INSERT INTO contacts VALUES
(022867385, 33);
INSERT INTO contacts VALUES
(021495939, 34);
INSERT INTO contacts VALUES
(034993872, 35);
INSERT INTO contacts VALUES
(027459278, 36);
COMMIT;
All the tables except the ones refering paper_code are working.
Errors are:
INSERT INTO teaches VALUES
*
ERROR at line 1:
ORA-02291: integrity constraint (DAANDERSON.SYS_C00623423) violated - parent
key not found
For enrols:
(paper_code INT REFERENCES papers(paper_code),
*
ERROR at line 2:
ORA-02270: no matching unique or primary key for this column-list
For lecture_location
(paper_code INT REFERENCES papers(paper_code),
*
ERROR at line 2:
ORA-02270: no matching unique or primary key for this column-list
Been trying for a few hours and stil can't get to work. Any information appreciated!

When creating your table teaches, you have:
FOREIGN KEY (paper_code, dept_id) REFERENCES papers(paper_code, dept_id));
So every (paper_code, dept_id) must exist as (paper_code, dept_id) in papers.
Your 2nd entry (241, 01) does not exist, nor does your fourth value (241, 03).
(others may be missing, I didn't check them all)
You're also not inserting dept_id values into lecture_location
You have a primary key value duplicated in enrols:
(160, 172384)
This part of enrols:
CREATE TABLE enrols
(paper_code INT REFERENCES papers(paper_code),
is invalid, since you must reference a unique foreign key - and the only unique key on papers is its primary key of (paper_code, dept_id)
Ditto for this part of lecture_location:
(paper_code INT REFERENCES papers(paper_code),
On the bright side, after doing the fixes above the schema actually builds: http://sqlfiddle.com/#!4/5ed2c2

Related

AVG() inside LISTAGG()

I need to group two columns, one of them with an average, AVG() inside an LISTAGG().
I have the following code:
CREATE OR REPLACE VIEW countryTimes AS
SELECT
LISTAGG(claOL.odCode||'-'||(AVG(claOL.timeCla) GROUP BY(claOl.timeCla))) WITHIN GROUP (ORDER BY c.cCode) AS ProvaTempsMig,
c.cDescription AS País,
c.cCode AS CodiPaís
FROM countries c
JOIN athletes a ON c.cCode = a.country
JOIN classificationOL claOL ON a.idCode = claOL.idAth;
But this throws this error:
ORA-00907: missing right parenthiesis erecho 00907. 00000 - "missing right parenthesis" *Cause: *Action:
I'm using Oracle.
UPDATE:
What I need to do is create a view where appears cCode, cDescription and a last column with the AVG of all the times for a single country. So I need to create from multiple rows, a single row for each country.
Code:
CREATE TABLE Countries (
cCode VARCHAR(5) NOT NULL,
cdescription VARCHAR(100) NOT NULL,
CONSTRAINT couPK PRIMARY KEY (cCode)
);
CREATE TABLE athletes (
idCode NUMBER NOT NULL,
Name VARCHAR(200) NOT NULL,
Surname VARCHAR(200) NOT NULL,
country VARCHAR(5) NOT NULL,
CONSTRAINT athPK PRIMARY KEY (idCode),
CONSTRAINT countryFK FOREIGN KEY (country) REFERENCES Countries (cCode)
);
CREATE TABLE olympicDisciplines (
oCode VARCHAR(10) NOT NULL,
odName VARCHAR(200) NOT NULL,
discipline VARCHAR(200) NOT NULL,
CONSTRAINT olympicPK PRIMARY KEY (oCode)
);
CREATE TABLE classificationOL(
idAth NUMBER NOT NULL,
odCode VARCHAR(10) NOT NULL,
timeCla INTEGER,
CONSTRAINT classifPK PRIMARY KEY (idAth, odCode),
CONSTRAINT claAthFK FOREIGN KEY (idAth) REFERENCES athletes (idCode),
CONSTRAINT claDFK FOREIGN KEY (odCode) REFERENCES olympicDisciplines (oCode)
);
UPDATE 2:
Data:
INSERT INTO Countries VALUES ('UK', 'United Kingdom');
INSERT INTO Countries VALUES ('AND', 'Andorra');
INSERT INTO Countries VALUES ('FR', 'France');
INSERT INTO athletes VALUES (1, 'Jack', 'Johnson', 'UK');
INSERT INTO athletes VALUES (2, 'Pau', 'Márquez', 'AND');
INSERT INTO athletes VALUES (3, 'Pierre', 'Dubois', 'FR');
INSERT INTO athletes VALUES (4, 'Christophe', 'Dubois', 'FR');
INSERT INTO athletes VALUES (5, 'Adolphe', 'Moreau', 'FR');
INSERT INTO olympicDisciplines VALUES ('ATH', 'Athletics', 'Athletics');
INSERT INTO olympicDisciplines VALUES ('CYC', 'Cycling', 'Cycling');
INSERT INTO olympicDisciplines VALUES ('CCC', 'Cycling CC', 'Cross Country Cycling');
INSERT INTO classificationOL VALUES (1, 'ATH', 120);
INSERT INTO classificationOL VALUES (2, 'ATH', 119);
INSERT INTO classificationOL VALUES (3, 'CCC', 38);
INSERT INTO classificationOL VALUES (4, 'CCC', 37);
INSERT INTO classificationOL VALUES (5, 'ATH', 122);
Reading your first UPDATE, if you're allowed to, you can transform your tables to object to solve your necessity, instead of using LISTAGG(). I'll show you:
CREATE TYPE average AS OBJECT(
name VARCHAR(200),
avgerageTime NUMBER);
CREATE TYPE results AS TABLE OF average;
CREATE TYPE countriesResults AS OBJECT(
cName VARCHAR(100),
cCode VARCHAR(5),
classifications results
);
CREATE VIEW countriesAverages OF countriesResults
WITH OBJECT OID (coName)
AS
SELECT c.cdescription, c.ccode,
CAST (MULTISET (SELECT
olympicDisciplines.name, avg(classificationOL.timeCla)
FROM athletes a, countries, classificationOL, olympicDisciplines
WHERE countries.cCode = c.cCode
AND a.idCode = classificationOL.idAth
AND a.country = countries.cCode
AND olympicdisciplines.oCode = classificationOL.oCode
GROUP BY olympicdisciplines.odName) AS results )
FROM countries c;

Using multiple foreign keys in a SQL select statement

I have four tables, one of them named matches and another one named teams. I need to display the teamCode in teams with the number of point they have that we can calculate in matches. Each win is 2 points each draw one point and each lost zero.
CREATE TABLE divisions
(
codediv CHAR(1) NOT NULL,
nomdiv VARCHAR2(40)
);
ALTER TABLE divisions
ADD CONSTRAINT divisions_pk PRIMARY KEY (codediv);
CREATE TABLE teams
(
teamCode CHAR(3) NOT NULL,
teamName VARCHAR2(50),
codediv CHAR(1) NOT NULL,
ville VARCHAR2(40),
nbcoupes NUMBER
);
ALTER TABLE teams ADD CHECK (nbcoupes >= 0);
ALTER TABLE teams ADD CONSTRAINT teams_pk PRIMARY KEY (teamCode);
CREATE TABLE joueurs
(
numjoueur NUMBER(3) NOT NULL,
nom VARCHAR2(30),
prenom VARCHAR2(30),
codeequipe CHAR(3)
);
ALTER TABLE joueurs ADD CONSTRAINT joueurs_pk PRIMARY KEY (numjoueur);
CREATE TABLE matchs
(
MatchNumber NUMBER(4) NOT NULL,
datematch DATE,
codeVisitingTeam CHAR(3) NOT NULL,
codeReceivingTeam CHAR(3) NOT NULL,
scoreVisitingTeam NUMBER(2),
scoreReceivingTeam NUMBER(2)
);
ALTER TABLE matchs ADD CONSTRAINT matchs_pk PRIMARY KEY (MatchNumber);
CREATE TABLE statistiques
(
nummatch NUMBER(4) NOT NULL,
numjoueur NUMBER(3) NOT NULL,
nbbuts NUMBER(3),
nbpasse NUMBER(3)
);
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_pk PRIMARY KEY (numjoueur, nummatch);
ALTER TABLE matchs
ADD CONSTRAINT codeVisitingTeam FOREIGN KEY ( codeVisitingTeam)
REFERENCES teams ( teamCode );
ALTER TABLE teams
ADD CONSTRAINT teams_divisions_fk FOREIGN KEY ( codediv )
REFERENCES divisions ( codediv );
ALTER TABLE joueurs
ADD CONSTRAINT joueurs_equipes_fk FOREIGN KEY ( teamCode )
REFERENCES equipes ( teamCode );
ALTER TABLE matchs
ADD CONSTRAINT matchs_equipes_fk FOREIGN KEY ( CodeReceivingTeam )
REFERENCES equipes ( teamCode );
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_joueurs_fk FOREIGN KEY ( numjoueur )
REFERENCES joueurs ( numjoueur );
ALTER TABLE statistiques
ADD CONSTRAINT statistiques_matchs_fk FOREIGN KEY ( nummatch )
REFERENCES matchs ( nummatch );
insert into divisions values('O', 'OUEST');
insert into divisions values('E', 'EST');
insert into equipes values('MTL', 'LES CANADIENS DE MONTRÉAl', 'E', 'MONTRÉAl', 24);
insert into equipes values('TOR', 'LES MAPLE LEAFS', 'E', 'TORONTO', 22);
insert into equipes values('OTT', 'LES SÉNATEURS', 'E', 'OTTAWA', 4);
insert into equipes values('AVL', 'LES AVALANCHES', 'O', 'COLORADO', 2);
insert into equipes values('VAN', 'LES CANUKS', 'O', 'VANCOUVER', 1);
insert into equipes values('BRU', 'LES BRUNS DE BOSTON', 'E', 'BOSTON', 13);
insert into Joueurs values(1, 'PRICE', 'CAREY', 'MTL');
insert into Joueurs values(2, 'MARKOV', 'ANDRÉ', 'MTL');
insert into Joueurs values(3, 'SUBBAN', 'KARL', 'MTL');
insert into Joueurs values(4, 'PATIORETTY', 'MAX', 'MTL');
insert into Joueurs values(10, 'HAMMOND', 'ANDREW', 'OTT');
insert into Joueurs values(6, 'STONE', 'MARC', 'OTT');
insert into Joueurs values(9, 'TURIS', 'KYLE', 'OTT');
insert into Joueurs values(7, 'GALLAGHER', 'BRANDON', 'MTL');
insert into Joueurs values(8, 'TANGUAY', 'ALEX', 'AVL');
insert into Joueurs values(11, 'THOMAS', 'BIL', 'AVL');
insert into Joueurs values(5, 'PATOCHE', 'ALAIN', NULL);
insert into Joueurs values(12, 'POIRIER', 'JUTEUX', NULL);
insert into Matchs values(100, TO_DATE('18-10-30', 'YY/MM/DD'), 'MTL', 'TOR', 3 , 4);
insert into Matchs values(101, TO_DATE('18-11-10', 'YY/MM/DD'), 'TOR', 'MTL', 3 , 3);
insert into Matchs values(102, TO_DATE('18-10-12', 'YY/MM/DD'), 'MTL', 'OTT', 2 , 0);
insert into Matchs values(103, TO_DATE('18-10-20', 'YY/MM/DD'), 'OTT', 'MTL', 0 , 1);
insert into Matchs values(104, TO_DATE('18-11-30', 'YY/MM/DD'), 'MTL', 'AVL', 3 , 4);
insert into Matchs values(105, TO_DATE('18-11-10', 'YY/MM/DD'), 'AVL', 'MTL', 0 , 0);
insert into Matchs values(106, TO_DATE('18-12-12', 'YY/MM/DD'), 'MTL', 'VAN', 2 , 0);
insert into Matchs values(107, TO_DATE('18-03-17', 'YY/MM/DD'), 'VAN', 'MTL', 3 , 1);
insert into Matchs values(108, TO_DATE('18-11-30', 'YY/MM/DD'), 'OTT', 'VAN', 0 , 0);
insert into Matchs values(109, TO_DATE('18-11-10', 'YY/MM/DD'), 'OTT', 'TOR', 0 , 4);
insert into Matchs values(114, TO_DATE('18-10-30', 'YY/MM/DD'), 'BRU', 'TOR', 3 , 4);
insert into Matchs values(115, TO_DATE('19-02-15', 'YY/MM/DD'), 'AVL', 'TOR', null , null);
insert into Matchs values(120, TO_DATE('18-02-26', 'YY/MM/DD'), 'MTL', 'AVL', null , null);
insert into Matchs values(121, TO_DATE('19-02-20', 'YY/MM/DD'), 'MTL', 'OTT', null , null);
Insert into statistiques values(100,3,2,2);
Insert into statistiques values(100,7,1,1);
Insert into statistiques values(101,3,1,0);
Insert into statistiques values(101,7,0,1);
Insert into statistiques values(101,4,1,2);
Insert into statistiques values(101,2,1,2);
Insert into statistiques values(100,4,0,2);
Insert into statistiques values(102,3,1,1);
Insert into statistiques values(102,7,1,2);
Insert into statistiques values(102,9,0,1);
Insert into statistiques values(106,4,1,1);
Insert into statistiques values(106,3,0,2);
Insert into statistiques values(106,2,1,0);
Insert into statistiques values(100,1,null,null);
Insert into statistiques values(101,1,null,null);
Insert into statistiques values(103,1,null,null);
Insert into statistiques values(102,1,null,null);
I've started with this to get the winning teams
select *
from
(select v.teamcode, count(m.codeVisitingTeam) as WonMatches
from matchs m
join teams v on v.teamCode = m.codeVisitingTeam
where m.scoreVisitingTeam > m.scoreReceivingTeam
group by v.teamCode
union all
select r.codeequipe, count(m.codeequiper) as WonMatches
from matchs m
join teams r on r.teamCode = m.codeReceivingTeam
where m.scoreReceivingTeam > m.scoreVisitingTeam
group by r.teamCode));
The only problem with the code above is that it returns twice the team 'MTL' as so :
VAN 1
MTL 2
AVL 1
TOR 3
MTL 1
So I was having a bit of fun with your query and did a bit more than you asked. I wrote the following query to calculated the full complement of wins, losses, and ties. I then ordered the results by points (3 points for a win and 1 for a draw). I hope this helps you a bit:
SELECT *
FROM (SELECT TeamCode,
CASE
WHEN (team = 'VISTING' AND scoreVisitingTeam > SCORERECEIVINGTEAM) OR (team = 'RECEIVING' AND SCORERECEIVINGTEAM > SCOREVISITINGTEAM) THEN 'WIN'
WHEN (team = 'VISTING' AND scoreVisitingTeam < SCORERECEIVINGTEAM) OR (team = 'RECEIVING' AND SCORERECEIVINGTEAM < SCOREVISITINGTEAM) THEN 'LOSS'
ELSE 'DRAW'
END AS RESULT
FROM matchs
UNPIVOT (TeamCode FOR Team IN (CodeVisitingTeam AS 'VISTING', CodeReceivingTeam AS 'RECEIVING')))
PIVOT(COUNT(*) FOR RESULT IN ('WIN' AS WINS, 'LOSS' AS LOSSES, 'DRAW' AS DRAWS))
ORDER BY (wins*3)+draws DESC;
If you have questions, please let me know.
I also created a SQLFiddle. (Link) Note: I removed your constraints from the SQLFiddle. They were throwing errors and I didn't feel like debugging it.
You can do it in a single query with conditional aggregation:
select e.teamCode,
sum(
case
when (e.teamCode = m.codeReceivingTeam and m.scoreReceivingTeam > m.scoreVisitingTeam)
or (e.teamCode = m.codeVisitingTeam and m.scoreReceivingTeam < m.scoreVisitingTeam) then 2
when m.scoreReceivingTeam = m.scoreVisitingTeam then 1
else 0
end
) total_points
from equipes e inner join matchs m
on e.teamCode in (m.codeReceivingTeam, m.codeVisitingTeam)
group by e.teamCode

I'm trying to add data which have same value in sql. How can I do that?

CREATE TABLE DON
(
REGI_NUM INTEGER NOT NULL UNIQUE,
MAKE VARCHAR(20) NOT NULL,
MODEL VARCHAR(20) NOT NULL,
TYPE VARCHAR(20) NOT NULL,
CATEGORY VARCHAR(20) NOT NULL,
DAILY_RENTAL_RATE INTEGER NOT NULL,
PRIMARY KEY(REGI_NUM)
);
INSERT INTO CAR
VALUES (**389238**,'TOYOTA','FJ cruise','sedan','luxury',49);
In this data and following data have same REGI_NUM. when I add them in tera term VT, it said unique constraint violated. How can I add them?
INSERT INTO CAR
VALUES (**389238**, 'MITSUBISHI', 'cruise', 'hatchback', 'luxury', 67);
INSERT INTO CAR
VALUES (326372, 'TOYOTA', 'MDX', 'sedan', 'normal', 20);
INSERT INTO CAR
VALUES (324244, 'Acura', 'FJ cruise', 'SUV', 'luxury', 57);
INSERT INTO CAR
VALUES (124345, 'Acura', 'TL 4dr', 'sedan', 'normal', 23);
INSERT INTO CAR
VALUES (326372, 'Aucara', 'D345', 'sedan', 'luxury', 49);
INSERT INTO CAR
VALUES (389238, 'TOYOTA', 'FJ cruise', 'sedan', 'normal', 24);
INSERT INTO CAR
VALUES (324244, 'Honda', 'odyseey', 'sedan', 'luxury', 57);
Update
Sorry it needs to be like this:
CREATE TABLE DON
(REGI_NUM INTEGER NOT NULL,
MAKE VARCHAR(20) NOT NULL,
MODEL VARCHAR(20) NOT NULL,
TYPE VARCHAR(20) NOT NULL,
CATEGORY VARCHAR(20) NOT NULL,
DAILY_RENTAL_RATE INTEGER NOT NULL,
PRIMARY KEY(REGI_NUM));
INSERT INTO CAR
VALUES (389238,'TOYOTA','FJ cruise','sedan','luxury',49);
INSERT INTO CAR
VALUES (389238,'MITSUBISHI','cruise','hatchback','luxury',67);
INSERT INTO CAR
VALUES (326372,'TOYOTA','MDX','sedan','normal',20);
INSERT INTO CAR
VALUES (324244,'Acura','FJ cruise','SUV','luxury',57);
INSERT INTO CAR
VALUES (124345,'Acura','TL 4dr','sedan','normal',23);
INSERT INTO CAR
VALUES (326372,'Aucara','D345','sedan','luxury',49);
INSERT INTO CAR
VALUES (389238,'TOYOTA','FJ cruise','sedan','normal',24);
INSERT INTO CAR
VALUES (324244,'Honda','odyseey','sedan','luxury',57);
PRIMARY KEY(REGI_NUM))
Since REGI_NUM is the primary key every entry for that column should be unique and not null.
If you want to repeat values, create a table without a primary key on REGI_NUM and add another column to have unique/not null values for primary key if there is a purpose.

SQL Developer - Integrity Constraint , parent key not found ( while inserting values )

I know that in order to insert values in a table which relies on foreign keys you need to have data in that primary key of that table .
These are my constraints :
ALTER TABLE DIDACT
MODIFY (CONSTRAINT id_prof_fk FOREIGN KEY(id_prof) REFERENCES profs (id_prof));
ALTER TABLE DIDACT
MODIFY (CONSTRAINT id_course_fk FOREIGN KEY(id_course) REFERENCES courses (id_course));
Next I insert values in both profs and courses tables :
INSERT INTO courses VALUES ('21', 'Logic', 1, 1, 5);
INSERT INTO courses VALUES ('22', 'Math', 1, 1, 4);
INSERT INTO courses VALUES ('23', 'OOP', 1, 2, 5);
INSERT INTO courses VALUES ('24', 'DB', 2, 1, 8);
INSERT INTO courses VALUES ('25', 'Java', 2, 2, 5);
INSERT INTO profs VALUES ('p1', 'Mary', 'Banks', 'Prof');
INSERT INTO profs VALUES ('p2', 'Francis', 'Steven', 'Conf');
INSERT INTO profs VALUES ('p3', 'John', 'Jobs', 'Prof');
INSERT INTO profs VALUES ('p4', 'Alex', 'Brown', 'Prof');
INSERT INTO profs VALUES ('p5', 'Dan', 'Lovelace', 'Lect');
INSERT INTO profs VALUES ('p6', 'Roxanne', 'Smith', 'Conf');
Then I'm trying to populate the DIDACT table:
INSERT INTO didact VALUES ('p1','21');
INSERT INTO didact VALUES ('p3','21');
INSERT INTO didact VALUES ('p5','22');
But this occurs :
INSERT INTO didact VALUES ('p1','21') Error report - SQL Error:
ORA-02291: integrity constraint (user.ID_COURSE_FK) violated - parent
key not found
02291. 00000 - "integrity constraint (%s.%s) violated - parent key not found"
*Cause: A foreign key value has no matching primary key value.
*Action: Delete the foreign key or add a matching primary key.
These are my tables , in case it will help :
CREATE TABLE courses(
id_course CHAR(2),
course_name VARCHAR2(15),
year NUMBER(1),
semester NUMBER(1),
credits NUMBER(2)
)
CREATE TABLE profs(
id_prof CHAR(4),
name CHAR(10),
surname CHAR(10),
grade VARCHAR2(5)
)
CREATE TABLE didact(
id_prof CHAR(4),
id_course CHAR(4)
)
I'm struggling with this for about an hour and I still haven't managed to find my mistake.
Thank you.
You seem to have different formats for id_course in your tables. In didact it's id_course CHAR(4) and in courses it's id_course CHAR(2).
And since you use a fixed-length type the value in didact will differ from the one in courses by two added blanks.

Microsoft SQL Server

So I'm working on a SQL and I keep getting errors and I have triple checked it and still haven't come up with a reason as to why the queries aren't showing up correctly. I'm using Microsoft SQL Server. These are the errors that I'm currently getting:
Msg 1767, Level 16, State 0, Line 2
Foreign key 'FK_PatientID' references invalid table 'Patient'.
Msg 1750, Level 16, State 0, Line 2
Could not create constraint. See previous errors.
Msg 208, Level 16, State 1, Line 2
Invalid object name 'TreatmentDetails'.
Code:
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'Hospital')
DROP DATABASE [Hospital]
GO
CREATE DATABASE [Hospital]
GO
USE Hospital
GO
CREATE TABLE [dbo].[Physician]
(
PhysicianID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
Specialty VARCHAR(30) NOT NULL,
GraduationDate DATE NOT NULL,
CONSTRAINT [PK_PhysicianID] PRIMARY KEY (PhysicianID)
);
GO
CREATE TABLE [dbo].[TreatmentDetails]
(
TreatmentID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
StartDateTime DATE NOT NULL,
EndDateTime DATE NULL,
Results VARCHAR(30),
CONSTRAINT [PK_TreatmentID] PRIMARY KEY (TreatmentID),
CONSTRAINT [FK_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
CREATE TABLE [dbo].[Patient]
(
PatientID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
DateOfBirth DATE NOT NULL,
CONSTRAINT [PK_PatientID] PRIMARY KEY (PatientID),
);
GO
CREATE TABLE [dbo].[AdmissionDate]
(
AdmissionID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
AdmissionDate DATE NOT NULL,
DischargeDate DATE NULL,
CONSTRAINT [PK_AdmissionID] PRIMARY KEY (AdmissionID),
CONSTRAINT [FK_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
INSERT INTO TreatmentDetails VALUES (1, 12345, 1234, '2014-4-5', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (2, 12346, 1235, '2013-5-6', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (3, 12347, 1236, '2012-7-8', '2014-9-10', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (4, 12348, 1237, '2011-9-10', '2013-11-12', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (5, 12349, 1238, '2010-11-12', NULL, 'NOT DONE')
INSERT INTO Physician VALUES (12345, 'Will', 'Smith', 'Surgeon', '2014-5-9');
INSERT INTO Physician VALUES (12346, 'Jim', 'Carey', 'Pediatrictian', '2013-2-4');
INSERT INTO Physician VALUES (12347, 'Adam', 'Sandler', 'Immunologist', '2012-6-12');
INSERT INTO Physician VALUES (12348, 'Seth', 'Rogan', 'Neurologist', '2010-9-19');
INSERT INTO Physician VALUES (12349, 'James', 'Bond', 'Dermatologist', '2011-5-2');
INSERT INTO Patient VALUES (1234, 'Christopher', 'Thompson', '1989-7-9');
INSERT INTO Patient VALUES (1235, 'Mac', 'Miller', '1970-9-5');
INSERT INTO Patient VALUES (1236, 'Abraham', 'Lincoln', '1988-1-22');
INSERT INTO Patient VALUES (1237, 'George', 'Washington', '1965-2-8');
INSERT INTO Patient VALUES (1238, 'Franklin', 'Roosevelt', '1992-5-19');
INSERT INTO AdmissionDate VALUES (001, 12345, 1234,'2014-2-9', NULL);
INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-15-9');
INSERT INTO AdmissionDate VALUES (003, 12347, 1236,'2014-3-7', '2014-4-9');
INSERT INTO AdmissionDate VALUES (004, 12348, 1237, '2014-8-6', NULL);
INSERT INTO AdmissionDate VALUES (005, 12349, 1238, '2014-5-5', NULL);
GO
USE Hospital
SELECT * FROM Physician
SELECT * FROM Patient
SELECT * FROM AdmissionDate
SELECT * FROM TreatmentDetails
SELECT Patient.PatientID, Patient.FirstName, Patient.LastName, Patient.DateOfBirth, AdmissionDate.AdmissionDate, AdmissionDate.DischargeDate, Physician.Specialty
FROM Patient, AdmissionDate, Physician
WHERE AdmissionDate IS NOT NULL
ORDER BY Patient.LastName, Patient.FirstName, AdmissionDate.AdmissionDate
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NOT NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
You have incorrect order of creating tables.
You are creating foreign keys with same name in different tables.
You are inserting data in tables in incorrect order.
You have provided incorrect date format. Default format is YYYY-MM-DD
and you provide INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-15-9'); 2014-15-9 this is to change.
Here is working script:
USE master
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'Hospital')
DROP DATABASE [Hospital]
GO
CREATE DATABASE [Hospital]
GO
USE Hospital
GO
CREATE TABLE [dbo].[Physician]
(
PhysicianID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
Specialty VARCHAR(30) NOT NULL,
GraduationDate DATE NOT NULL,
CONSTRAINT [PK_PhysicianID] PRIMARY KEY (PhysicianID)
);
GO
CREATE TABLE [dbo].[Patient]
(
PatientID INTEGER NOT NULL,
FirstName VARCHAR(30) NOT NULL,
LastName VARCHAR(30) NOT NULL,
DateOfBirth DATE NOT NULL,
CONSTRAINT [PK_PatientID] PRIMARY KEY (PatientID),
);
GO
CREATE TABLE [dbo].[TreatmentDetails]
(
TreatmentID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
StartDateTime DATE NOT NULL,
EndDateTime DATE NULL,
Results VARCHAR(30),
CONSTRAINT [PK_TreatmentDetails_TreatmentID] PRIMARY KEY (TreatmentID),
CONSTRAINT [FK_TreatmentDetails_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_TreatmentDetails_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
CREATE TABLE [dbo].[AdmissionDate]
(
AdmissionID INTEGER NOT NULL,
PhysicianID INTEGER NOT NULL,
PatientID INTEGER NOT NULL,
AdmissionDate DATE NOT NULL,
DischargeDate DATE NULL,
CONSTRAINT [PK_AdmissionDate_AdmissionID] PRIMARY KEY (AdmissionID),
CONSTRAINT [FK_AdmissionDate_PhysicianID] FOREIGN KEY (PhysicianID) REFERENCES Physician(PhysicianID),
CONSTRAINT [FK_AdmissionDate_PatientID] FOREIGN KEY (PatientID) REFERENCES Patient(PatientID),
);
GO
INSERT INTO Physician VALUES (12345, 'Will', 'Smith', 'Surgeon', '2014-5-9');
INSERT INTO Physician VALUES (12346, 'Jim', 'Carey', 'Pediatrictian', '2013-2-4');
INSERT INTO Physician VALUES (12347, 'Adam', 'Sandler', 'Immunologist', '2012-6-12');
INSERT INTO Physician VALUES (12348, 'Seth', 'Rogan', 'Neurologist', '2010-9-19');
INSERT INTO Physician VALUES (12349, 'James', 'Bond', 'Dermatologist', '2011-5-2');
INSERT INTO Patient VALUES (1234, 'Christopher', 'Thompson', '1989-7-9');
INSERT INTO Patient VALUES (1235, 'Mac', 'Miller', '1970-9-5');
INSERT INTO Patient VALUES (1236, 'Abraham', 'Lincoln', '1988-1-22');
INSERT INTO Patient VALUES (1237, 'George', 'Washington', '1965-2-8');
INSERT INTO Patient VALUES (1238, 'Franklin', 'Roosevelt', '1992-5-19');
INSERT INTO TreatmentDetails VALUES (1, 12345, 1234, '2014-4-5', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (2, 12346, 1235, '2013-5-6', NULL, 'NOT DONE')
INSERT INTO TreatmentDetails VALUES (3, 12347, 1236, '2012-7-8', '2014-9-10', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (4, 12348, 1237, '2011-9-10', '2013-11-12', 'Patient finished')
INSERT INTO TreatmentDetails VALUES (5, 12349, 1238, '2010-11-12', NULL, 'NOT DONE')
INSERT INTO AdmissionDate VALUES (001, 12345, 1234,'2014-2-9', NULL);
INSERT INTO AdmissionDate VALUES (002, 12346, 1235, '2014-12-8', '2014-9-15');
INSERT INTO AdmissionDate VALUES (003, 12347, 1236,'2014-3-7', '2014-4-9');
INSERT INTO AdmissionDate VALUES (004, 12348, 1237, '2014-8-6', NULL);
INSERT INTO AdmissionDate VALUES (005, 12349, 1238, '2014-5-5', NULL);
GO
USE Hospital
SELECT * FROM Physician
SELECT * FROM Patient
SELECT * FROM AdmissionDate
SELECT * FROM TreatmentDetails
SELECT Patient.PatientID, Patient.FirstName, Patient.LastName, Patient.DateOfBirth, AdmissionDate.AdmissionDate, AdmissionDate.DischargeDate, Physician.Specialty
FROM Patient, AdmissionDate, Physician
WHERE AdmissionDate IS NOT NULL
ORDER BY Patient.LastName, Patient.FirstName, AdmissionDate.AdmissionDate
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName
SELECT Physician.PhysicianID, Physician.FirstName, Physician.LastName, Patient.PatientID, Patient.FirstName, Patient.LastName, TreatmentDetails.TreatmentID, TreatmentDetails.StartDateTime, TreatmentDetails.EndDateTime, TreatmentDetails.Results
FROM Physician, Patient, TreatmentDetails
WHERE TreatmentDetails.EndDateTime IS NOT NULL
ORDER BY TreatmentDetails.StartDateTime, Physician.LastName, Patient.LastName