Constrain number of rows in table, by value in another table - sql

I have a table called ward (dealing with hospitals):
Create table ward(
Wno varchar(15) Primary Key,
Name varchar(20) Not Null,
Number_of_beds integer Not Null
);
And a table for patients:
Create table patient(
Pid varchar(15) Primary Key,
Name varchar(20) Not Null,
Address varchar(50) Not Null,
Date_of_birth date Not Null
);
I need to constrain the patients somehow so that if a patient is assigned to a specific ward then the number of patients can't exceed the number of beds in the ward.
I thought of adding the Wno as a foreign key to the patient table, but don't really know where to go from there.

You may add the foreign key into patient table as following. Apology this query is in MYSQL. I noticed that you need Oracle though. However the logic is similar :) The syntax needs changes.
Create table ward(
Wno varchar(15) Not null Primary Key,
Name varchar(20) Not Null,
Number_of_beds integer Not Null
);
And a table for patients:
Create table patient(
Pid varchar(15) Primary Key,
Name varchar(20) Not Null,
Address varchar(50) Not Null,
Date_of_birth date Not Null,
WardNo varchar(15),
foreign key (wardno) references ward (wno) ' -- adds the foreign key relation
);
In order to check if ward is full, you can have an insert or update trigger
Free bed count can be obtained by following query:
SELECT p.wardno, (w.number_of_beds - count(pid)) as freebeds
from patient as p
left join ward as w
on p.wardno = w.wno
group by wardno
Now we create a trigger to check if any patient is going into a ward whre freebed count = 0.
Updated to Oracle Version
CREATE OR REPLACE TRIGGER FreeBedsWardTrigger
BEFORE UPDATE OR INSERT
ON patient
FOR EACH ROW
DECLARE
max_beds INTEGER; -- max number of beds for the ward
used_beds INTEGER; -- used beds for the ward
BEGIN
SELECT COUNT (pid)
INTO used_beds
FROM patient
WHERE wardno = :NEW.wardno;
SELECT number_of_beds
INTO max_beds
FROM ward
WHERE wno = :NEW.wardno;
IF (max_beds - used_beds) > 0
THEN
RETURN;
ELSE
RAISE_APPLICATION_ERROR (-100100,
'No more beds available in this ward.');
END IF;
END;

Related

trigger for not inserting members doesnt work

I have this table
CREATE TABLE members
(
member_id INT PRIMARY KEY NOT NULL,
first_name VARCHAR(20),
last_name VARCHAR(20),
web_page VARCHAR(200),
e_mail VARCHAR(200),
cv VARCHAR(800),
dep_id INT,
teacher_id INT
);
and I want to create a trigger that if someone wants to insert a member which has a dep_id of 1 or 2 or 3.
And the teacher_id is different than NULL (as the teacher_id column is filled with either NULL or an id of another member)
I came up with this
CREATE TRIGGER employee_insup1
ON members
FOR INSERT, UPDATE
AS
DECLARE #dep_id INT, #teacher_id INT
SELECT #dep_id = i.dep_id, #teacher_id = i.teacher_id
FROM inserted i
IF ((#dep_id = 1) AND (#teacher_id != NULL))
BEGIN
RAISERROR('Teacher_id expects NULL',16,1)
ROLLBACK TRANSACTION
END
but after all if I try to insert a member with dep_id 1 and teacher_id 7(for example) it will be registered
You don't need a trigger for this. A check constraint is sufficient:
alter table members add constraint chk_members_dep_teacher
check (dep_id not in (1, 2, 3) or teacher_id is not null);
Specifically, this ensures that when dep_id is in one of those departments, then the teacher_id is not null. You might find the logic easier to follow as:
alter table members add constraint chk_members_dep_teacher
check (not (dep_id nt in (1, 2, 3) and teacher_id is null) );

SQL name error with foreign key in sql code

I am getting ORA-00955 error which is name is already used by an existing object. I know it is in the foreign key constraint im trying to use. It happens in both foreign key constraints. I cant figure out why its happening. I tried renaming them to anything possible and I cant understand why it wont work.
DROP TABLE STUDENT;
CREATE TABLE STUDENT
(stuID VARCHAR (7) PRIMARY KEY NOT NULL,
major VARCHAR (15) NOT NULL,
firstName VARCHAR (15) NOT NULL,
lastName VARCHAR (15) NOT NULL,
yr VARCHAR(8) NOT NULL
);
DROP TABLE ENROLL;
CREATE TABLE ENROLL
(stuID VARCHAR (7) NOT NULL,
grade VARCHAR (1) NOT NULL,
courseID VARCHAR(7) NOT NULL,
CONSTRAINT fk_STUDENT
FOREIGN KEY (stuID)
REFERENCES STUDENT(stuid)
);
DROP TABLE CLASS;
CREATE TABLE CLASS
(instructorID VARCHAR(7) NOT NULL,
classRoomNumber VARCHAR(7) NOT NULL,
dateStarts DATE NOT NULL,
courseID VARCHAR(7) PRIMARY KEY NOT NULL,
description CHAR(100) NOT NULL,
CONSTRAINT fk_INSTRUCTOR
FOREIGN KEY (instructorID)
REFERENCES INSTRUCTOR(instructorid)
);
DROP TABLE INSTRUCTOR;
CREATE TABLE INSTRUCTOR
(firstName VARCHAR (15) NOT NULL,
lastName VARCHAR (15) NOT NULL,
departmentName VARCHAR (15) NOT NULL,
instructorID VARCHAR(7) PRIMARY KEY NOT NULL
);
In a comment, you said that there's still an error.
If you create (and/or drop) tables in a correct order, everything is OK. I prefer dropping them separately.
At first, tables don't exist so I'll just create them:
SQL> CREATE TABLE student (
2 stuid VARCHAR(7) PRIMARY KEY NOT NULL,
3 major VARCHAR(15) NOT NULL,
4 firstname VARCHAR(15) NOT NULL,
5 lastname VARCHAR(15) NOT NULL,
6 yr VARCHAR(8) NOT NULL
7 );
Table created.
SQL> CREATE TABLE enroll (
2 stuid VARCHAR(7) NOT NULL,
3 grade VARCHAR(1) NOT NULL,
4 courseid VARCHAR(7) NOT NULL,
5 CONSTRAINT fk_student FOREIGN KEY ( stuid )
6 REFERENCES student ( stuid )
7 );
Table created.
SQL> CREATE TABLE instructor (
2 firstname VARCHAR(15) NOT NULL,
3 lastname VARCHAR(15) NOT NULL,
4 departmentname VARCHAR(15) NOT NULL,
5 instructorid VARCHAR(7) PRIMARY KEY NOT NULL
6 );
Table created.
SQL> CREATE TABLE class (
2 instructorid VARCHAR(7) NOT NULL,
3 classroomnumber VARCHAR(7) NOT NULL,
4 datestarts DATE NOT NULL,
5 courseid VARCHAR(7) PRIMARY KEY NOT NULL,
6 description CHAR(100) NOT NULL,
7 CONSTRAINT fk_instructor FOREIGN KEY ( instructorid )
8 REFERENCES instructor ( instructorid )
9 );
Table created.
Drop tables in reverse order, so that detail is dropped before its master
SQL> DROP TABLE enroll;
Table dropped.
SQL> DROP TABLE student;
Table dropped.
SQL> DROP TABLE class;
Table dropped.
SQL> DROP TABLE instructor;
Table dropped.
SQL>
Table INSTRUCTOR is referenced by table CLASS, hence you heed to create table INSTRUCTOR before you create table CLASS.
Also, you should use DROP TABLE ... CASCADE CONSTRAINTS instead of just DROP TABLE .... This allows foreign and primary keys to be properly dropped at the same time as the table, and might avoid error name already used by existing object that you are currently getting.

SQL Logic and Aggregate Issue

I have the following problem to solve in SQL :
d) A query that provides management information on take up of the various types of activities on offer. For each type of activity, the query should show the total number of individuals who took that type of activity and the average number of individuals taking each type of activity.
Here are my tables :
CREATE TABLE accommodations
(
chalet_number int PRIMARY KEY,
chalet_name varchar(40) NOT NULL,
no_it_sleeps number(2) NOT NULL,
indivppw number(4) NOT NULL
)
CREATE TABLE supervisors
(
supervisor_number int PRIMARY KEY,
supervisor_forename varchar(30) NOT NULL,
supervisor_surname varchar(30) NOT NULL,
mobile_number varchar(11) NOT NULL
)
CREATE TABLE visitors
(
visitor_ID int PRIMARY KEY,
group_ID int NOT NULL,
forename varchar(20) NOT NULL,
surname varchar(20) NOT NULL,
dob date NOT NULL,
gender varchar(1) NOT NULL
)
CREATE TABLE activities
(
activity_code varchar(10) PRIMARY KEY,
activity_title varchar(20) NOT NULL,
"type" varchar(20) NOT NULL
)
CREATE TABLE "groups"
(
group_ID int PRIMARY KEY,
group_leader varchar(20) NOT NULL,
group_name varchar(30)
number_in_group number(2) NOT NULL
)
CREATE TABLE bookings
(
group_ID int NOT NULL,
start_date date NOT NULL,
chalet_number int NOT NULL,
no_in_chalet number(2) NOT NULL,
start_date date NOT NULL,
end_date date NOT NULL,
CONSTRAINT bookings_pk PRIMARY KEY(group_ID, chalet_number));
CREATE TABLE schedule
(
schedule_ID int PRIMARY KEY,
activity_code varchar(10) NOT NULL,
time_of_activity number(4,2) NOT NULL,
am_pm varchar(2) NOT NULL,
"date" date NOT NULL
)
CREATE TABLE activity_bookings
(
visitor_ID int NOT NULL,
schedule_ID int NOT NULL,
supervisor_number int NOT NULL,
comments varchar(200),
CONSTRAINT event_booking_pk PRIMARY KEY(visitor_ID, schedule_ID));
ALTER TABLE visitors
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE Schedule
ADD FOREIGN KEY (activity_code)
REFERENCES activities(activity_code)
ALTER TABLE bookings
ADD FOREIGN KEY (group_ID)
REFERENCES "groups"(group_ID)
ALTER TABLE bookings
ADD FOREIGN KEY (chalet_number)
REFERENCES accommodations(chalet_number)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (visitor_ID)
REFERENCES visitors(visitor_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (schedule_ID)
REFERENCES schedule(schedule_ID)
ALTER TABLE activity_bookings
ADD FOREIGN KEY (supervisor_number)
REFERENCES supervisors(supervisor_number)
I have the following solution:
SELECT activities."type", 'overalltotal' AS OT, ('overalltotal' / 'activities') AS AVG
FROM activities, schedule
WHERE 'overalltotal' = (SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type"
)
AND 'activities' = (SELECT COUNT(DISTINCT activities."type")
FROM activities
)
AND schedule.activity_code = activities.activity_code
GROUP BY activities."type";
I have implemented sample data and code to check the variables above:
SELECT SUM(COUNT(schedule_ID))
FROM activities, schedule
WHERE schedule.activity_code = activities.activity_code
GROUP BY activities."type";
Result : 20
SELECT COUNT(DISTINCT activities."type")
FROM activities;
Result : 5
However when running the code :
ORA-01722: invalid number
01722. 00000 - "invalid number"
*Cause:
*Action:
EDIT:
Using Dave's Code i have the following output:
Snowboarding 15
sledding 19
Snowmobiling 6
Ice Skating 5
Skiing 24
How would i do the final part of the question?
and the average number of individuals taking each type of activity.
You must use double quotes around column names in Oracle, not single quotes. For example, "overalltotal". Single quotes are for text strings, which is why you're getting an invalid number error.
EDIT: This is probably the type of query you want to use:
SELECT activities."type", COUNT(*) AS total, COUNT(*)/(COUNT(*) OVER ()) AS "avg"
FROM activities a
JOIN schedule s ON a.activity_code=s.activity_code
JOIN activity_bookings ab ON s.schedule_ID=ab.schedule_ID
GROUP BY activities."type";
Basically, because each activity booking has one visitor id, we want to get all the activity bookings for each activity. We have to go through schedule to do that. They we group the rows by the activity type and count how many activity bookings we have for each type.

ORA-00900: invalid SQL statement

CREATE TABLE Customers(
CustID number(5,0),
EmpID CHAR(1),
Cust_Name varchar(20) not null,
Cust_Address varchar(20) not null,
Cust_City varchar(20) not null,
Cust_State char(2) not null,
Cust_Zipcode number(5,0) not null,
Ship_Date date not null,
Order_Date date not null,
constraint ci_fk FOREIGN KEY (EmpID) references EMPLOYEES(EmpID),
constraint ci_ck check (Ship_Date>Order_Date)
)
What's the problem?
Employees table does not exist.
or EmpId is not a primary key.
Once I did these, my copy of the create statement worked.
Chris said it.
Change CHAR to VARCHAR2 as CHAR should never be used. Also, number(5,0) is the same as NUMBER(5), so you can use that.
Verify that the Employees table exists.
Verify that the EmpID column in the Employees table is of the same datatype as in the Customers table.
Verify that the EmpID column in the Employees table is the primary key of the employee table.

Creating table with Identity related too other column in table

I'm trying to create a table that has a primary key (Department_ID) that auto assigns(not hard). However the assignment would be based on the exsisting value in another column(Department_Name). So for example if its the department_name payroll the department_ID would be 1 for example. If I tried to insert into and had to add another payroll employee it would not auto increment. It would assign value 1 to it. I assume its constraint I am looking for, but have no idea if I'm looking at this wrong or how to write it. Here's what I have so far:
CREATE TABLE tblDepartment
(
Department_ID int NOT NULL IDENTITY,
Department_Name varchar(255) NOT NULL,
Division_Name varchar(255) NOT NULL,
City varchar(255) default 'sometown' NOT NULL,
Building int default 1 NOT NULL,
Phone varchar(255) NOT NULL,
PRIMARY KEY (Department_ID)NOT NULL,
Check (Building >=1 AND Building <= 10 )
)
CREATE TABLE tblEmployee
(
Employee_ID int NOT NULL IDENTITY,
Department_ID int ,
Employee_Name varchar(255),
Social_Security_Number varchar(255),
Work_Phone varchar(255),
Position varchar(255),
Hire_Date datetime,
Birth_Date datetime,
FOREIGN KEY (Department_ID) REFERENCES tblDepartment(Department_ID)
)
Thanks for the help!
You shouldn't need a Department record per employee. You'll only have one Department record per department. You'll insert the Department.Department_ID value from the corresponding Department record into the Employee.Department_ID field when you insert an Employee record.
An autoincrement field for Department.Department_ID should be fine.
According to your schema, you already have a constraint that enforces this.
A TRIGGER on insert into tblEmployee that reads tblDepartment and sets the key accordingly might be a solution.
What happens if an employee changes department?