Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Database Development (BAIT3)

Exam assignment
Daniele Dell’Aglio and Huan Li
05/01/2021

Full name:

Student number:

E-mail address: @student.aau.dk

Remarks
This exam consists of ten exercises and the maximum number of points is 100. It has 16 pages.
Read carefully the text of each exercise before solving it. Prepare your answers directly on the
exam paper (e.g. by printing it, answering it with your device, etc.) or a white paper. In the latter
case, clearly indicate the number of the exercise above your answer, as in the following example:
# Exercise 22.1 #
SELECT * FROM table WHERE variable > 10;
# Exercise 21.3 #
(a)
# Exercise 25.2 #
YES; NO; YES; YES

Do not forget to indicate your name, student number and e-mail address. At the end, prepare a PDF
or a ZIP file containing the answers (if you use paper and pen, use a scanner or your camera), and
submit them in the Digital Exam platform. You must upload your answers by 05/01/2021 13:00
(CET). Make sure that you have enough time to upload your answers on time.
Use readable handwriting and if you scan or take photos, make sure they are clear (e.g. no blur).
During the exam, you are allowed to consult books and notes. You can also use a computer, but
only for accessing the electronic textbook, slides, and notes. You are not allowed to use MySQL
or any other software for helping yourself to solve the exercises.
This is an individual exam. You are not allowed to communicate with your peers or other people.

1 2 3 4 5 6 7 8 9 10 Sum

6 6 6 17 15 15 16 7 6 6
Do not write in this table
1
1. Inner joins [6 pts]
Consider the tables r and s, defined as follows:

Answer the following questions.


1.1 [2 pts] Consider the query:
SELECT * FROM r JOIN s ON r.A = s.C;
What is the result of the query evaluation? Select one of the possible answers (clearly mark one
of the four choices).

2
1.2 [4 pts] Consider the query:
SELECT * FROM r NATURAL JOIN s;
What is the result of the query evaluation? Write the answer below.

A B C D
1 2 3 2
3 2 1 10
3 2 1 7

2. Outer joins [6 pts]


Consider the tables r and s defined as follows:

Answer the following questions.


2.1 [4 pts] Consider the query:
SELECT * FROM r LEFT OUTER JOIN s ON r.A = s.Y;
What is the result of the query evaluation? Write the answer below.
A B X Y Z
a d e a b
c c NULL NULL NULL
d b d d A
d b a d c

2.2 [2 pts] Consider the following incomplete query:


SELECT * FROM r _________ OUTER JOIN s ON r.B = r.Z;
The query produces the following answer:

3
Which type of outer join has been executed? Select one of the following options.
 LEFT
 RIGHT
 NATURAL
 FULL

3. Set operations [6 pts]


Consider the following tables u, v and w:

Answer the following questions.


3.1 [4 pts] Given the query:
SELECT color FROM u INTERSECT SELECT color FROM v INTERSECT SELECT
color FROM w;
What is the result of the query evaluation? Write the answer in the box below.

color
blue

4
3.2 [2 pts] Given the query:
SELECT color FROM u UNION SELECT color FROM v EXCEPT SELECT color
FROM w;
What is the result of the query evaluation? Select one of the possible answers (clearly mark one
of the four choices).

5
4. Null values [17 pts]
The Aalborg Book Club (ABC) ran a survey among its members and stored the answers in the
survey table:

In the first part of the survey, ABC asks for demographic information (name, gender and country).
ABC members can decide to do not disclose their gender (NULL values). Next, the survey proposes
three questions to assess if members read books in English (q1), in Danish (q2) and how many
books they read in the last month (q3). Similar to the gender, members can skip questions, resulting
in NULL values in the q1, q2 and q3 columns.
Answer the following questions.
4.1 [6 pts; 2 pts per answer] ABC executes three queries. For each of them, write the query answer.

a. SELECT name FROM survey WHERE q1 AND q2;

name
Dave
Fred

b. SELECT name FROM survey WHERE q1 OR NOT q2;


name
Dave
Fred
Chris
Bob
Emma

6
c. SELECT name FROM survey WHERE q1 OR q2 AND country <> 'SE';

name
Dave
Fred
Emma

4.2 [4 pts] Write a SQL query to retrieve from the survey table the name of the members who did
not indicate their gender, ordered alphabetically.
SELECT name
FROM survey
WHERE gender IS NULL
ORDER BY name;

4.3 [4 pts] Write a SQL query to retrieve from the survey table the name of the members who
skipped at least one of the three questions (q1, q2 and q3).
SELECT name
FROM survey
WHERE q1 IS NULL OR q2 IS NULL OR q3 IS NULL

4.4 [3 pts] Given the following query:


SELECT gender, country, AVG(q3) FROM survey GROUP BY gender, country;
What is the result of the query evaluation?

7
gender country AVG(q3)
NULL DK 1
Female DK 3
Male SE 5

5. Map an ER diagram to tables [15 pts]


The North Jutland Dodgeball (NJD) association manages the dodgeball tournaments in the region.
The IT responsible of the NJD defines the following ER diagram to model the teams and their
members:

The team members are identified through their CPR number, and they are described through
names, birth dates and heights. A team is characterized by a unique identification number, a name,
an address and a category. Possible categories are pro, amateur and disbanded. A team has a
member in the coach role, and one or more in the player role. Players have a jersey number, and
cannot play for different teams.
Map the ER diagram to tables using appropriate SQL DDL statements. Remember to include all
relevant constraints, such as primary and foreign keys.
CREATE TABLE Person (
cpr CHAR(11) PRIMARY KEY,
name VARCHAR(50) NOT NULL,
birthdate DATE,
height FLOAT,
play_team INTEGER REFERENCES Team(id) NULL,
number INTEGER NULL
);

CREATE TABLE Team (


id INTEGER PRIMARY KEY,

8
name VARCHAR(50) NOT NULL,
address VARCHAR(100),
category CHAR(9) ADD CONSTRAINT CHECK
(category IN (‘pro’, ‘amateur’, ‘disbanded’)),
coach CHAR(11) REFERENCES Person(cpr) NOT NULL
);

9
6. Design of an ER diagram [15 pts]
The Aalborg Transport Service (ATS) operates the underground system of the city. Each
underground line has an opening year and a total length, and it is identified by a color. Lines are
composed by station sequences, such as in the following example:

Each station has a name and an unique ID. Some stations are part of one line, while others are
shared among two or more lines. Stations have positions in the lines they are part of. For example,
the Nordkraft, Castle and Museum stations have positions 3, 4 and 5 in the orange line, respectively.
Kommune, which is shared among lines, has positions 2 and 3 in blue and red lines, respectively.
ATS assigns a certain number of trains to each line. Each train has an ID and a maximum capacity.
Moreover, every train is colored with the color of the line it is assigned to. As a consequence, each
train operates in exactly one line.
ATS purchases an insurance plan for each train it owns. An insurance plan has a contract number,
an insured amount, the start and end dates of the insurance coverage.
Design an ER diagram for the ATS database according to the specification above. Explicitly
indicate which attributes are part of primary keys and the cardinality of the relationships. You must
draw the ER diagram by hand.

10
11
7. SQL statements [16 pts]
The Aalborg Movie Club (AMC) owns a database about movies. The actor table stores the
information about actors: an unique ID, name, age, and country. The movie table contains data
about movies: movie ID, title, release year, genre, and revenue. The play table captures the roles
that actors played in movies. The prize table describes prizes, through a prize ID, an issuer, an
award year, and the awarded movie. The four tables are defined in SQL as follows:
CREATE TABLE actor (
aid INT PRIMARY KEY,
name VARCHAR(40) NOT NULL,
birthday DATE,
country VARCHAR(20));

CREATE TABLE movie (


mid INT PRIMARY KEY,
title VARCHAR(140) NOT NULL,
year DATE,
genre VARCHAR(15) CHECK (genre IN ('Action', 'Drama', 'Comedy')),
revenue DECIMAL(15,2));

CREATE TABLE play (


mid INT REFERENCES movie(mid),
aid INT REFERENCES actor(aid),
role VARCHAR(20) NOT NULL,
PRIMARY KEY(mid, aid));

CREATE TABLE prize (


pid INT PRIMARY KEY,
issuer VARCHAR(8),
year DATE,
mid INT REFERENCES movie(mid));

Write SQL statements equivalent to the following statements.


7.1 [2 pts] List the names of actors who are older than 20 and come from a country ending with
‘land’.
SELECT name
FROM actor
WHERE country LIKE ‘%land’
AND birthday <= ‘2001-01-05’;

7.2 [2 pts] Get the number of the movies released per year.
SELECT EXTRACT(YEAR BY year) AS y, COUNT(*) AS movie_cnt
FROM movie
GROUP BY y;

12
7.3 [3 pts] Create the view awarded_movies, containing only the awarded movies. The attributes
of awarded_movies must be the same of the movie table.
CREATE VIEW awarded_movies AS
SELECT m.*
FROM movie AS m NATURAL JOIN prize;

7.4 [3 pts] List the titles of awarded Action movies between 2010 and 2015. Optionally, you can
use the awarded_movie view (introduced in Question 3) to build this statement.
SELECT title
FROM awarded_movie
WHERE genre = ‘action’
AND year >= ‘20100101’
AND year <= ‘20151231’;

7.5 [3 pts] List the titles of the awarded movies that get less revenue than the average in their genre.
Optionally, you can use the awarded_movie view (introduced in Question 3) to build this
statement.
SELECT title
FROM awarded_movie AS A
WHERE revenue < ( SELECT AVG(revenue)
FROM awarded_movie AS B
WHERE A.genre = B.genre );

7.6 [3 pts] Retrieve the IDs of the top-3 actors who played most number of awarded movies.
Optionally, you can use the awarded_movie view (introduced in Question 3) to build this
statement.
SELECT aid
FROM play NATURAL JOIN awarded_movie
13
GROUP BY aid
ORDER BY COUNT(mid) DESC
LIMIT 3;

8. Database security [7 pts]


The Aalborg Book Club (ABC) created a login page for its members in the club web site:

After the user presses the login button, the following code is executed:
txtName = getRequestString("Username");
txtPassword = getRequestString("Password");
sqlQuery = "SELECT COUNT(*) FROM users WHERE name LIKE '" + txtName +
"' AND password LIKE '"+txtPassword+ "';";
After that sqlQuery is created, the server executes it. If the answer is a number greater than 0
the login is successful, otherwise the login fails. The table users contains the following records:

Answer the following questions.


8.1 [4 pts; 1 pt per answer] Check the following pairs of inputs for the username and password
fields. For each pair, indicate if it leads to a successful login or not.

Username Password Success Failure


A' OR '1' = '1 A O
A A' OR '1' = '1 O
A' OR 1 = 1 A O
A A' OR 1 = 1 O

14
8.2 [3 pts] Spotting the SQL injection threat, ABC updates the script as follows:
txtName = getRequestString("Username");
txtPassword = getRequestString("Password");
if(txtName.contains("'"))
failedLogin();
else if(txtPassword.contains("'"))
failedLogin();
else {
sqlQuery = "SELECT COUNT(*) FROM users WHERE name LIKE '" +txtName+
"' AND password LIKE '"+txtPassword+ "';";
As before, after that sqlQuery is created, the server executes it and the login is successful if the
query answer is a number greater than 0.
Would you consider the ABC web site safe now? If not, which username and password can a
malicious user insert to access the web site without knowing the records of the users table?
It is not safe yet, as one may input % as username and password.

9. Triggers [6 pts]
Consider the company and country tables, defined as follows:

The database administrator registers the following trigger in the DBMS.


CREATE TRIGGER update_country_value
AFTER INSERT ON company
FOR EACH ROW
15
BEGIN
UPDATE country SET value = value + NEW.value WHERE name = NEW.country;
END;

Answer the following questions. Assume that questions do not influence each other, i.e., answer
each question with regards to the two tables described above.
9.1 [2 pts] After the execution of the INSERT statement:
INSERT INTO company VALUES ('Lego', 80, 'DK');
the following SELECT query is executed:
SELECT name, value FROM country;
What is the result of the SELECT query execution?

name value
DE 96
US 120
DK 80

16
9.2 [2 pts] After the execution of the INSERT statements:
INSERT INTO company VALUES ('SAP', 100, 'DE');
INSERT INTO company VALUES ('FORD', 10, 'US');
INSERT INTO company VALUES ('MS', 214, 'US');
the following SELECT query is executed:
SELECT name, value FROM country;
What is the result of the SELECT query execution?

name value
DE 196
US 344
DK 0

9.3 [2 pts] After the execution of the INSERT statements:


INSERT INTO company VALUES ('DIOR', 438, 'FR');
the following SELECT query is executed:
SELECT name, value FROM country;
What is the result of the SELECT query execution?

name value
DE 96
US 120
DK 0

17
10. Database administration [6 pts]
Consider the Book table defined as follows:
CREATE TABLE Book (
id INT PRIMARY KEY,
title VARCHAR(40),
author VARCHAR(20),
price DOUBLE(20));

Jim is the root user and manages the access to the table. Answer the following questions.
10.1 [2 pts] Peter is an existing user of the database. To let Peter retrieve data from the Book
table, Jim writes the following incomplete statement:
GRANT ________ ON Book TO Peter;
What is the correct keyword Jim should use to complete the above query?
 SELECT
 INSERT
 UPDATE
 DELETE

10.2 [2 pts; 0.5 pts per answer] Jim executes those two queries to add a new user, Cathy:
CREATE USER Cathy IDENTIFIED BY 'HalloHallo';
GRANT SELECT Book(title, prize) TO Cathy WITH GRANT OPTION;
Can Cathy run successfully the following queries? For each query, answer yes or no.
YES NO
SELECT AVG(prize) FROM Book GROUP BY author; O
SELECT prize FROM Book WHERE title = ‘The Lord of The Rings’; O
GRANT DELETE to Peter; O
GRANT SELECT(prize) to Peter; O

18
3. [2 pts, 0.5 pts per answer] Jim wants to let Cathy successfully execute the following SQL
statement:
DELETE FROM Book WHERE price < (SELECT AVG(price) FROM Book);
For each of the following statements, answer yes if the statement lets Cathy successfully execute
her query, no otherwise.
YES NO
GRANT ALL ON Book TO Cathy; O
GRANT UPDATE ON Book TO Cathy; O
GRANT DELETE, SELECT ON Book TO Cathy; O
GRANT SELECT, UPDATE ON Book TO Cathy; O

19

You might also like