Lab 9

You might also like

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

IS222 Lab 9

Advanced SQL using MySQL


Objectives:

 To write a variety of more advanced SQL queries in MySQL. We will continue to build on the
previous labs using the database schema from the previous labs, (which has been already
implemented in your student database).

Pre-Lab Preparation:

Before attending this lab, it is a requirement to have done the following:


 You should have completed all previous labs. 
  You should have read the lab (this document). 
 You should have read the Chapter on Advanced Structured Query Language (SQL) from the
textbook and looked at the lecture notes relating to SQL from prior weeks. 

 You should have looked at the following reference links to familiarize yourself with the SQL
syntax covered so far (for DML/DDL statements) when working with MySql. You also can
use these during the lab for reference:
1) http://www3.ntu.edu.sg/home/ehchua/programming/sql/MySQL_Beginner.html
(provides a good summary of pivotal SQL commands and its syntax)
2) https://dev.mysql.com/doc/refman/5.1/en/sql-syntax.html (this link provides the entire
reference manual for describing the syntax for the SQL statements supported by MySQL.
This is the complete guide for you to locate details regarding the syntax of any type of
DDL/DML SQL query supported in MySQL.

Note that the reference manual is for MySql 5.1 as that is what we have installed in our
SCIMS based server

3) http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html (provides
Date/Time functions)
4) Note that you can also search for any particular type of SQL syntax on Google.

Note:

After the lab and the lectures from the previous week(s), you should be aware of the following:
- All SQL/MySQL related activities/exercises from all the previous labs/lectures
- Have familiarity with the syntax of writing more advanced queries relating to
 Creating views
 MySql Date/Time functions
 Indexes
 Sub queries
 Unions
 Having clause
 Joins (left, right, inner)

1
 Correlated sub queries

As far as joins are concerned for this course, you mostly need to be familiar with the syntax of
inner, left and right joins. Right joins work very much the same way as left joins.

What you will be doing?

In this lab you will continue writing SQL statements (of a more advanced nature) based on the
schema originally created in Lab 7. You should still have the tables from the previous labs in your
database.

Overall Goal of this Tutorial

By the end of this lab, you should know how write more advanced SQL queries from where we last
left off.

You can also practice writing more of these types of queries examined in the lab by attempting
the review questions at the end of the textbook chapters for Advanced SQL & Intro to SQL in your
own time.

Schema for the Lab (continuation of the previous lab)

Task 1: Advanced Queries

- Your tutor will need to see your queries so these should be saved in a text file.
- Call this file Lab9.sql.
- Save this file anywhere you can have access to it after the lab.

Note:
You cannot save your queries in MySQL. You do not need to run a script for these questions

2
below.

For all these questions, you will use the original tables in the schema above and NOT the
additional CUSTOMER2 or Product2 tables earlier created in the previous lab, unless explicitly
specified.

1. Create a query to display the details of all of the invoices with the invoice date format as in the
eg.: 'Monday, 21st October, 2012'. Use the Date_Format function and look up the MySQL
reference for the syntax. List only the invoice number and date. Order by ascending order of
the date aliased as NewDate.

Your output should be similar to the one below:

2. Create a query to display the invoice number, invoice date for each invoice including the
difference between the invoice date and the date 12/2/2004 (12th Feb, 2004), aliased as
date_difference.

Use the DateDiff function and look up the MySQL reference for the syntax. Order by ascending
order of the date difference.

Also format the invoice date as for eg, 12/02/2004 (day/month/year). Use the alias NewDate

Hint: 12/2/2004 can be represented as 2004-02-12 in the query

Your output should be similar to the one below:

3
3. Create an index for the product table based on the product description. Use the index name,
description_index. The index doesn’t need to be unique.

After you create your index, you can view it as follows:

SHOW INDEX FROM product;

Additional Question: What is the index type for your new index and what are all the indexes
that you can see after you have created your new index?

4. Create a new view called Customer_View that will display the customer code
(CV_CustomerCode), customer full name (CV_ Name), customer area code (CV_AreaCode),
customer phone number (CV_Phone) and customer balance (CV_Balance). The brackets
indicate the aliases for each column.

The customers should be sorted in the ascending order of their full name.

Hint:

See the syntax for creating a view. After you create your view, issue the command show tables;
and locate your view.

To see the details of your newly created view, issue the statement,
select * from Customer_View;

The SQL statement would be case sensitive for the view name in the shell.

5. Create another view to display the invoice numbers and the invoice totals for all invoices. Call
this view, invoice_totals_view. You can just display the invoice totals for each invoice in the line
table as an invoice with any sales will have to exist in the line table. No particular ordering is
required.

Your view should be based on the output below:

[HINT: Create the view from a select query that uses the GROUP BY clause with the sum
aggregate function].

4
You can check the contents of your view by using the select statement just like you would view
the contents of a table.

6. Write a query to display the information as shown in the output below. Use the invoice,
product and line tables to display the details for each customer code in the invoice table, as
follows:
a. The invoice number and invoice date (no particular formatting required)
b. the product description for the products associated with the respective invoice number
i. along with the line units and line price for that product.

Do not show the line total, just the line price. Order the information in the ascending order of
the customer code, then the invoice number and product description

Hint: One possible solution is to work with a Cartesian product of the respective tables with
the correct filter clauses using where.

For instance, you can start with the invoice table that would need to be matched with the
invoice numbers in the line table and then the product code from the line table matched
correctly with the product table etc.

7. Write a query to alter the view called Customer_View that you created earlier to now reflect all
the customers in the view with a balance of 0. Retain the aliases and columns used to create
Customer_View in question 4. Order the results by the full name in ascending order.

Hint: Use the Alter command

8. Recall that you had created a Customer2 table which was practically identical to the Customer
table in one of the previous labs.

You will write a select query that will combine the contents of both the tables. Do the union
such that the customer2 table details are appended to the bottom of the customer table.

5
No particular ordering is required.

Hint: Use the UNION keyword. See the syntax for doing unions with MySql.

9. Display all the customer details for all the customers who have a customer balance more than
the average customer balance but less than the maximum customer balance. Work with
subqueries. No particular ordering is required.

Hint: You can use queries to locate the average/max balances and then use those results to
work out all the customers within the required balance range.

10. For each invoice number in the line table, list its total sales if it is above $100. The total sales
for each invoice can be calculated as the sum of the line total (line units X line price) from each
entry for the specific invoice. Use the having clause in your solution. Order by the ascending
order of the Total_sales

You output should be similar to the one below:

11. List all the details of all the customers in the customer table whose customer codes are not
present in the invoice table. Order the results by the customer code in ascending order. Work
with the following in a sub query:
a. Distinct
b. NOT
c. IN

You should get an output similar to the one below:

12. Identify the list of all products that have not been sold with a price greater than $50. Display all
product details and sort them by their product code (ascending order). Your output should be
similar to the one below.

6
13. For each invoice in the invoice table, list the total number of products sold for that particular
invoice. If there aren’t any, indicate that as 0. Display the invoice number and the total number
of products sold for that invoice aliased as Total_Products. Sort by the ascending order of the
invoice number.

For instance, in the line table below, invoice 1004 has 2 entries in the table below. One entry
has 3 line units and the other 2, which makes a total of 5. So there were about 5 products
bought under that same invoice.

Your query’s output should be similar to the one below

Hint: Use LEFT JOIN and you can also use IFNULL in conjunction.

14. Try attempting question 13 with an inner join. Are you able to get the same result? Is it
appropriate to use an inner join in this case?

15. In a SQL database query, a correlated subquery is a subquery (a query nested inside another
query) that uses values from outer query. The subquery is evaluated once for each row
processed by the outer query

You will attempt one in this question.

7
Write a query to list for each customer the total number of invoices (aliased as Total_Invoices)
by using a correlated subquery. List all details of the customer.
Sort the results in ascending order of the customer code.

Write another query to list the same information without a correlated sub query for
comparison purposes only.

Your output should be similar to the one below:

16. Build on the previous query in q15 to list additional details by using correlated subqueries
again.

These additional details will be the total purchases by the relevant customer by summing the
total sales of all the invoices for the customer in a correlated subquery. This will be aliased as
Total_Purchases. If there are no purchases from a customer, show the total as 0.

List all details of the customer. Sort the results in ascending order of the customer code.

Write another query to list the same information without a correlated sub query for
comparison purposes only.

Your results should be similar to the output below:

17. Use the remainder of your time to complete all the join related queries from the previous lab,
Lab 8, (if you have not completed them or did not get them correct in the previous lab).

You might also like