Translate the schema provided in into an “equivalent” relational schema (tables) in SQL - 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.

Related

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 integrity 1-1 or 1-0

I have a question on an exam that i don't know how to solve.
this is the question:
How do you keep the integrity of a 1-1 or 1-0 relationship between 2 tables?
Now a primary key and foreign key wouldn't work because then you can have a 1-m relationship. Maybe you can use unique in some way or alternative key?
We need to give the create table expressions and explain why this would work.
Here's an example of a 1-1 relationship in PostgreSQL. It requires the standard SQL feature of deferrable constraints:
create table employee (
id int primary key not null,
name varchar(20),
desk_id int not null,
constraint uq1 unique (desk_id),
constraint fk1 foreign key (desk_id) references desk (id)
deferrable initially immediate
);
create table desk (
id int primary key not null,
desk_code varchar(20).
employee_id int not null,
constraint uq2 unique (employee_id),
constraint fk2 foreign key (employee_id) references employee (id)
deferrable initially immediate
);
In simple English: every row of employee points to a desk. Every desk points to an employee.
Deferrable constraints are only implemented in PostgreSQL and Oracle, as far as I know.
I am going to give example from oracle
Here is 1:1 relationship example
create table state
(
sid number(3) ,
name varchar2(100),
gid number(3) not null,
constraint state_pk primary key (sid),
constraint gov_state_fk foreign key (gid) references gov(gid)
);
Here is 1:0..1 relationship (a.k.a. Surjection)
create table state
(
sid number(3) ,
name varchar2(100),
gid number(3) ,
constraint state_pk primary key (sid),
constraint gov_state_fk foreign key (gid) references gov(gid)
);
basicly what differs is,
In 1:0 relationship gid can be nullable
In 1:0..1 relationship gid cannot be null
EDIT: I also added Unicity for preserving 1:0..1 and 1:1 relationship.

SQL Server : constraints and foreign keys

I have an assignment where I must
Create an Entity Relationship diagram of a particular situation, and
Write up the SQL code to represent the diagram
I am new to SQL Server, but I have a table class that has a primary key CRN varchar(10)(UNN) and two foreign keys, emp_id varchar(20) (NN) which has a 1 mandatory relationship with instructor, and room_number varchar(5) (UNN) which also has a 1 mandatory relationship with Classroom.
My code for table Class:
CREATE TABLE class
(
CRN varchar(10) UNSIGNED NOT NULL,
emp_id varchar(20),
room_number varchar(5),
enrollment smallint UNSIGNED NOT NULL,
CONSTRAINT pk_class PRIMARY KEY (CRN),
CONSTRAINT fk_class
FOREIGN KEY (emp_id) REFERENCES instructor (emp_id),
CONSTRAINT fk_class
FOREIGN KEY (room_number) REFERENCES classroom (room_number)
);
The error I'm getting is:
Constraint "FK_CLASS" already exists; SQL statement:
CREATE TABLE class
(CRN varchar(10) UNSIGNED NOT NULL,
emp_id varchar(20),
room_number varchar(5),
enrollment smallint UNSIGNED NOT NULL,
CONSTRAINT pk_class PRIMARY KEY (CRN),
CONSTRAINT fk_class FOREIGN KEY (emp_id) REFERENCES instructor (emp_id),
CONSTRAINT fk_class FOREIGN KEY (room_number) REFERENCES classroom (room_number) ) [90045-193]
I have seen many different examples on how to make a table have two foreign keys, but have had no luck. What am I doing wrong?
Contraints must have a unique name, and you are using name fk_class twice. So naming the one fk_instructor and the other fk_classroom should solve the problem.
Note that there is a shorter notation, which avoids such issues:
CREATE TABLE class (
CRN varchar(10) PRIMARY KEY,
emp_id varchar(20) references instructor (emp_id),
room_number varchar(5) REFERENCES classroom (room_number),
enrollment smallint UNSIGNED NOT NULL
);

Recursive relationship SQL error

I am pretty new to SQL and I have a problem. I want to make a recursive relationship (a table that relates to itself), but I get an error when I try to execute my code. It's working fine without the Coordinator_Office_ID foreign key.
The error is:
The number of columns in the foreign-key referencing list is not equal
to the number of columns in the referenced list.
Create table Logistican (
Office_ID Number(10) Constraint nb_office Not NULL,
Worker_ID Number(15) Constraint lg_worker not null,
Name_logistican Varchar(20),
Room Varchar(10) constraint log_room UNIQUE,
Coordinator_Office_ID Integer,
Primary key (Office_ID, Worker_ID),
Constraint work_id Foreign key (Worker_ID) References worker(worker_ID) on delete cascade,
Constraint lg_cord_id Foreign key (Coordinator_Office_ID) References Logistican(Office_ID)
);
Yes, that's cause you have defined composite primary key like Primary key (Office_ID, Worker_ID) and thus your FK should include both of them else it will result in PFD (partial functional dependency)
Add the constraint with alter table:
Create table Logistican (
Office_ID Number(10) Constraint nb_office Not NULL,
Worker_ID Number(15) Constraint lg_worker not null,
Name_logistican Varchar(20),
Room Varchar(10) constraint log_room UNIQUE,
Coordinator_Office_ID Integer,
Primary key (Office_ID, Worker_ID),
Constraint work_id Foreign key (Worker_ID) References worker(worker_ID) on delete cascade
);
alter table Logistican
add Constraint lg_cord_id
Foreign key (Coordinator_Office_ID, Worker_Id) References Logistican(Office_ID, Worker_Id);
The relationship needs all elements of the primary key to be valid. I'm not sure if it needs to be a separate statement in Oracle.

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