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

LAB

MANUAL
Course: CSC271: Database Systems

Department of Computer Science

Database Learning Procedure


1) Stage J (Journey inside-out the concept)
2) Stage a1 (Apply the learned)
3) Stage v (Verify the accuracy)
4) Stage a2 (Assess your work)

COMSATS University Islamabad (CUI) 1


Table of Contents

Lab # Topics Covered Page


#
Lab # 01 MySQL and Workbench Environment
Installation, Using and understanding tool
Lab # 02 Relational Algebra – Generic Operations
Generic Operations
Lab # 03 Relational Algebra – Cross Product
Cross Product
Lab # 04 Introduction to SQL
Select Statement usage
Lab # 05 SELECT Query Modifiers
Query Modifiers (ORDER BY and LIMIT)
Lab # 06 Lab Sessional 1

Lab # 07 SQL Join Operations


Join Operations
Lab # 08 SQL Outer/Inner Join Operations
Outer/Inner Join
Lab # 09 Aggregation and Groups
Aggregation Operations
Lab # 10 Sub Queries
Sub Queries
Lab # 11 SQL as Data Manipulation Language
DML Operations
Lab # 12 Lab Sessional 2

Lab # 13 SQL as Data Definition Language


DDL Operations
Lab # 14 Relational Database Design (Normalization)
Normalization
Lab # 15 Entity-Relational Model and Diagram
ERD
Lab # 16 Reinforcement of Joins and Aggregation
Joins, Aggregations and groups
Terminal Examination

2
LAB # 01

Statement Purpose:
Data is a collection of raw facts and figures, processed to obtain useful information to
assist organization in making decisions. Database is an organized collection of related
data. In order to manage the databases, Database Management Systems (DBMS) or
Database Systems offer sets of program and tools.

Activity Outcomes:
After performing this lab students should be able to:

 Load or unload a database in MySQL through MySQL Workbench


 Explore structure of tables in a database
 Retrieve data from the tables
 Change existing data in the database tables

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

1) Stage J (Journey)

Introduction
Data is a collection of raw facts and figures, processed to obtain useful information to
assist organization in making decisions. Database is an organized collection of related
data. In order to manage the databases, Database Management Systems (DBMS) or
Database Systems offer sets of program and tools.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. MySQL Workbench is a unified visual tool for database architects, developers, and DBAs
alike. Both MySQL Community Server and Workbench are already installed on your
workstation. If they are not, download and installed the latest version from the MySQL

3
Website. MySQL Server usually runs as a service on port 3306 and it starts automatically. If it
is not running, you should manually start it first. Afterwards open the Workbench. Its landing
window appears as follows.
2. When Workbench first starts, it presents the Home window, which lists saved connections to
MySQL Server. See the highlighted area in the snapshot. Connections help to manage and
connect with MySQL Server that actually runs the database. At any time you may add a new
connection by selecting the (+) icon.
3. Select an appropriate connection from the list. This opens a database management window
as shown below.

Solution:

Activity 2:
1. Expand the Sakila database from the left side of the Workbench window. Among the listed
categories, expand Tables. You will see list of tables in Sakila database.
2. Right click on any table of your choice (e.g. Actors) and select “Table Inspector”. It opens a
new tab showing the schema, attribute names and other metadata.
3. Afterwards right click on the same table and now select “Select Rows”. It will open another
tab for navigating through the contents of the database table.
4. The data view supports many different options such as sorting on a column by selecting its
header, searching contents, deleting a row, adding another, or exporting the contents to an
external file. You can play with these options.
5. Don’t forget to check the log pan below the query tab. It mentions all errors, warnings, and
messages.

4
Solution:

2) Stage v (verify)

Home Activities:
 Answer questions from the quiz. These questions assume Sakila database hasn’t changed.

3) Stage a2 (assess)
Lab Assignment and Viva voce

Deliverable
There is no deliverable for this lab. You only have to attempt a quiz designed around the lab
task.

5
LAB # 02

Statement Purpose:
Relational Algebra is a meta-language and forms underlying basis of SQL query language. It has
six basic operators including: select, project, union, set difference, rename, and cross product.
The operators take one or two relations as inputs and produce a new relation as a result.

Activity Outcomes:
After performing this lab students should be able to:

1. Implement relational algebra operations


2. Design query expressions by composing relational algebra operations
3. Retrieve data from a database using RA expressions

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database
 Relational Algebra Interpreter (Duke University)
o http://www.cs.duke.edu/~junyang/ra/
o https://github.com/junyang/RA

4) Stage J (Journey)

Introduction
Relational Algebra is a meta-language and forms underlying basis of SQL query language. It has
six basic operators including: select, project, union, set difference, rename, and cross product.
The operators take one or two relations as inputs and produce a new relation as a result.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. Load RA Interpreter and unzip it to any appropriate folder. We will use the interpreter to
write relational algebra queries and submit these to MySQL for retrieving required data.
2. Open console and change current directory to where the interpreter was placed.
3. Run following command from the console.

6
 java -jar ra.jar mysql.properties
4. A new ra prompt will be activated in the console. Here you can type and run relational
algebra operations.
5. As specified in the mysql.properties file, the interpreter would be connected to MySQL and
Sakila database. You can try to execute different expressions on the Sakila database.
6. Make sure MySQL Workbench is also running where you can inspect relation schema to
cross check that the queries are referring to accurate relation and attribute names. Note
that clicking on any relation on the left pane of Workbench opens relation information in a
bottom left pane.
7. Preferably write relational algebra expression within the Workbench and ignore if any error
is reported as the Workbench is primarily meant to work with SQL queries instead of
relational algebra. Once written, the expression can be pasted on the ra console to execute
the query.
8. The interpreter supports handful of relational algebra operations as listed in the following
table. The interpreter uses a special syntax and the expression should end with semi-colon
symbol. Examples are presented in the next table. Focus on first two operations.
9. You can start your experiment with the given relational algebra expressions.
10. Continue playing with the interpreter till you are comfortable with the querying syntax and
mechanism.

Solution:
Operation Syntax and Description

SELECT \select_{CONDITION} EXPRESSION

Selection over an expression

PROJECT \project_{ATTRIBUTE_LIST} EXPRESSION

Projection on selected attributes

RENAME \rename_{NEW_ATTRIBUTE_NAME_LIST} EXPRESSION

Rename all attributes of an expression

UNION EXPRESSION_1 \union EXPRESSION_2

Union between two expressions

DIFFERENCE EXPRESSION_1 \diff EXPRESSION_2

Difference between two expressions

INTERSECT EXPRESSION_1 \intersect EXPRESSION_2

Intersection between two expressions

CROSS EXPRESSION_1 \cross EXPRESSION_2


PRODUCT
Cross-product between two expressions

JOIN EXPRESSION_1 \join EXPRESSION_2

7
Natural join between two expressions; The interpreter literally follows
the rules for cross product that column names must be unique from
both sides. Don't forget to apply rename operation if after cross
product two columns with same name may appear in the schema.

1. You can start your experiment with the given relational algebra expressions.

Information Need Expression in Interpreter Syntax

Copies of ALASKA \select_{film_id=flm_id and title='ALASKA PHANTOM'} (


PHANTOM in the
inventory film \cross (

\rename_{inventory_id, flm_id, store_id, last_updat} inventory

);

Category of the film \project_{name} (


ICE CROSSING
\select_{category_id=cat_id} (

\select_{film_id=flm_id and title='ICE CROSSING'} (

film \cross (

\rename_{flm_id, cat_id, last_updat} film_category

\cross

(\rename_{category_id,name,last_updt} category)

);

2. Continue playing with the interpreter till you are comfortable with the querying
syntax and mechanism.

Activity 2:
1. Write relational algebra expression for the following information needs. Write their
corresponding expressions in the interpreter syntax as well.
2. Store all expressions in a plain text file.
3. Information needs:
a. List of movies with rental rate higher than $3. [2]
b. List of addresses from the “Alberta” district. [2]

8
c. List of actors by full name that have TOM as their first name. [3]
d. Title and replace cost of movies that are PG rated. [3]
e. Rental and return date of all rentals of customer 148. [3]
f. List payment id, amount and payment date of all such payments made by HELEN
g. HARRIS where the amount was more than $5. Hint: First find and note down
customer id for the given name and then lookup payment information from the
relevant relation. [3]
h. Rental and return date for the movie HUNGER ROOF. [4]

Solution:
Submit a PDF document including the relational algebra expressions in the interpreter syntax to
answer above-mentioned information needs as well as snapshot of their outcome when executed
on the interpreter.

5) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

6) Stage a2 (assess)
Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the relational algebra expressions in the interpreter syntax to
answer above-mentioned information needs as well as snapshot of their outcome when executed
on the interpreter.

9
LAB # 03

Statement Purpose:
Relational Algebra is a meta-language and forms underlying basis of SQL query language. It has
six basic operators including: select, project, union, set difference, rename, and cross product.
The operators take one or two relations as inputs and produce a new relation as a result.

Activity Outcomes:
After performing this lab students should be able to:

 Implement relational algebra operations


 Design query expressions by composing relational algebra operations
 Retrieve data from a database using RA expressions

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database
 Relational Algebra Interpreter (Duke University)
o http://www.cs.duke.edu/~junyang/ra/
o https://github.com/junyang/RA

7) Stage J (Journey)

Introduction
Relational Algebra is a meta-language and forms underlying basis of SQL query language. It has
six basic operators including: select, project, union, set difference, rename, and cross product.
The operators take one or two relations as inputs and produce a new relation as a result.

Stage a1 (apply)
Lab Activities:
Activity 1:
11. Load RA Interpreter and unzip it to any appropriate folder. We will use the interpreter to
write relational algebra queries and submit these to MySQL for retrieving required data.
12. Open console and change current directory to where the interpreter was placed.
13. Run following command from the console.

10
 java -jar ra.jar mysql.properties
14. A new ra prompt will be activated in the console. Here you can type and run relational
algebra operations.
15. As specified in the mysql.properties file, the interpreter would be connected to MySQL and
Sakila database. You can try to execute different expressions on the Sakila database.
16. Make sure MySQL Workbench is also running where you can inspect relation schema to
cross check that the queries are referring to accurate relation and attribute names. Note
that clicking on any relation on the left pane of Workbench opens relation information in a
bottom left pane.
17. Preferably write relational algebra expression within the Workbench and ignore if any error
is reported as the Workbench is primarily meant to work with SQL queries instead of
relational algebra. Once written, the expression can be pasted on the ra console to execute
the query.
18. The interpreter supports handful of relational algebra operations as listed in the following
table. The interpreter uses a special syntax and the expression should end with semi-colon
symbol. Examples are presented in the next table. Focus on first two operations.
19. You can start your experiment with the given relational algebra expressions.
20. Continue playing with the interpreter till you are comfortable with the querying syntax and
mechanism.

Solution:
Operation Syntax and Description

SELECT \select_{CONDITION} EXPRESSION

Selection over an expression

PROJECT \project_{ATTRIBUTE_LIST} EXPRESSION

Projection on selected attributes

RENAME \rename_{NEW_ATTRIBUTE_NAME_LIST} EXPRESSION

Rename all attributes of an expression

UNION EXPRESSION_1 \union EXPRESSION_2

Union between two expressions

DIFFERENCE EXPRESSION_1 \diff EXPRESSION_2

Difference between two expressions

INTERSECT EXPRESSION_1 \intersect EXPRESSION_2

Intersection between two expressions

CROSS EXPRESSION_1 \cross EXPRESSION_2


PRODUCT
Cross-product between two expressions

JOIN EXPRESSION_1 \join EXPRESSION_2

11
Natural join between two expressions; The interpreter literally follows
the rules for cross product that column names must be unique from
both sides. Don't forget to apply rename operation if after cross
product two columns with same name may appear in the schema.

1. You can start your experiment with the given relational algebra expressions.

Information Need Expression in Interpreter Syntax

Copies of ALASKA \select_{film_id=flm_id and title='ALASKA PHANTOM'} (


PHANTOM in the
inventory film \cross (

\rename_{inventory_id, flm_id, store_id, last_updat} inventory

);

Category of the film \project_{name} (


ICE CROSSING
\select_{category_id=cat_id} (

\select_{film_id=flm_id and title='ICE CROSSING'} (

film \cross (

\rename_{flm_id, cat_id, last_updat} film_category

\cross

(\rename_{category_id,name,last_updt} category)

);

2. Continue playing with the interpreter till you are comfortable with the querying
syntax and mechanism.

Activity 2:
1. Write relational algebra expression for the following information needs. Write their
corresponding expressions in the interpreter syntax as well.
2. Store all expressions in a plain text file.
3. Information needs:
a. First and last name of actors who played in BOONDOCK BALLROOM. [3]

12
b. Rental and return date for the movie ALASKA PHANTOM. [3]
c. List of movie titles that were never rented. [4]
d. Email addresses of customers who haven’t paid even a single penny yet. [5]
e. Email addresses of customers who although rented a movie but didn’t pay
anything. [5]

Solution:
Submit a PDF document including the relational algebra expressions in the interpreter syntax to
answer above-mentioned information needs as well as snapshot of their outcome when executed
on the interpreter.

8) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

9) Stage a2 (assess)
Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the relational algebra expressions in the interpreter syntax to
answer above-mentioned information needs as well as snapshot of their outcome when executed
on the interpreter.

13
LAB # 04

Statement Purpose:
Structured Query Language (SQL) was developed at IBM San Jose Research Laboratory as a part
of System R project. It is a declarative query language for querying a relational database. It also
includes features for defining the structure of the data, for inserting and modifying data in the
database, and for specifying security constraints. It is relational complete (it supports all six core
relational algebra operations). SQL commands can be classified into three groups out of which
we are going to practice commands that query a database, called Data Manipulation Language
(DML).

Activity Outcomes:
After performing this lab students should be able to:

1. Design SQL queries to retrieve data using SELECT clause and various associated
operators.
2. Translate relational algebra expressions to SQL queries.
3. Execute SQL queries over MySQL using MySQL Workbench.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

10) Stage J (Journey)

Introduction
Structured Query Language (SQL) was developed at IBM San Jose Research Laboratory as a part
of System R project. It is a declarative query language for querying a relational database. It also
includes features for defining the structure of the data, for inserting and modifying data in the
database, and for specifying security constraints. It is relational complete (it supports all six core
relational algebra operations). SQL commands can be classified into three groups out of which
we are going to practice commands that query a database, called Data Manipulation Language
(DML).

14
Stage a1 (apply)
Lab Activities:
Activity 1:
1. This lab assumes that MySQL Community Server is running and Sakila database has
been loaded using MySQL Workbench.
2. Open MySQL Workbench and open the default connection instance.
3. A new query window would open from where you can write and execute queries.

4. You can save the query file and can also add comments using # symbol.
5. On executing queries, results are displayed in the lower part of the screen.
6. Error or success messages are displayed in action output pane at the bottom.
7. Try running few SQL queries modeled during the lectures to get it going.
8. Continue playing with the Workbench and SQL queries till you are comfortable with
the querying mechanism and have learnt the shortcuts to execute queries.

Solution:

Activity 2:
1. Write SQL queries for the following information needs. You should execute your
attempt and make necessary corrections if needed.
2. Information needs:
a. Retrieve first names of all actors. [2]
b. Retrieve all payments over and above $10 made during 14-22 August 2005.
[3]
c. Find all films of more than two and half hour length and not rated PG-13. [3]
d. List id, title, rental rate, and replacement cost of all films below $1 rental
value. [3]

15
e. Find id and email of all customers whose first name is SARAH. [2]
f. Retrieve all addresses from Ishikawa, Hiroshima, or Osaka districts [2]

Solution:

11) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

12) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

16
LAB # 05

Statement Purpose:
WHERE clause and query modifiers (ORDER BY and LIMIT) are critical to retrieve required
information for a given information need. These clauses form very commonly used in SELECT
type of queries

Activity Outcomes:
After performing this lab students should be able to:

1. Design SQL queries to retrieve data using WHERE clause and various associated query
modifiers.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

17
13) Stage J (Journey)

Introduction
WHERE clause and query modifiers (ORDER BY and LIMIT) are critical to retrieve required
information for a given information need. These clauses form very commonly used in SELECT
type of queries.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. This lab assumes that MySQL Community Server is running and Sakila database has
been loaded using MySQL Workbench.
2. Open MySQL Workbench and open the default connection instance.
3. A new query window would open from where you can write and execute queries.
4. You can save the query file and can also add comments using # symbol.
5. On executing queries, results are displayed in the lower part of the screen.
6. Error or success messages are displayed in action output pane at the bottom.

Solution:

18
Activity 2:
1. Write SQL queries for the following information needs. You should execute your
attempt and make necessary corrections if needed.
2. Information needs:
a. A sorted list of country names ending with "tan" such as Pakistan. [2]
b. What are the names of all the languages in the database (sorted
alphabetically)? [2]
c. Find the full names (by concatenating first and last) of actors with “SON” in
their last name, ordered by their first name. [3]
d. Find all the addresses where the postal code is missing (empty or null), and
return these district-sorted. [3]
e. Return the sorted list of film titles given the film involves a “crocodile” as
well as a “monkey” (Hint: film_text). [2]
f. Find id, title, rental rate and replacement rate of 10 shortest films. [3]

Solution:

19
14) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

15) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

20
LAB # 06

Statement Purpose:
A SQL join clause combines records from two or more tables in a database. It creates a set that
can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables by
using values common to each.

Activity Outcomes:
After performing this lab students should be able to:

1. Design SQL queries to retrieve data from multiple tables by using JOIN operation.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

16) Stage J (Journey)

Introduction
Data is a collection of raw facts and figures, processed to obtain useful information to
assist organization in making decisions. Database is an organized collection of related
data. In order to manage the databases, Database Management Systems (DBMS) or
Database Systems offer sets of program and tools.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. This lab assumes that MySQL Community Server is running, Sakila database has
been loaded using MySQL Workbench, and the query window is open.
2. Try running following SQL query.
3. List rental and return date for the movie VANILLA DAY. Nine entries of renting this
movie should be found from the database. Keep in mind that there might be multiple
DVD copies of one film. A single copy is represented as an inventory item. For
21
finding rental date of a film, actually the rental date of the DVD of the corresponding
film is retrieved. Also note that the below query uses ON clause because an additional
comparison is made on the title attribute from one table (in contrast to comparing
columns from both sides).
a. select r.rental_date, return_date from film f join inventory i on
(f.film_id=i.film_id and f.title like 'VANILLA DAY') join rental r using
(inventory_id);

Solution:

Activity 2:
1. Write SQL queries for the following information needs. You should execute your
attempt and make necessary corrections if needed.
2. Information needs:
a. Find film ID of all movies rented on 2005-05-30. [2]
b. Email of customers who rented VANILLA DAY. [3]
c. List of movies (sorted on title) in the Horror category having rental rate of
more than $4. [3]
d. List first and last name of actors who played in the movie VANILLA DAY.
[3]
e. List full (first and last) name of actors who played in any Horror movie.
Names should be in sorted order and make sure the names do not repeat. [3]
f. Retrieve all the customers from Pakistan. List their id, name and the city. Sort
the result on city. [3]
g. For all the customers from Pakistan, retrieve which movies they have rented
and the movie category. The result-set should include customer name, city,
movie title and category. Sort the result on movie category. [3]

22
Solution:

17) Stage v (verify)

Home Activities:
 Answer questions from the quiz. These questions assume Sakila database hasn’t changed.

18) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

23
LAB # 07

Statement Purpose:
A SQL join clause combines records from two or more tables in a database. It creates a set that
can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables by
using values common to each.

Activity Outcomes:
After performing this lab students should be able to:

1. Design SQL queries to retrieve data from multiple tables by using JOIN operation.
2. Select among INNER, OUTER, NATURAL and theta join as and when required.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

24
19) Stage J (Journey)

Introduction
A SQL join clause combines records from two or more tables in a database. It creates a set that
can be saved as a table or used as it is. A JOIN is a means for combining fields from two tables by
using values common to each.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. This lab assumes that MySQL Community Server is running, Sakila database has
been loaded using MySQL Workbench, and the query window is open.
2. Try running following SQL query.
3. List of movie titles that were never rented. There are 43 of them. Notice that there are
two outer joins as the movie might be missing altogether from the inventory but may
still be included in the result set. On the other hand movie might be available in the
inventory but never rented, the SQL query covers both cases.
select f.title from film f left join inventory i using (film_id)
left join rental r using (inventory_id)
where (i.inventory_id is null or r.rental_id is null);

Solution:

25
Activity 2:
1. Write SQL queries for the following information needs. You should execute your
attempt on MySQL Workbench and make necessary corrections if needed before
submission.
2. Information needs:
a. List the top 25 films (lower replacement cost) that are not included in the
inventory. [3]
b. Email of customers who never rented BREAKING HOME. [3]
c. Email and first name of customers who never rented a movie from the Games
category. [3]
d. List of unpaid rentals (film title, inventory id and replacement cost). Unpaid
rental is defined as zero or no payment. List should be sorted on descending
order of replacement cost and ascending film titles. [4]
e. For the films in unpaid rental categories above, check if there exists a copy of
the film in the inventory. Return the film title and inventory id of the copy.
Hint: Self join! [4]
f. Take union of all the customers in query (b) and (c). What adjustments are
needed in the base queries? [3]

Solution:

26
20) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

21) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

27
LAB # 08

Statement Purpose:
Aggregate functions operate on the multi-set of values from a column of a relation and return a
consolidated value. This achieves scalar aggregation. Sometimes, we want to apply aggregation
to each of several groups of records to achieve vector aggregation.

Activity Outcomes:
After performing this lab students should be able to:

1. Design SQL queries to retrieve consolidated data by applying aggregate functions.


2. Implement grouping in the SQL queries and use it in combination with WHERE, JOIN
and other clauses.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

28
22) Stage J (Journey)

Introduction
Aggregate functions operate on the multi-set of values from a column of a relation and return a
consolidated value. This achieves scalar aggregation. Sometimes, we want to apply aggregation
to each of several groups of records to achieve vector aggregation.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. This lab assumes that MySQL Community Server is running, Sakila database has
been loaded using MySQL Workbench, and the query window is open.
2. Try running following SQL queries discussed during the lecture.
3. List accumulative payments per customer in descending order of the amount. The
following command will spit out customer id and sum of all amounts paid for rentals.
a. select customer_id, sum(amount) as sum_amount from payment group by
customer_id order by sum_amount desc;
b. Note: the renamed attribute can NOT be referred in where clause but it may
be referred in order by because select clause and hence the rename is
executed after where and having clauses.

Solution:

Activity 2:
6. Write SQL queries for the following information needs. You should execute your
attempt and make necessary corrections if needed.

29
7. Information needs:
a. Customers are from different countries. Find out how many customers are
listed from each country. Sort the output on country names. [3]
b. Find number of films listed in each category. List the most populated category
on top. [2]
c. Find out which film category has given most business to the rental company.
List the total earning along with the category name. The result set should also
include the second and third categories in the sorted order. [3]
d. Find the most popular film category. Popular is defined as most number of
cumulative rentals. [3]
e. List titles of films with 5 or more actors playing the act. Sort the output on
descending order of actors per film. [2]
f. Find ratio of rental revenue to number of actors for each film. You are
supposed to list number of actors per film as well its accumulative rental
revenue. Sort the records in descending order of rental revenue to number of
actors ratio (revenue/actors). [3]

Solution:

30
23) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

24) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

31
LAB # 09

Statement Purpose:
SQL provides a mechanism for the nesting of sub-queries. A sub-query is a select-from-where
expression that is nested within another query. It can be used in a condition of the WHERE
clause or within the HAVING clause (e.g. for set membership) or as a “table” of the FROM
clause.

Activity Outcomes:
After performing this lab students should be able to:

1. Design SQL queries to retrieve consolidated data by using sub-queries.


2. Implement correlated and non-correlated sub-queries using various clauses such as
SOME, ALL, EXISTS, EXCEPT, and UNIQUE.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

32
25) Stage J (Journey)

Introduction
SQL provides a mechanism for the nesting of sub-queries. A sub-query is a select-from-where
expression that is nested within another query. It can be used in a condition of the WHERE
clause or within the HAVING clause (e.g. for set membership) or as a “table” of the FROM
clause.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. This lab assumes that MySQL Community Server is running, Sakila database has
been loaded using MySQL Workbench, and the query window is open.
2. Try running following SQL query discussed during the last lab.
3. Find ratio of rental revenue to number of actors for each film. You are supposed to list
number of actors per film as well its accumulative rental revenue. Sort the records in
descending order of rental revenue to number of actors ratio (revenue/actors).
select f.title, act.actors, rev.revenue, rev.revenue/act.actors as 'revenue per
actor' from (select film_id, count(actor_id) as 'actors' from film_actor group
by actor_id) as act join
(select i.film_id, sum(p.amount) as 'revenue' from inventory i join rental r
using (inventory_id) join payment p using (rental_id) group by i.film_id) as
rev using (film_id) join film f using (film_id) order by rev.revenue/act.actors
desc;

Solution:

33
Activity 2:
1. Write SQL queries for the following information needs. You should execute your
attempt and make necessary corrections if needed. You are expected to provide two
versions of the queries: one that uses sub-queries constructs and the other that doesn’t.
In case the second query cannot be implemented, explain the reason.
2. Information needs:
a. Number of customers who never rented BREAKING HOME. [3]
b. List accumulative replacement cost of the movies that were never rented. [3]
c. Find out customers who have rented movies from each category. [3]
d. List total revenue of each film with 10 or more actors playing the act. Sort the
output on descending order of the revenue. [3]

Solution:

Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

34
26) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

27) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

35
LAB # 10

Statement Purpose:
SQL Insert, Update and Delete operations are expressed using the assignment operator for two
or more tables in a database. It uses a set that can be saved as a table or used as it is.

Activity Outcomes:
After performing this lab students should be able to:

1. Design SQL queries to Insert, Update and Delete and retrieve data from multiple tables
by using assignment operator.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

36
28) Stage J (Journey)

Introduction
SQL Insert, Update and Delete operations are expressed using the assignment operator for two
or more tables in a database. It uses a set that can be saved as a table or used as it is.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. This lab assumes that MySQL Community Server is running, Sakila database has
been loaded using MySQL Workbench, and the query window is open.

Solution:

Activity 2:
1. Write SQL queries for the following information needs. You should execute your
attempt and make necessary corrections if needed.
2. Information needs:
3. At least 4 Queries for Each of Following:
a. Insert New Films and Actors Records. [2]
b. Update Film Actor Table using conditional Logic. [3]
c. Delete Records of all Movies which are rented but rent was still not paid. [3]

37
Solution:

29) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

30) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

38
LAB # 11

Statement Purpose:
SQL provides a subset of commands, known as data definition language (DDL), for defining new
database schema. This subset includes CREATE TABLE command to define data structure for a
new table, its columns and domains.

Activity Outcomes:
After performing this lab students should be able to:

1. Create database schema and create relation schemas using CREATE SCHEMA and
CREATE TABLE command.
2. Understand the differences between different SQL data-types and chose an appropriate
type in a given situation.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

39
31) Stage J (Journey)

Introduction
SQL provides a subset of commands, known as data definition language (DDL), for defining new
database schema. This subset includes CREATE TABLE command to define data structure for a
new table, its columns and domains.

Stage a1 (apply)
Lab Activities:
Activity 1:
1. This lab assumes that MySQL Community Server is running and the query window is
open.

Solution:

Activity 2:
1. Implement SQL schema definition for creating a database for Alpha Auto Insurance.
2. Choose an appropriate domain for each attribute and an appropriate primary key (and
foreign key) for each relation.
3. The company currently manages following data in Excel files.
a. Persons (cnic, name, address, city, age)
b. Vehicles (registration number, district, maker, model, year, owner cnic)
i. Maker examples: Toyota, Honda
ii. Model examples: Corolla, Civic

40
c. Accidents (report number, registration number, date/time, location, region,
comments)
d. Damages (accident report number, body part, assessed amount, repair
summary)
4. The company only insures certain vehicles manufactured by Toyota and Honda as
they think other manufacturer do not conform to necessary safety standards and
features. So the maker column in Vehicle table should be restricted to contain limited
values. Hint: Read about the ENUM datatype.
5. Insert at least couple of records in every relation using INSERT command.
a. One of the persons should have CNIC value as 12345-1234567-1.
b. Registration year of some of vehicle should be 2012 or earlier and some others
after 2012.
c. Some of the accidents should be from “Islamabad” region.
6. Implement SQL queries to retrieve following information.
a. Calculate the total damage claim (amount) for accidents reported from the
Islamabad region.
b. Display the total damage claim amount for the person with CNIC value as
12345-1234567-1.
c. List all owners (cnic, name, and city) of cars registered before 2013.

Solution:

41
32) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

33) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF or plain-text document including the SQL queries to implement the database in
MySQL using the Workbench.

42
LAB # 12

Statement Purpose:
The goal of relational database design is to generate a set of relational schemas that allows us to
store information without unnecessary redundancy, yet also allows us to retrieve information
easily. This is accomplished by designing schemas that are in an appropriate normal form.

Activity Outcomes:
After performing this lab students should be able to:

1. Identify functional dependencies in a relation.


2. Identify if a relation is in BCNF (and 3NF) or not.
3. Decompose a relation to achieve BCNF.
4. Create database schema from the design of relations.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

43
34) Stage J (Journey)

Introduction
The goal of relational database design is to generate a set of relational schemas that allows us to
store information without unnecessary redundancy, yet also allows us to retrieve information
easily. This is accomplished by designing schemas that are in an appropriate normal form.

Stage a1 (apply)
Lab Activities:
Activity 1:
2. This lab assumes that MySQL Community Server is running and the query window is
open.
3. Carefully, study and analyze the following data table and perform the tasks mentioned
below.

Solution:

Activity 2:
1. Identify the information items that should be recorded in a database. Outcome of this
task is a list of attributes. Make sure that attribute domains are atomic.

44
2. Assuming the list of attributes as a single large relation, identify functional
dependencies in the relation and also find closure set.
3. Based on the studied rules for lossless decomposition, translate the large relation into
BCNF.
4. Use DDL to create the relation schema in MySQL. Choose an appropriate domain for
each attribute and an appropriate primary key (and foreign key) for each relation.
5. Use DML to record all necessary information from the given sheet into the newly
created database.

Solution:

35) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

45
36) Stage a2 (assess)
Lab Assignment and Viva voce

Deliverable
Submit a PDF or plain-text document including the SQL queries to implement the database in
MySQL using the Workbench.

46
LAB # 13

Statement Purpose:
The goal of relational database design is to generate a set of relational schemas that allows us to
store information without unnecessary redundancy, yet also allows us to retrieve information
easily.

Activity Outcomes:
After performing this lab students should be able to:

1. Identify relations and associations given a case study or scenario.


2. Design and develop an E-R model using E-R Diagram notations.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

47
37) Stage J (Journey)

Introduction
The goal of relational database design is to generate a set of relational schemas that allows us to
store information without unnecessary redundancy, yet also allows us to retrieve information
easily.

Stage a1 (apply)
Lab Activities:
Activity 1:
3. T This lab assumes that MySQL Community Server is running and MySQL
Workbench is loaded.
4. From the bottom of the main Workbench screen, select the plus sign near Models to
create a new E-R diagram.

5. Select (double click) the “Add Diagram” option. A new tab for the ERD would open.

6. You may click the entity (table) icon from the tool bar and then click an
appropriate portion of the diagram to create a new entity in the model.

7. Double click the newly created table placeholder in the diagram to


open its properties in the bottom of the screen. There you can modify name of the
relation and may also add attributes and their constraints such as PK for primary key,
NN for setting not null, and AI for auto increment.

48
8. From the menu, go to Model > Model Options and select “Show Caption” in the
options for diagram to enable relationship labels.
9. Before modeling an association between two relations, make sure that the target
relations have primary keys. Later, click (DON’T DRAG) the relevant association
icon from the toolbar and select first (where foreign key should be added) and then
the second relation (referring to the primary key). In case of many-to-many associate,
a new relation would be created that you may modify.
10. MySQL Workbench doesn’t allow to model a single many-to-many association
directly as it creates an associative entity instead, and creates two one-to-many
associations.

Solution:

Activity 2:
1. Draw an ERD for the following situation using MySQL Workbench.
a. Deewan Engineering is an auto-parts manufacturing firm with approximately
500 employees. A database is required to keep track of all employees, their
skills, projects assigned, and departments worked in. Every employee has a
unique number assigned by the firm and is required to store his or her name
and date of birth. If an employee is currently married to another employee of
Deewan, the date of marriage and who is married to whom must be stored;
however, no record of marriage is required if an employee’s spouse is not also
an employee. Each employee is given a job title (e.g., engineer, secretary, and

49
so on). An employee does only one type of job at any given time, and we only
need to retain information for an employee’s current job.
b. There are 11 different departments, each with a unique name. An employee
can report to only one department. Each department has a phone number.
c. To procure various kinds of equipment, each department deals with many
vendors. A vendor typically supplies equipment to many departments. We are
required to store the name and address of each vendor and the date of the last
meeting between a department and a vendor.
d. Many employees can work on a project. An employee can work on many
projects (e.g., Atlas Honda, Indus Motors, and so on) but can only be assigned
to at most one project in a given city. For each city, we are interested in its
name and population. An employee can have many skills (preparing material
requisitions, checking drawings, and so on), but she or he may use only a
given set of skills on a particular project. (For example, an employee Mumtaz
may prepare requisitions for the newly acquired Indus Motors project and
prepare requisitions as well as check drawings for manufacturing bumpers of
new City for Atlas Honda.) Employees use each skill that they possess in at
least one project. Each skill is assigned a number, and we must store a short
description of each skill. Projects are distinguished by project numbers, and
we must store the estimated cost of each project.
2. Normalize the model into 3BNF and adjust the entities in the ERD.
3. Finally, generate the database schema from the normalized model.

Solution:

50
38) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

39) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF or plain-text document including the MWB file while designing the ER-D of the
model using MySQL Workbench

51
LAB # 14

Statement Purpose:
Aggregate functions operate on the multi-set of values from a column of a relation and return a
consolidated value. This achieves scalar aggregation. Sometimes, we want to apply aggregation
to each of several groups of records to achieve vector aggregation.

This lab is a reinforcement of the SQL Joins and Aggregation functions.

Activity Outcomes:
After performing this lab students should be able to:
1. Design SQL queries to retrieve data from multiple tables by using JOIN operation.
2. Design SQL queries to retrieve consolidated data by applying aggregate functions.
3. Implement grouping in the SQL queries and use it in combination with WHERE, JOIN
and other clauses.

Instructor Note:
As pre-lab activity, attend theory class.

Tools/Software Requirement
 MySQL Community Server 5.6
 MySQL Workbench 6.1
 Sakila Database

52
40) Stage J (Journey)

Introduction
Aggregate functions operate on the multi-set of values from a column of a relation and return a
consolidated value. This achieves scalar aggregation. Sometimes, we want to apply aggregation
to each of several groups of records to achieve vector aggregation.

This lab is a reinforcement of the SQL Joins and Aggregation functions.

Stage a1 (apply)
Lab Activities:
Activity 1:
 This lab assumes that MySQL Community Server is running, Sakila database has
been loaded using MySQL Workbench, and the query window is open.

Solution:

Activity 2:
1. Load HR database in MySQL. The schema and data files are available on the course website.
Load all SQL scripts starting from 1 to 7, one at a time. Make sure you load data in a
sequential order of files that doesn’t violate integrity constraints.
 Familiarize yourself with the schema and the data.
2. Write SQL queries for the following information needs. You should execute your attempt
and make necessary corrections if needed.
3. Information needs:

53
1) Find salary bill (current salaries of every employee as well as a cumulative figure) for
the department d003. Note that employees might have switched from one
department to another department. Those who are currently in a particular
department are modeled as '9999-01-01' value in the to_date field of dept_emp
relation. Similar approach is followed in the salaries relation. [4]
2) Find cumulative salary bill of each department. List department name, manager's
name and the bill amount. [4]
3) List the employee who was given most number of promotions (hint: check for salary
increase). If two or more employees were given same number of promotions, list all
of them. [4]
4) Find the employee who was given highest salary raise. Don't forget to manually
validate the output of the query. [4]
5) Find average number of employee-promotions per department. [4]
Solution:

54
41) Stage v (verify)

Home Activities:
 Answer questions from the task. These questions assume Sakila database hasn’t changed.

42) Stage a2 (assess)


Lab Assignment and Viva voce

Deliverable
Submit a PDF document including the SQL queries to answer above-mentioned information
needs as well as snapshot of their outcome when executed over MySQL using the Workbench.

55

You might also like