Q3) (42 points) Consider the following Car database where primary keys are underlined:
Person Car
Name age city License color year MId
Ahmed 22 Riyadh 5222klj red 2015 Porsche510
Yacine 39 Jeddah 3678jdd green 2018 Impala
Faysal 35 Dammam 2599dnf yellow 2012 E300
Owns Model
Name License buy-year MId brand price weight
Ahmed 5222klj 2016 Porsche510 Porsche 250000 1300
Ahmed 3678jdd 2018 Porsche310 Porsche 190000 1400
Yacine 2599dnf 2015 Impala GM 26000 3000
E300 Mercedes 100000 2800
Write SQL statement corresponding to the following queries
Query #1 List full details of all green cars whose owner name contain "ysa" in
ascending Order
SQL SELECT P.Name, P.age, P.city
FROM Person P, Car C, Owns O
WHERE P.Name = C.Name AND C.Licesne= O.Licesne AND
O.Name like "%ysa%" AND C.color = 'green'
Ordered by Name ASC;
Query #2 List the owner names and buying year for all red cars with price greater than
$100,000 for owner who lives either in Jeddah or dammam.
SQL SELECT O.Name , O.buy-year
FROM Car C, Person P, Owns O, Model M
WHERE P.Name = O.Name AND O.License = C.License AND
C.color = "red" AND M.price > = 1000000 AND
P.City IN( Jeddah, Dammam);
Query #3 For each Person who has more than two cars, retrieve the Person name , age,
Licesne number, and the color of car purchased during 2016.
SQL SELECT P.Name , P. age, C. Licesne , C.color , COUNT(*)
FROM Person P, Owns O, Car C
WHERE P.Name = O.Name AND C.License= O.License
AND Buy-year = 2016
GROUP BY Name
HAVING COUNT (*) > 2 ;
Query #4 Display the car license number, color, and car maximum price of all cars
model with weight less than or equal 2500 KG.
SQL Select M.License, C.color , MAX(price)
From Car C, Model M
Where C.Mid = M.Mid AND M.weight <=2500;
Query #5 Find cars that are more expensive than all those produced By “Porsche”.
SQL SELECT C.License
FROM Car C, Model M
WHERE C.Mid= M.Mid AND M.price > ALL ( SELECT price
FROM Model
WHERE M.brand = ‘Porsche ’);
Query #6 Retrieve the name of car owners who own either yellow car or Mercedes car.
SQL (SELECT O.Name
FROM Car C, Owns O
WHERE O.license = C.license AND C.color = ‘yellow ’ )
UNION
(SELECT O.Name
FROM Car C, Owns O, Model M
WHERE O.license = C.license AND M.MId= Car.MId AND M.brand =
‘Mercedes’);
Q5) (80 Points ) The following ACTOR_PLAY database contains information about actors, plays, and
roles performed. Primary keys are underlined.
Actor(actor_id, name, salary, year_born)
Play(play_id, title, author, year_written)
Role(actor_id, play_id, character_name)
Where:
Actor is a table of actors, their names, salaries, rate and the year they were born. Each actor has a
unique actor_id, which is a key.
Play is a table of plays, giving the title, author, and year written for each play. Each play has a unique
play_id, which is a key.
Role records actors who performed roles (characters) in some plays.
Using the ACTOR_PLAY database write the following queries in SQL.
1) Write the relation schema (table) for the relation Role. Be sure to define appropriate keys and foreign
key constraints.
CREATE TABLE Role (
actor_id INTEGER,
play_id INTEGER,
character_name VARCHAR(100),
PRIMARY KEY(actor_id, play_id)
FOREIGN KEY actor_id REFERENCES Actor(actor_id), ON DELETE CASCADE
FOREIGN KEY play_id REFERENCES Play(play_id), ON DELETE CASCADE);
2) List in alphabetical order names of actors who played a role with character_name starting with the word
“star”. The List should not contain duplicates.
SELECT DISTINCT name
FROM Role r, Play p, Actor a
WHERE character_name like “star%”
AND p.play_id = r.play_id
AND a.actor_id = r.actor_id
ORDER BY name;
3) Which actor is older than all actors who played in “Horizon 2084” (title = “Horizon 2084”)
SELECT name
FROM Actor
WHERE year_born < ALL (SELECT year_born
FROM Role r, Play p, Actor a
WHERE title= “Horizon 2084”
AND p.play_id = r.play_id
AND a.actor_id = r.actor_id);
4) What was the highest salary of actors who played the character “Superman”.
SELECT MAX(a.salary)
FROM Actor a, Role r
WHERE r.character_name = ‘Superman’
AND a.actor_id = r.actor_id);
5) Returns the number of actors who have performed in three or more different plays written by the
author “Najib Mahfouz”.
SELECT count(r.actor_id)
FROM Role r, Play p
WHERE p.author = ‘Najib Mahfouz’
AND p.play_id = r.play_id
GROUP BY r.actor_id
HAVING count(DISTINCT r.play_id) > 2;
6) Write a SQL query that returns the names of all actors who have performed some play by the author
“Raed Al-Aqad” and have never performed in any play written by author “Ali Sibai”. The list should not
contain duplicates.
SELECT DISTINCT a.name
FROM Actor a, Play p, Role r
WHERE p.author = ‘Raed Al-Aqad’
AND p.play_id = r.play_id
AND r.actor_id = a.actor_id
AND a.actor_id NOT IN (SELECT r2.actor_id
FROM Role r2, Play p2
WHERE p2.author = ‘Ali Sibai’
AND p2.play_id = r2.play_id);
7) Give a 10% salary increase for all actors born after 1984
UPDATE Actor SET salary = salary *1.1 WHERE year_born > 1984;
8) What is the schema of the following query:
SELECT * FROM Actor NATURAL LEFT OUTER JOIN Role;
(actor_id, name, salary, year_born, play_id, character_name);
Question 4- (60 Points) Use the GARAGE Database schema in solving the following two questions.
CUSTOMER
CustomerNo Fname Lname FirstDateSeen
9
VISIT
CarID VisitDate VisitTime VisitReason VisitSymptoms MaintenanceCost
Car
CarID CustomerNbr Model Year Mileage LicensePlate MechanicalName
Specify the following queries on the relational database scheme shown above
a. (10 Points) Select in an ordered list (newer to older cars) all cars descriptions assigned to mechanical
engineer: Ahmed Abdullah.
b. (10 Points) List how many cars are assigned to each mechanical engineer:
Font DISTI
c. (10 Points) Select all the details of all the visits of customer named: Khaled Salem:
P a g e | 5 of 10
d. (10 Points) List the names of customers whose reported maintenance cost exceeded the average cost for
all visits by all customers:
e. (10 Points) Create a view named: NewGarage by retrieving the names of all customers except those who
are visiting mechanical Engineer Ahmed Abdullah.
f. (10 Points ) Delete from the database all cars with mechanical name starting with ‘Omar’.
P a g e | 6 of 10
Q5) (60 Points) The following Database state introduces an example, concerning World War 2 capital
ships. It involves the following relations:
ShipModels(model, type, country, numGuns, bore, displacement)
Ships(shipName, model, launched)
Battles(battleName, date)
Outcomes(shipName, battleName, result)
The relation ShipModels records the name of the model, the type(‘bb’ for battleship or ‘bc’ for
battlecruiser), the country that build the ship, the number of main guns, and their size (bore), and the
displacement(weight, in tons). Relation Ships records the name of the ship, the model of the ship, and
the year in which the ship was launched. Relation Battles gives the name and date of battles involving
these ships, and relation Outcomes gives the result (sunk, damaged, ok) for each in each battle. The
following shows sample instances for these relations.
Write an SQL statement for the following queries:
1) (7 Points) Write the create table statement of the table Ships, specify the primary key, foreign keys
and any constraint.
CREATE TABLE Ships (
shipName Char(30) NOT NULL,
model Char(30),
launched int,
PRIMARY KEY (shipName),
FOREIGN KEY (model) REFERENCES shipModels (model),
ON DELETE CASCADE ON UPDATE CASCADE;
2) (8 Points) Find the models of ships which participated in battles “Guadalcanal” or “North Cape”.
Order the results in alphabetical order.
Select model
From Outcomes O, Ships S
Where O.shipName = S.Shipname
AND battleName = “Guadalcanal” OR battleName = “North Cape”
Order by ShipName;
3) (7 Points) Find the name of all ships that begin with the letters “Re”
Select shipName
From Ships where shipName like "R%";
4) (8 Points) Find the countries whose ships had the largest number of guns.
Select country
From ShipModels
Where numGuns =
(Select max(numGuns)
From ShipModels);
OR
Select country
From ShipModels
Where numGuns >= All
(Select numGuns
From shipModels)
5) (7 Points) Find the models of ships, at least one of which was sunk in a battle
Select Model
From Ships
Where shipName in
(Select shipName
From Outcomes
Where result = 'sunk')
6) (8 Points) For each ShipModel with at least four ships, find the year in which the first ship of that
model was launched.
Select model, min(launched)
From Ships
Group by model
Having count(*) > 3
7) (7 Points) Delete from table Ships all ships sunk in battles.
Delete From Ships
Where shipName in
(Select shipName
From Outcomes
Where result = 'sunk');
8) (8 Points) Create a view “shipModelSunk” including each ShipModel that has participated in a
battle, and the number of ships of that model sunk in battles.
create view shipModelSunk as
Select model, count(O.shipName)
From Outcomes O, Ships S
Where S.shipName=O.shipName AND O.result = 'sunk'
Group by model
Question 5- (120 Points) Consider the World Factbook database relation
schema.
Nations (Nation_Name, Region, Population, Gdb)
Ranking_Index (Id, Nation_Name, Rank)
* GDP: Gross Domestic Product
Nations relation state:
Nation_Name Region Population Gdp
O
' Saudi Arabia ' 'Middle East' 31,540.37 646
' Pakistan ' 'Asia' 188,924.87 269.97
'Germany' 'Europe' 80,688.55 3,355.77
'Ghana' 'Africa' 27,409.89 37.86
fro
Ranking_Index relation state: her popular select population
Id
23
Nation_Name Rank
' Saudi Arabia' 141 fromnor regionAfi
where
45 ' Pakistan' 143
90 ' Germany' 13
34 'Ghana' 59
Write SQL statement that corresponding to the following queries:
selectsumcgdp
I
1. Show the total gdb of the world.
s
SELECT SUM(gdb)
FROM Nations; from
2. List all the regions just once each. Reg
SELECT DISTINCT region
select DISTINCT
FROM Nations;
3. List the nations which have a population greater than the whole population
of Africa 0
Cnane1
SELECT nation_name
FROM Nations
WHERE population >
eck.yegin.ca
(SELECT SUM(population)
FROM Nation
WHERE region='Africa');
S Page 7 of 10
fr
Gropa by regs
0
4. For each region show the region and number of nations.
SELECT region, COUNT(name)
FROM Nation
Group By region;
5. For each region show the region and number of countries with population of
at least 10 millions.
SELECT region, COUNT(name)
FROM Nation
WHERE population >=10000000
GROUP BY region;
6. List the regions with total populations of at least 100 million.
SELECT region
FROM Nations
GROUP BY region
HAVING SUM(population)>=100000000;
7. List nations name, GDP, and rank, sorted by the GDP(from high to low).
SELECT nation_name,gdp,rank
FROM Ranking_index r ,nations n
Where r.nation_name= n.nation_name
Order by gdp desc;
8. List all details of nations in the regions containing 'Kuwait', 'Saudi Arabia'
SELECT *
FROM nation
WHERE region IN
(SELECT region
FROM nation
WHERE name IN (' Kuwait','Saudi Arabia'));
9. Which nations (name) have a rank of 1?
SELECT nation_name
FROM Ranking_index
WHERE rank =1;
Page 8 of 10
10. Find the region of the nation that has a rank of 130.
SELECT region
FROM Ranking_index r ,nations n
Where r.nation_name= n.nation_name and rank = 130;
11. Which nations (name) have GDP greater than any European nation?
SELECT nation_name
FROM nation
WHERE gdp > ALL
(SELECT gdp
FROM nations
WHERE region = 'Europe');
Page 9 of 10
Q3) (SO-I) (50 Points) Consider the following database about car database structure and primary
keys are underlined.
Owner (SSN, Name, Age, City, Phone)
Car (CID, Model, Make, Color , ManfactureYear)
Owns (SSN, CID, Price, BuyingYear)
Insured (IPN, InsuranceName, Startdate, Expriedate, Cost, discountrate CID, SSN)
Write an SQL statement for the following queries:
1. Find the maximum price, the minimum price, and the average price among owns who
bought a red care from FORD manfacture before July 2015.
2. Retrieve the Insurance Policy numbers and Insurance Company name of all Owners who
living .
3. For each Insurance Company, retrieve the number of cars covered and the average
insurance cost of cars model E450 bought by less than SR50000.
4.
coverd by insurance company with cost greater than SR3000.
5. Retrieve the name of each owner who has a discount rate greater than 15% with care price
more than SR60000.
Good Luck and Best
Q5) (60 Points) Consider the following PRESCRIPTION database schema held in a relational
DBMS.
Doctor(DSSN, FName, LName, Specialty, Years, Phone)
Patient(PSSN, FName, LName, Address, DOB, DSSN)
Medicine(TradeName, Price, Generic)
Prescription(ID, Date, DSSN, PSSN)
Prescription_Medicine(ID, TradeName, NUnits, Type )
Write SQL statement that corresponding to the following queries
Query #1 List full details of all patients alphabetically ordered by Last Name
SQL
Query #2 List all Doctor information who wrote a prescription for patients’ living in Riyadh
and having age above 31 years.
SQL
Query #3 Decrease the price of any Medicine by 10% for any Company name including
“Zer”.
SQL
Query #4 Count how many prescription prescribe by Doctor Chen in capsule type
SQL
Query #5 List the Date of Birth and Last name for All patients treated by doctor first name
Cheng and who prescribed Medicine with price greater than SR 100.
SQL
Query #6 List the number of Patients for each Doctor.
SQL
Question 3: SO- C (50 points)
Consider the following schema about a university database:
Student (snum, sname, major, level, age, gpa)
Class (cname, start_time, room, fid)
Enrolled (snum, cname)
Faculty (fid, fname, deptid)
Write the following queries in SQL. No duplicates should be printed in any of the answers.
1. Find the names of all Junior Student (level = JR) who are enrolled in a class taught by faculty
John Smith.
SELECT DISTINCT S.Sname
FROM Student S, Class C, Enrolled E, Faculty F
WHERE S.snum = E.snum AND E.cname = C.name AND C.fid = F.fid AND F.fname = ‘John Smith’
AND S.level = ‘JR’;
2. Find the age of the oldest student who is either a History major or is enrolled in a course taught
by George Douglas.
SELECT MAX (S.age)
FROM Student S
WHERE (S.major = ‘History’)
OR S.num IN (SELECT E.snum
FROM Class C, Enrolled E, Faculty F
WHERE E.cname = C.name AND C.fid = F.fid AND F.fname = ‘George Douglas’);
3. For each major, print the major and the average gpa of students for that major.
SELECT major, AVG (gpa)
FROM Student
Group by major;
4. List the majors with average gpa of at least 3.5
SELECT major, AVG (gpa)
FROM Student
Group by major
Having avg (gpa) >= 3.5;
5. Find the names of all classes that either meet in room R128 or have five or more students
enrolled.
SELECT C.name
FROM Class C
WHERE C.room = ‘R128’
OR C.name IN (SELECT E.cname
FROM Enrolled E
GROUP BY E.cname
HAVING COUNT (*) >= 5);
Page 3|4