0% found this document useful (0 votes)
18 views23 pages

521 HW3

Uploaded by

namanwho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views23 pages

521 HW3

Uploaded by

namanwho
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

ADBMS HW3

Naman Sreyas Goda 65765962 11/22/2024

CREATING TABLES AND INSERTING VALUES:


Table 1 : takes
create table takes (
ID varchar(5),
course_id varchar(8),
sec_id varchar(8),
semester varchar(6),
year numeric(4,0),
grade varchar(2),
primary key (ID, course_id, sec_id, semester, year) ,
foreign key (ID) references student,
foreign key (course_id, sec_id, semester, year) references section);

INSERT INTO takes (ID, course_id, sec_id, semester, year, grade) VALUES
('00128', 'CS-101', '1', 'Fall', 2017, 'A'),
('00128', 'CS-347', '1', 'Fall', 2017, 'A'),
('12345', 'CS-101', '1', 'Fall', 2017, 'C'),
('12345', 'CS-190', '2', 'Spring', 2017, 'A'),
('12345', 'CS-315', '1', 'Spring', 2018, 'A'),
('12345', 'CS-347', '1', 'Fall', 2017, 'A'),
('19991', 'HIS-351', '1', 'Spring', 2018, 'B'),
('23121', 'FIN-201', '1', 'Spring', 2018, 'C+'),
('44553', 'PHY-101', '1', 'Fall', 2017, 'B'),
('45678', 'CS-101', '1', 'Fall', 2017, 'F'),
('45678', 'CS-101', '1', 'Spring', 2018, 'B+'),
('45678', 'CS-319', '1', 'Spring', 2018, 'B'),
('54321', 'CS-101', '1', 'Fall', 2017, 'A'),
('54321', 'CS-190', '2', 'Spring', 2017, 'B+'),
('55739', 'MU-199', '1', 'Spring', 2018, 'A'),
('76543', 'CS-101', '1', 'Fall', 2017, 'A'),
('76543', 'CS-319', '2', 'Spring', 2018, 'A'),
('76653', 'EE-181', '1', 'Spring', 2017, 'C'),
('98765', 'CS-101', '1', 'Fall', 2017, 'C'),
('98765', 'CS-315', '1', 'Spring', 2018, 'B'),
('98988', 'BIO-101', '1', 'Summer', 2017, 'A'),
('98988', 'BIO-301', '1', 'Summer', 2018, NULL);
Table 2 : PREREQ

CREATE table prereq (


course_id varchar(8), prereq_id varchar(8),
primary key(course_id, prereq_id),
foreign key(course_id) references course on delete cascade,
foreign key(prereq_id) references course);

INSERT INTO prereq (course_id, prereq_id) values


('BIO-301', 'BIO-101'),
('BIO-399', 'BIO-101'),
('CS-190', 'CS-101'),
('CS-315', 'CS-101'),
('CS-319', 'CS-101'),
('CS-347', 'CS-101'),
('EE-181', 'PHY-101');
Table 3 : TIMESLOT
CREATE TABLE timeslot (
time_slot_id VARCHAR(4),
day VARCHAR(1) CHECK (day IN ('M', 'T', 'W', 'R', 'F', 'S', 'U')),
start_time TIME, end_time TIME,
PRIMARY KEY (time_slot_id, day, start_time));

INSERT INTO timeslot (time_slot_id, day, start_time, end_time)


VALUES
('A', 'M', '08:00', '08:50'),
('A', 'W', '08:00', '08:50'),
('A', 'F', '08:00', '08:50'),
('B', 'M', '09:00', '09:50'),
('B', 'W', '09:00', '09:50'),
('B', 'F', '09:00', '09:50'),
('C', 'M', '11:00', '11:50'),
('C', 'W', '11:00', '11:50'),
('C', 'F', '11:00', '11:50'),
('D', 'M', '13:00', '13:50'),
('D', 'W', '13:00', '13:50'),
('D', 'F', '13:00', '13:50'),
('E', 'T', '10:30', '11:45'),
('E', 'R', '10:30', '11:45'),
('F', 'T', '14:30', '15:45'),
('F', 'R', '14:30', '15:45'),
('G', 'M', '16:00', '16:50'),
('G', 'W', '16:00', '16:50'),
('G', 'F', '16:00', '16:50'),
('H', 'W', '10:00', '12:30');
Queries

Basic Queries
1. Selecting Attributes:
Select specific attributes from a table.
SELECT dept_name from instructor

• Find the department names of all instructors, and remove duplicates


select distinct dept_name from instructor
• Select Clause with arithmatic operations
select ID, name, salary/12 as monthly_salary from instructor

• From and Where clause


select name from instructor where dept_name = 'Comp. Sci.'

• From and Where clause with comparisions (>)


select name from instructor where dept_name = 'Comp. Sci.' and salary > 70000
• From and Where clause with comparision (=)
select name, course_id from instructor , teaches where instructor.ID = teaches.ID

• From and Where clause with comparision with and operator


select name, course_id from instructor , teaches where instructor.ID = teaches.ID and instructor.
dept_name = 'Art'

2.String operations
select name from instructor where name like '%dar%'
3.Ordering the results
select distinct name from instructor order by name desc;

• Where Clause Predicates


select name from instructor where salary between 90000 and 100000

• Tuple Comparision :
select name, course_id from instructor, teaches where (instructor.ID, dept_name) = (teaches.ID,
'Biology');

4. Aggregate functions
• Find the average salary of instructors in the Computer Science department
select avg (salary) from instructor where dept_name= 'Comp. Sci.';

• Find the total number of instructors who teach a course in the Spring 2018 semester
select count (distinct ID) from teaches where semester = 'Spring' and year = 2018;
Direct tuple conversion is actually not supported by SQL server

• Find the number of tuples in the course relation


select count (*) from course;
• Find the average salary of instructors in each department
select dept_name, avg (salary) as avg_salary from instructor group by dept_name;

• Find the names and average salaries of all departments whose average salary is greater than 42000
select dept_name, avg (salary) as avg_salary from instructor group by dept_name having avg (salary) >
42000;

Set Operations
• Find courses that ran in Fall 2017 or in Spring 2018
(select course_id from section where sem = 'Fall' and year = 2017) union (select course_id from section
where sem = 'Spring' and year = 2018)

• Find courses that ran in Fall 2017 and in Spring 2018


(select course_id from section where sem = 'Fall' and year = 2017) intersect (select course_id from
section where sem = 'Spring' and year = 2018)
• Find courses that ran in Fall 2017 but not in Spring 2018
(select course_id from section where sem = 'Fall' and year = 2017) except (select course_id from section
where sem = 'Spring' and year = 2018)

• Find all instructors whose salary is null.


select name from instructor where salary is null

Set Membership
• Find courses offered in Fall 2017 and in Spring 2018
select distinct course_id from section where semester = 'Fall' and year= 2017 and course_id in (select
course_id from section where semester = 'Spring' and year= 2018);

• Find courses offered in Fall 2017 but not in Spring 2018


select distinct course_id from section where semester = 'Fall' and year= 2017 and course_id not in (select
course_id from section where semester = 'Spring' and year= 2018);

• Name all instructors whose name is neither “Mozart” nor Einstein” select distinct name from
instructor where name not in ('Mozart', 'Einstein'):
• Find the total number of (distinct) students who have taken course sections taught by the instructor
with ID 10101
select count (distinct ID) from takes where (course_id, sec_id, semester, year) in (select course_id,
sec_id, semester, year from teaches where teaches.ID= 10101);
Direct tuple conversion is actually not supported by SQL server

Set Comaprision:
Find names of instructors with salary greater than that of some (at least one) instructor in the Biology
department.:
select distinct T.name
from instructor as T, instructor as S
where T.salary > S.salary and S.dept_name = 'Biology';

Same query using > some clause:


select name
from instructor
where salary > some (select salary
from instructor
where dept name = 'Biology');

• All clause;
Find the names of all instructors whose salary is greater than the salary of all instructors in the
Biology department
select name
from instructor
where salary > all (select salary
from instructor
where dept_name = 'Biology');

• Use of “exists” Clause;


Yet another way of specifying the query “Find all courses taught in both the Fall 2017 semester and in
the Spring 2018 semester”
select course_id
from section as S
where semester = 'Fall' and course_year = 2017 and
exists (select *
from section as T
where semester = 'Spring' and course_year= 2018
and S.course_id = T.course_id);

• Use of “not exists” Clause


Find all students who have taken all courses offered in the Biology department:
select distinct S.ID, S.std_name
from student as S
where not exists ( (select course_id
from course
where dept_name = 'Biology')
except
(select T.course_id
from takes as T
where S.ID = T.ID));

Test for absence of Duplicate Tuples


Find all courses that were offered at most once in 2017
select T.course_id
from course as T
where unique ( select R.course_id
from section as R
where T.course_id= R.course_id
and R.course_year = 2017);

*error in SQL server of Microsoft


From Clause
SELECT dept_name, avg_salary
FROM (
SELECT dept_name, AVG(salary) AS avg_salary
FROM instructor
GROUP BY dept_name) AS dept_avg_salaries
WHERE avg_salary > 42000;

With Clause:
Find all departments with the maximum budget
with max_budget (value) as
(select max(budget)
from department)
select department.dept_name
from department, max_budget
where department.budget = max_budget.value;

Complex Queries using With Clause


Find all departments where the total salary is greater than the average of the total salary at all
departments:

Scalar subquery
select dept_name,
( select count(*) from instructor
where department.dept_name = instructor.dept_name)
as num_instructors
from department;
Data Modifications
Insert and Delete
• delete from instructor
• delete from instructor where dept_name = 'Finance';
• delete from instructor
where dept_name in (select dept_name from department where building = 'Watson');
• delete from instructor where salary < (select avg (salary) from instructor);
• insert into course values ('CS-437', 'Database Systems', 'Comp. Sci.', 4);
• insert into student values ('3003', 'Green', 'Finance', null);
• insert into instructor select ID, name, dept_name, 18000 from student where dept_name =
'Music' and total_cred > 144;
The above queries couldnot be executed because they conflict with the foreign key constraints
Update
• update instructor set salary = salary * 1.05

• update instructor set salary = salary * 1.05 where salary < 70000;
• update instructor
set salary = case
when salary <= 100000 then salary * 1.05
else salary * 1.03
end

• UPDATE student
SET tot_cred = (
SELECT
CASE
WHEN SUM(course.credits) IS NOT NULL THEN SUM(course.credits)
ELSE 0
END
FROM takes
INNER JOIN course ON takes.course_id = course.course_id
WHERE takes.ID = student.ID
AND takes.grade <> 'F'
AND takes.grade IS NOT NULL
);

Join Operations
• Natural Join in SQL:
select std_name, course_id
from student, takes
where student.ID = takes.ID;

• Right Outer Join:


SELECT course.course_id,
course.title,
course.dept_name,
course.credits,
prereq.prereq_id
FROM course
RIGHT OUTER JOIN prereq
ON course.course_id = prereq.course_id;

• Left Outer Join:


SELECT course.course_id,
course.title,
course.dept_name,
course.credits,
prereq.prereq_id
FROM course
LEFT OUTER JOIN prereq
ON course.course_id = prereq.course_id;

• Full Outer Join:


SELECT course.course_id,
course.title,
course.dept_name,
course.credits,
prereq.prereq_id
FROM course
FULL OUTER JOIN prereq
ON course.course_id = prereq.course_id;
• Inner Join:
SELECT course.course_id,
course.title,
course.dept_name,
course.credits,
prereq.prereq_id
FROM course
INNER JOIN prereq
ON course.course_id = prereq.course_id;

View operations
• Create a view :
GO
CREATE VIEW faculty
AS
SELECT ID, name, dept_name
FROM instructor;
GO
• Using views
Find all instructors in the Biology department
select name from faculty where dept_name = 'Biology'

• view of department salary totals


create view departments_total_salary(dept_name, total_salary)
as
select dept_name, sum (salary)
from instructor
group by dept_name;

• Views Defined Using Other Views


create view physics_fall_2017
as
select course.course_id, sec_id, building, room_number
from course, section
where course.course_id = section.course_id
and course.dept_name = 'Physics'
and section.semester = 'Fall'
and section.course_year = '2017';

create view physics_fall_2017_watson


as
select course_id, room_number
from physics_fall_2017
where building= 'Watson';

• View Expansion
DROP VIEW IF EXISTS physics_fall_2017_watson;
GO
create view physics_fall_2017_watson
as
select course_id, room_number
from physics_fall_2017
where building= 'Watson'
GO

DROP VIEW IF EXISTS physics_fall_2017_watson;


GO
create view physics_fall_2017_watson as
select course_id, room_number
from (select course.course_id, building, room_number
from course, section
where course.course_id = section.course_id
and course.dept_name = 'Physics'
and section.semester = 'Fall'
and section.course_year = '2017')
where building= 'Watson';

• Update of view
insert into faculty values ('30765', 'Green', 'Music');

create view instructor_info as


select ID, name, building
from instructor, department
where instructor.dept_name= department.dept_name;

insert into instructor_info


values ('69987', 'White', 'Taylor');

Integrity constraints
Create Table takes (
ID VARCHAR(5) NOT NULL,
course_id VARCHAR(8) NOT NULL,
sec_id VARCHAR(8) NOT NULL,
semester VARCHAR(6) NOT NULL,
course_year NUMERIC(4, 0) NOT NULL,
grade VARCHAR(2) CHECK (grade IN ('A', 'B', 'C', 'D', 'F')) DEFAULT 'F',
PRIMARY KEY (ID, course_id, sec_id, semester, course_year),
FOREIGN KEY (course_id, sec_id, semester, course_year)
REFERENCES section(course_id, sec_id, semester, course_year)
ON DELETE CASCADE,
FOREIGN KEY (ID)
REFERENCES student(ID)
ON DELETE CASCADE, CHECK (semester IN ('Fall', 'Winter', 'Spring', 'Summer')),
);
User Defined Types
Create :
CREATE TYPE Dollars FROM NUMERIC(12, 2) NOT NULL;

Using UDT :
create table department_test
(dept_name varchar (20),
building varchar (15),
budget Dollars);

Domains
• create type person_name from char(20) not null
• create domain degree_level varchar(10) constraint degree_level_test check (value in
('Bachelors', 'Masters', 'Doctorate'))
Create Domain doesn’t work in Microsoft SQL server
Performance and Indexing
I chose to create an index file for Department table.
The below function has randomly inserted a huge number of values into the Department table.
DECLARE @i INT = 1;

WHILE @i <= 100000


BEGIN
INSERT INTO Department (Dept_name, Building, Budget)
VALUES (
'Department_' + CAST(@i AS VARCHAR(10)),
CASE WHEN @i % 5 = 1 THEN 'Taylor'
WHEN @i % 5 = 2 THEN 'Watson'
WHEN @i % 5 = 3 THEN 'Newton'
WHEN @i % 5 = 4 THEN 'Packard'
ELSE 'Painter' END,
RAND() * 100000 + 50000
);

SET @i = @i + 1;
END;

Query On department table Before Index creation:


Set Statistics IO ON;
SELECT Dept_name, Building, Budget
FROM Department
WHERE Building = 'Watson'
AND Budget BETWEEN 60000 AND 120000
ORDER BY Budget ASC;

Performance Before Index Creation:

Index creation: I decided to create a composite index on building and budget.


CREATE INDEX idx_building_budget ON Department (Building, Budget);

Performance After Index creation:

Authorization :
• Create Users
CREATE LOGIN Amit WITH PASSWORD = 'SecurePassword123';
CREATE USER Amit FOR LOGIN Amit;

CREATE LOGIN Satoshi WITH PASSWORD = 'SecurePassword123';


CREATE USER Satoshi FOR LOGIN Satoshi;
CREATE LOGIN U1 WITH PASSWORD = 'SecurePassword123';
CREATE USER U1 FOR LOGIN U1;

CREATE LOGIN U2 WITH PASSWORD = 'SecurePassword123';


CREATE USER U2 FOR LOGIN U2;

CREATE LOGIN Mariano WITH PASSWORD = 'SecurePassword123';


CREATE USER Mariano FOR LOGIN Mariano;

Grant Privileges
GRANT SELECT ON department TO Amit, Satoshi;

GRANT SELECT ON instructor TO U1, U2;

GRANT REFERENCES (dept_name) ON department TO Mariano;

GRANT SELECT ON department TO Amit WITH GRANT OPTION;

Create Role and Assign Users


CREATE ROLE instructor;

ALTER ROLE instructor ADD MEMBER Amit;

Revoke Privileges
REVOKE SELECT ON student FROM U1, U2;

REVOKE ALL ON student FROM U1, U2;


REVOKE SELECT ON department FROM Amit, Satoshi CASCADE;

Authorising views :
CREATE VIEW geo_instructor AS
SELECT *
FROM instructor
WHERE dept_name = 'Geology';

CREATE ROLE geo_staff;

GRANT SELECT ON geo_instructor TO geo_staff;

CREATE LOGIN geo_user WITH PASSWORD = 'SecurePassword123';


CREATE USER geo_user FOR LOGIN geo_user;
ALTER ROLE geo_staff ADD MEMBER geo_user;

GRANT SELECT ON instructor TO geo_user;

You might also like