SQL: check constraint and on delete clauses - sql

I created two tables below:
CREATE TABLE Horse (
ID SMALLINT UNSIGNED AUTO_INCREMENT,
RegisteredName VARCHAR(15),
PRIMARY KEY (ID))
CREATE TABLE Student (
ID SMALLINT UNSIGNED AUTO_INCREMENT,
FirstName VARCHAR(20),
LastName VARCHAR(30),
PRIMARY KEY (ID))
For the third table, I want it to meet the following requirements:
1.HorseID - integer with range 0 to 65 thousand, not NULL, partial primary key, foreign key references Horse(ID)
2.StudentID - integer with range 0 to 65 thousand, foreign key references Student(ID)
3.LessonDateTime - date/time, not NULL, partial primary key
4.If a row is deleted from Horse, the rows with the same horse ID should be deleted from LessonSchedule automatically.
5.If a row is deleted from Student, the same student IDs should be set to NULL in LessonSchedule automatically.
Here is the query:
(For some reason, I was not able to put the codes below in a code block.)
CREATE TABLE LessonSchedule (
HorseID SMALLINT UNSIGNED NOT NULL CHECK(HorseID BETWEEN 0 AND 65000),
StudentID SMALLINT UNSIGNED CHECK(StudentID BETWEEN 0 AND 65000),
LessonDateTime DATETIME NOT NULL,
PRIMARY KEY (HorseID, LessonDateTime),
FOREIGN KEY(HorseID) REFERENCES Horse(ID) ON DELETE CASCADE,
FOREIGN KEY(StudentID) REFERENCES Student(ID) ON DELETE SET NULL)
I got an erroe message: Column 'StudentID' cannot be used in a check
constraint 'lessonschedule_chk_2': needed in a foreign key constraint
'lessonschedule_ibfk_2' referential action.
Here are my questions:
Based on the error message, can anyone tells me what my query went wrong?
Did I do it right putting the two ON DELETE clauses at the end of the two foreign key statements?

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 )

Column exist but program don t see? [duplicate]

This question already has answers here:
SQLite Foreign Key
(5 answers)
Closed 1 year ago.
I created a 3 tables but in the last one shows errors
CREATE TABLE Student
(
St_Id char(7) PRIMARY KEY,
St_Fname varchar(15) NOT NULL,
St_Lname varchar(20) NOT NULL,
St_DOB date
)
CREATE TABLE Course
(
Course_code char(5) PRIMARY KEY,
Course_title varchar(30) NOT NULL,
Course_credit INTEGER NOT NULL
)
CREATE TABLE Registration
(
Reg_no INTEGER PRIMARY KEY AUTOINCREMENT ,
FOREIGN KEY (St_Id) REFERENCES Student(St_Id),
FOREIGN KEY (Course_code) REFERENCES Course(Course_code),
Mark_obtaines INTEGER
)
and error is
Execution finished with errors. Result: unknown column "St_Id" in
foreign key definition At line 1: CREATE TABLE Registration ( Reg_no
INTEGER PRIMARY KEY AUTOINCREMENT , FOREIGN KEY (St_Id) REFERENCES
Student(St_Id),
In order to define a foreign key, you need to define the column first -- and the types need to match the type in the referenced table:
CREATE TABLE Registration (
Reg_no INTEGER PRIMARY KEY AUTOINCREMENT,
St_Id CHAR(7),
Course_Code CHAR(5),
FOREIGN KEY (St_Id) REFERENCES Student(St_Id),
FOREIGN KEY (Course_code) REFERENCES Course(Course_code),
Mark_obtaines INTEGER
);
Then the FOREIGN KEY declaration provides more information about the column.

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

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

Error when setting foreign key in SQL Server

I have the following queries that I run to create tables in MS SQL Server:
CREATE TABLE menus
(
menu_id int NOT NULL PRIMARY KEY,
menu_name char,
other_details char
)
CREATE TABLE bookings
(
booking_Id int NOT NULL PRIMARY KEY,
date_booked DATE,
date_of_booking DATE,
other_details char,
staff_id int FOREIGN KEY REFERENCES staff(staff_id),
customer_id int FOREIGN KEY REFERENCES customers(customer_id)
)
CREATE TABLE menus_booked
(
menu_id INT NOT NULL,
booking_id INT NOT NULL,
CONSTRAINT PK_menus_booked PRIMARY KEY(menu_id,booking_id),
FOREIGN KEY (menu_id) REFERENCES menus(menu_id),
FOREIGN KEY (booking_id) REFERENCES bookings(booking_id)
)
CREATE TABLE menu_changes
(
change_id int NOT NULL PRIMARY KEY,
menu_id int NOT NULL,
booking_id int NOT NULL,
change_details char,
FOREIGN KEY (menu_id) REFERENCES menus_booked(menu_id),
FOREIGN KEY (booking_id) REFERENCES menus_booked(booking_id)
)
On running the last query I get the error:
There are no primary or candidate keys in the referenced table 'menus_booked' that match the referencing column list in the foreign key 'FK_menu_chan_menu'
I am unsure if my queries are correct and can't resolve this error.
The primary key of menus_booked is a unique combination of menu_id and booking_id. A foreign must point to that combination, not just one of its fields, which is not necessarily unique. Your query currently tries to define two foreign keys, one on each column, instead of one foreign key on the combination of the columns:
CREATE TABLE menu_changes
(
change_id int NOT NULL PRIMARY KEY,
menu_id int NOT NULL,
booking_id int NOT NULL,
change_details char,
FOREIGN KEY (menu_id, booking_id)
REFERENCES menus_booked(menu_id, booking_id) -- Here!
)
A foreign key has to reference a primary key (or unique key but here the PK is the problem), and it has to reference it in it's entirety.
FOREIGN KEY (menu_id) REFERENCES menus_booked(menu_id),
FOREIGN KEY (booking_id) REFERENCES menus_booked(booking_id)
You have two foreign key's referencing part of the primary key of menus_booked. You'll have to alter it to:
FOREIGN KEY (menu_id, booking_id) REFERENCES menus_booked(menu_id, booking_id)