0% found this document useful (0 votes)
67 views

P S T U: Atuakhali Cience AND Echnology Niversity

The document contains sample SQL queries and answers for exercises related to various database schemas, including a university schema, insurance database, and banking database. The queries demonstrate how to write SQL statements to retrieve, insert, update, and delete data from tables defined based on the given schemas. Primary keys, foreign keys, joins, and other SQL features are utilized in the queries to solve the different exercises.

Uploaded by

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

P S T U: Atuakhali Cience AND Echnology Niversity

The document contains sample SQL queries and answers for exercises related to various database schemas, including a university schema, insurance database, and banking database. The queries demonstrate how to write SQL statements to retrieve, insert, update, and delete data from tables defined based on the given schemas. Primary keys, foreign keys, joins, and other SQL features are utilized in the queries to solve the different exercises.

Uploaded by

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

PATUAKHALI SCIENCE AND TECHNOLOGY

UNIVERSITY
Faculty of Computer Science and Engineering

Lab Work - 04
Course Title: Database System Sessional
Course Code: CCE-224

Submitted to:
Dr. Md. Samsuzzaman
Professor
Department of Computer and Communication Engineering
Faculty of Computer Science and Engineering
Patuakhali Science and Technology University, Dumki, Patuakhali,
Bangladesh

Submitted by:
Name : Md.Tasnif Rahman
ID : 1802014
Reg : 08424
CHAPTER-03

Solving exercise from 3.11 to 3.35

3.11 Write the following queries in SQL, using the university


schema.

a. Find the names of all students who have taken at least one Comp.
Sci. course; make sure there are no duplicate names in the result.
b. Find the IDs and names of all students who have not taken any
course offering before Spring 2009.
c. For each department, find themaximumsalary of instructors in that
department. Youmay assume that every department has at least one
instructor.
d. Find the lowest, across all departments, of the per-epartmentmaximum
salary computed by the preceding query.
Answer:
a. SQL query:
select name
from student natural join takes natural join course
where course.dept = ’Comp. Sci.’

b. SQL query:
select id, name
from student
except
select id, name
from student natural join takes
where year < 2009
Since the except operator eliminates duplicates, there is
no need
to use a select distinct clause, although doing so would
not affect
correctness of the query.
c. SQL query:
select dept, max(salary)
from instructor
group by dept

d. SQL query:
select min(maxsalary)
from (select dept, max(salary) as maxsalary
from instructor
group by dept)

3.12 Write the following queries in SQL, using the university


schema.
a. Create a new course “CS-001”, titled “Weekly Seminar”, with 0 credits.
b. Create a section of this course in Autumn 2009, with section id of 1.
c. Enroll every student in the Comp. Sci. department in the above
section.
d. Delete enrollments in the above section where the student’s name is
Chavez.
e. Delete the course CS-001. What will happen if you run this delete
statement without first deleting offerings (sections) of this course.
f. Delete all takes tuples corresponding to any section of any course
with the word “database” as a part

Answer:
a. SQL query:
insert into course
values (’CS-001’, ’Weekly Seminar’, ’Comp. Sci.’, 0)

b. SQL query:
insert into section
values (’CS-001’, 1, ’Autumn’, 2009, null, null, null)

Note that the building, roomnumber and slot were not specified in
the question, and we have set them to null. The same effect would
be obtained if they were specified to default to null, and we simply
omitted values for these attributes in the above insert statement.
(Many database systems implicitly set the default value to null, even
if not explicitly specified.)

c. SQL query:
insert into takes
select id, ’CS-001’, 1, ’Autumn’, 2009, null
from student
where dept name = ’Comp. Sci.’

d. SQL query:
delete from takes
where course id= ’CS-001’ and section id = 1 and
year = 2009 and semester = ’Autumn’ and
id in (select id
from student
where name = ’Chavez’)

Note that if there is more than one student named Chavez, all such
students would have their enrollments deleted. If we had used =
instead of in, an error would have resulted if there were more than
one student named Chavez.

e. SQL query:
delete from takes
where course id = ’CS-001’
delete from section
where course id = ’CS-001’
delete from course
where course id = ’CS-001’

If we try to delete the course directly, there will be a foreign key violation
because section has a foriegn key reference to course; similarly,
we have to delete corresponding tuples from takes before deleting
sections, since there is a foreign key reference from takes to section.
As a result of the foreign key violation, the transaction that performs
the delete would be rolled back.
f. SQL query:
delete from takes
where course id in
(select course id
from course
where lower(title) like ’%database%’)

3.13 Write SQL DDL corresponding to the schema in


Figure 3.18. Make any reasonable assumptions about data types,
and be sure to declare primary and foreign keys.

Answer:

a. SQL query:
person (driver id, name, address)
car (license, model, year)
accident (report number, date, location)
owns (driver id, license)
participated (report number, license, driver id, damage
amount)
Figure 3.18 Insurance database for Exercises 3.4 and 3.14.
create table person
(driver id varchar(50),
name varchar(50),
address varchar(50),
primary key (driver id))

b. SQL query:
create table car
(license varchar(50),
model varchar(50),
year integer,
primary key (license))
c. SQL query:
create table accident
(report number integer,
date date,
location varchar(50),
primary key (report number))

d. SQL query:
create table owns
(driver id varchar(50),
license varchar(50),
primary key (driver id,license)
foriegn key (driver id) references person
foriegn key (license) references car)

e. SQL query:
create table participated
(report number integer,
license varchar(50),
driver id varchar(50),
damage amountinteger,
primary key (report number,license)
foriegn key (license) references car
foriegn key (report number) references accident))

3.14 Consider the insurance database of Figure 3.18, where the


primary keys are underlined. Construct the following SQL queries
for this relational database.
a. Find the number of accidents in which the cars belonging to “John
Smith” were involved.
b. Update thedamage amount for the carwith license number “AABB2000”
in the accident with report number “AR2197” to $3000.
Answer:

Note: The participated relation relates drivers, cars, and accidents.

a. SQL query:
select count (*)
from accident
where exists
(select *
from participated, owns, person
where owns.driver id = person.driver id
and person.name = ’John Smith’
and owns.license = participated.license
and accident.report number = participated.report number)

The query can be written in other ways too; for example without a
subquery, by using a join and selecting count( distinct report
number)
to get a count of number of accidents involving the car.

b. SQL query:
update participated
set damage amount = 3000
where report number = “AR2197” and
license = “AABB2000”)

3.15 Consider the bank database of Figure 3.19, where the primary keys
are underlined.
Construct the following SQL queries for this relational database.
branch(branch name, branch city, assets)
customer (customer name, customer street, customer city)
loan (loan number, branch name, amount)
borrower (customer name, loan number)
account (account number, branch name, balance )
depositor (customer name, account number)
Figure 3.19 Banking database for Exercises 3.8 and 3.15.
a. Find all customers who have an account at all the branches located
in “Brooklyn”.
b. Find out the total sum of all loan amounts in the bank.
c. Find the names of all branches that have assets greater than those of
at least one branch located in “Brooklyn”.

Answer:
a. SQL query:
with branchcount as
(select count(*)
branch
where branch city = ’Brooklyn’)
select customer name
from customer c
where branchcount =
(select count(distinct branch name)
from (customer natural join depositor natural join
account
natural join branch) as d
where d.customer name = c.customer name)

There are other ways of writing this query, for example by first
finding customers who do not have an account at some branch
in
Brooklyn, and then removing these customers from the set of
all
customers by using an except clause.
b. SQL query:
select sum(amount)
from loan
c. SQL query:
employee (employee name, street, city)
works (employee name, company name, salary)
company (company name, city)
manages (employee name, manager name)
Figure 3.20 Employee database for Exercises 3.9, 3.10, 3.16, 3.17, and
3.20.
select branch name
from branch
where assets > some
(select assets
from branch
where branch city = ’Brooklyn’)
The keyword any could be used in place of some above.

3.16 Consider the employee database of Figure 3.20,where the primary


keys are underlined. Give an expression in SQL for each of the
following queries.
a. Find the names of all employees who work for First Bank
Corporation.
b. Find all employees in the database who live in the same cities as the
companies for which they work.
c. Find all employees in the database who live in the same cities and
on the same streets as do their managers.
d. Find all employees who earn more than the average salary of all
employees of their company.
e. Find the company that has the smallest payroll.

Answer:

a. Find the names of all employees who work for First Bank
Corporation.
select employee name
from works
where company name = ’First Bank Corporation’
b. Find all employees in the database who live in the same cities as the
companies for which they work.
select e.employee name
from employee e, works w, company c
where e.employee name = w.employee name and e.city
= c.city and
w.company name = c.company name
c. Find all employees in the database who live in the same cities and
on the same streets as do their managers.
select P.employee name
from employee P, employee R, manages M
where P.employee name = M.employee name and
M.manager name = R.employee name and
P.street = R.street and P.city = R.city
d. Find all employees who earn more than the average salary of all
employees of their company.
select employee name
from works T
where salary > (select avg (salary)
from works S
where T.company name = S.company name)
The primary key constraint on works ensures that each personworks
for at most one company.

e. Find the company that has the smallest payroll.


select company name
from works
group by company name
having sum (salary) <= all (select sum (salary)
from works
group by company name)

3.17 Consider the relational database of Figure 3.20. Give an


expression in SQL
for each of the following queries.
a. Give all employees of First Bank Corporation a 10 percent raise.
b. Give all managers of First Bank Corporation a 10 percent raise.
c. Delete all tuples in the works relation for employees of Small Bank
Corporation.
Answer:

a. Give all employees of First Bank Corporation a 10-percent raise.


(the
solution assumes that each person works for at most one company.)
update works
set salary = salary * 1.1
where company name = ’First Bank Corporation’
b. Give all managers of First Bank Corporation a 10-percent raise.
update works
set salary = salary * 1.1
where employee name in (select manager name
from manages)
and company name = ’First Bank Corporation’

c. Delete all tuples in the works relation for employees of Small Bank
Corporation.
delete from works
where company name = ’Small Bank Corporation’

3.18 List two reasons why null values might be introduced into the
database.
Answer:
• “null” signifies an unknown value.
• “null” is also used when a value does not exist.
3.19 Show that, in SQL, <> all is identical to not in.

Answer:
Let the set S denote the result of an SQL subquery. We compare
(x <> all S) with (x not in S). If a particular value x1 satisfies (x1 <> all S)
then for all elements y of S x1 6= y. Thus x1 is not a member of S and must
satisfy (x1 not in S). Similarly, suppose there is a particular value x2 which
satisfies (x2 not in S). It cannot be equal to any element w belonging to S,
and hence (x2 <> all S) will be satisfied. Therefore the two expressions are
equivalent.

3.20 Give an SQL schema definition for the employee database of


Figure 3.20. Choose an appropriate domain for each attribute and an
appropriate primary key for each relation schema.
Answer:

create table employee


(employee name varchar(20),
street char(30),
city varchar(20),
primary key (employee name))
create table works
(employee name person names,
company name varchar(20),
salary numeric(8, 2),
primary key (employee name))
create table company
(company name varchar(20),
city varchar(20),
primary key (company name))
member(memb no, name, age)
book(isbn, title, authors, publisher)
borrowed(memb no, isbn, date)

Figure 3.21 Library database for Exercise 3.21.

create table manages


(employee name varchar(20),
manager name varchar(20),
primary key (employee name))
3.21 Consider the library database of Figure 3.21.Write the
following queries in SQL.

a. Print the names ofmemberswho have borrowed any book published


by “McGraw-Hill”.
b. Print the names ofmemberswho have borrowed all books published
by “McGraw-Hill”.
c. For each publisher, print the names ofmemberswho have borrowed
more than five books of that publisher.
d. Print the average number of books borrowed permember. Take into
account that if an member does not borrow any books, then that
member does not appear in the borrowed relation at all.
Answer:

a. Print the names ofmemberswho have borrowed any book published


by McGraw-Hill.
select name
from member m, book b, borrowed l
where m.memb no = l.memb no
and l.isbn = b.isbn and
b.publisher = ’McGrawHill’
b. Print the names ofmemberswho have borrowed all books published
byMcGraw-Hill. (We assume that all books above refers to all books
in the book relation.)
select distinct m.name
from member m
where not exists
((select isbn
from book
where publisher = ’McGrawHill’)
except
(select isbn
from borrowed l
where l.memb no = m.memb no))
c. For each publisher, print the names ofmemberswho have borrowed
more than five books of that publisher.
select publisher, name
from (select publisher, name, count (isbn)
from member m, book b, borrowed l
where m.memb no = l.memb no
and l.isbn = b.isbn
group by publisher, name) as
membpub(publisher, name, count books)
where count books > 5
The above query could alternatively be written using the
having
clause.
d. Print the average number of books borrowed per member.
with memcount as
(select count(*)
from member)
select count(*)/memcount
from borrowed
Note that the above query ensures that members who have not borrowed
any books are also counted. Ifwe instead used count(distinct
memb no) from borrowed, we would not account for such members.

3.22 Rewrite the where clause


where unique (select title from course)
without using the unique construct.
Answer:
where(
(select count(title)
from course) =
(select count (distinct title)
from course))

3.23 Consider the query:


select course id, semester, year, section id, avg (credits earned)
from takes natural join student
where year = 2009
group by course id, semester, year, section id
having count (ID) >= 2;
Explain why joining section as well in the from clause would not change
the result.
Answer:
The common attributes of takes and section form a foreign key
of takes, referencing section. As a result, each takes tuple would match at
most one one section tuple, and there would not be any extra tuples in any
group. Further, these attributes cannot take on the null value, since they
are part of the primary key of takes. Thus, joining section in the from clause
would not cause any loss of tuples in any group. As a result, there would
be no change in the result.

3.24 Consider the query:


with dept total (dept name, value) as
(select dept name, sum(salary)
from instructor
group by dept name),
dept total avg(value) as
(select avg(value)
from dept total)
select dept name
from dept total, dept total avg
where dept total.value >= dept total avg.value;
Rewrite this query without using the with construct.
Answer:
There are several ways to write this query. One way is to use subqueries
in the where clause, with one of the subqueries having a second level
subquery in the from clause as below.
select distinct dept name d
from instructor i
where
(select sum(salary)
from instructor
where department = d)
>=
(select avg(s)
from
(select sum(salary) as s
from instructor
group by department))
Note that the original query did not use the department relation, and any
department with no instructors would not appear in the query result. If
we had written the above query using department in the outer from clause,
a department without any instructors could appear in the result if the
condition were <= instead of >=, which would not be possible in the
original query.
As an alternative, the two subqueries in the where clause could be moved
into the from clause, and a join condition (using >=) added.

3.25 The SQL query to find the names of those departments whose
budget is higher than that of Philosophy in the University schema is
as follows:
SELECT d2.dept_name, d2.budget

FROM depart d1, depart d2

WHERE d1.dept_name='philosophy' AND d2.budget>d1.budget

ORDER BY d2.dept_name desc;

3.26 Using the university schema, use SQL to do the


following:

For each student who has retaken a course at least twice (i.e., the student
has taken the course at least three times), show the course ID and the
student’s ID.

Please display your results in order of course ID and do not display


duplicate rows.

Answer:

 
select distinct course_id, ID

from takes

group by ID, course_id

having count(*) > 2

order by course_id

3.27 Using the university schema, write an SQL query to find


the IDs of those students who have retaken at least three
distinct courses at least once (i.e, the student has taken the course
at least two times).

Answer:

select distinct ID

from (

  -- At lease one time—

  select course_id, ID
  from takes

  group by ID, course_id

  having count(*) > 1)

group by ID

-- Have at lease three distinct course, count the number inside ID –

 
having count(course_id) > 2

3.28 The SQL query to find the ID and name of those instructors
who teach every course taught in his or her department is as
follows:

SELECT name, ID
COUNT(*) FROM instructor
INNER JOIN teaches ON instructor.id=teaches.ID
INNER JOIN course ON teaches.course_id=course.course_id
AS count1
WHERE count1= SELECT COUNT(*) FROM course AND
instructor.dept_name=course.dept_name
ORDER BY name

Here, the INNERJOIN in all three table perform because there is a relationship
between instructor and teaches using primary key ID and between teaches and
course, the relationship exists with primary key course_id. So, after inner join, the
course_id is counted and after that it is compared with the number of courses in
course.
3.29SQL Query:
The SQL query to find the ID and name of each History student whose name starts
with the letter ‘D’ and who has not taken at least five Music courses is as follows:

SELECT s.ID , s.Name

FROM

Student s , takes t , Section n , time_slot ts , Course c

WHERE

s.ID = t.ID AND

t.sec_id = n.sec_id AND

n.course_id = c.course_id AND

n.time_slot_id = ts.time_slot_id AND

s.dep_Name = "History" AND

s.Name LIKE 'D%'' AND

c.Title = "Music" AND

Count(ts.Time_slot_id) < '5' ;

Here, the LIKE operator is used to identify the students whose names begin with
‘D’.

3.31The SQL query to find the ID and name of each instructor who
has never given an A grade in any course he or she ha taught is as
follows:
SELECT ID, name

FROM instructor

WHERE ID NOT IN(

SELECT ID

FROM teaches, section

WHERE teaches.course_id = section.course_id AND


teaches.sec_id = section.sec_id AND teaches.semester =
section.semester AND teaches.year = section.year AND
grade = 'A'

);

3.34 The SQL query to find the number of students in each section in
the University schema is as follows:
SELECT s.course_id, s.sec_id, s.year, s.semester, count(id)
AS num

FROM takes t, section s

Where t.course_id==s.course_id AND t.sec_id==s.sec_id


AND t.year==s.year AND t.semester==s.semester

GROUP BY s.course_id, s.sec_id, s.year, s.semester

You might also like