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

324

Part III  •  Database Implementation and Use

process the inner query, return a result to the next outer can be used to create applications or to incorporate proce-
query, and then process that outer query. dures and functions using SQL data types directly. Trig-
Views are a mechanism that allows the creation of gers were also introduced in SQL:1999. It is important
virtual tables on the foundation of the base tables. Views to realize that many vendor-specific languages, such as
hide the actual database structure and provide a set of Oracle’s PL/SQL and Microsoft’s Transact-SQL, are dif-
user- or application-specific perspectives to a database, ferent from SQL/PSM and widely used.
simplifying the database from the users’ point of view This chapter also discusses new analytical capa-
and enhancing both security and developer productivity. bilities introduced in SQL:2008, SQL:2011, and SQL:2016,
Other advanced SQL topics that were covered in including new statistical and mathematical functions,
this chapter include the use of triggers and routines. Trig- data types, and processing features. In addition, new
gers are user-defined functions that run automatically temporal features of SQL:2011 and new dynamic capa-
when specific conditions are fulfilled at the time when bilities of SQL:2016 were discussed.
records are inserted, updated, or deleted. Procedures are In sum, this chapter has introduced foundational
user-defined code modules that must be explicitly called and advanced concepts related to multiple-table SQL
for them to execute. SQL:1999 introduced capabilities queries and subqueries. It has also reviewed the recent
that made SQL computationally complete, including flow extensions to SQL and the complex and extended capa-
control capabilities in a set of SQL specifications known bilities of SQL that must be mastered to build database
as Persistent Stored Modules (SQL/PSM). SQL/PSM application programs.

Chapter Review

Key Terms
Base table 309 Function 317 Outer join 289 Trigger 313
Correlated subquery 299 Join 286 Persistent Stored Modules User-defined data type 321
Dynamic view 309 Materialized view 309 (SQL/PSM) 316 Virtual table 309
Equi-join 287 Natural join 288 Procedure 317

Review Questions
6-1. Define each of the following terms: 6-5. What are some of the purposes for which you would use
a. dynamic view correlated subqueries?
b. correlated subquery 6-6. Explain the relationship between EXISTS and correlated
c. materialized view subqueries.
d. base table 6-7. Explain the following statement regarding SQL: Any
e. join query that can be written using the subquery approach
f. equi-join can also be written using the joining approach but not
g. self join vice versa.
h. outer join 6-8. Explain how to combine queries using the UNION clause.
i. virtualized table 6-9. Explain some possible purposes of creating a view using
6-2. Match the following terms to the appropriate definition: SQL. In particular, explain how a view can be used to rein-
           equi-join a. returns all records of designated force data security.
table 6-10. Explain why it is necessary to limit the kinds of updates
           derived table b. keeps redundant columns performed on data when referencing data through a
           natural join c. utilizes values from main query view.
in the subquery 6-11. When should we use joining and sub-query techniques?
           correlated d. outcome of a query embedded in 6-12. Explain the purpose of the WITH CHECK OPTION in a
subquery the FROM clause CREATE VIEW SQL command.
           outer join e. a set of SQL statements executed 6-13. Explain the use of derived tables.
under specific conditions 6-14. Describe an example in which you would want to use a
           trigger f. does not keep redundant columns derived table.
6-3. Discuss the differences between an equi-join, natural join, 6-15. Why is it not possible to update a base table via update
and outer join. commands against a view?
6-4. When is it better to use a subquery instead of a join? 6-16. What can Persistent Stored Modules be used for?
6-17. Explain three procedures to enforce data integrity.

M06_HOFF3359_13_GE_C06.indd 324 23/02/19 1:01 PM


6  •  Advanced SQL     325

6-18. Discuss the differences between triggers and stored proce- 6-23. Discuss the new commands that have been incorporated
dures. into SQL2007 and SQL2016, and identify the commands
6-19. Provide three reasons for embedding SQL in a 3GL. they have replaced in previous versions of SQL.
6-20. What are the potential security implications of using 6-24. Research a NoSQL database such as MondoDB or Fire-
embedded or dynamic SQL? base. Why is it important to consider a metadata-based
6-21. What is the purpose of the temporal extensions to SQL schema when working with NoSQL databases?
that were introduced in SQL:2011?
6-22. What are the key new features of SQL introduced in
SQL:2016?

Problems and Exercises


Problems and Exercises 6-25 through 6-30 are based on the class sched- 6-26. Write SQL retrieval commands for each of the following
ule 3NF relations along with some sample data in Figure 6-15. For queries:
Problems and Exercises 6-25 through 6-30, draw a Venn or ER diagram a. Display the course ID and course name for all courses
and mark it to show the data you expect your query to use to produce with an ISM prefix.
the results. This problem set continues from Chapter 5, Problems and b. Display the numbers and names of all courses for
Exercises 5-34 through 5-45, which were based on Figure 5-11. which Professor Berndt has been qualified.
6-25. Write an SQL query to answer the following question: c. Display the class roster, including student name, for all
Which instructors are qualified to teach ISM 3113? students enrolled in section 2714 of ISM 4212.

FIGURE 6-15  Class scheduling relations (for Problems and Exercises 6-25—6-30)

STUDENT (StudentID, StudentName) QUALIFIED (FacultyID, CourseID, DateQualified)

StudentID StudentName FacultyID CourseID DateQualified

38214 Letersky 2143 ISM 3112 9/2008


54907 Altvater 2143 ISM 3113 9/2008
66324 Aiken 3467 ISM 4212 9/2015
70542 Marra 3467 ISM 4930 9/2016
... 4756 ISM 3113 9/2011
4756 ISM 3112 9/2011
...

FACULTY (FacultyID, FacultyName) SECTION (SectionNo, Semester, CourseID)

FacultyID FacultyName SectionNo Semester CourseID

2143 Birkin 2712 I-2018 ISM 3113


3467 Berndt 2713 I-2018 ISM 3113
4756 Collins 2714 I-2018 ISM 4212
... 2715 I-2018 ISM 4930
...

COURSE (CourseID, CourseName) REGISTRATION (StudentID, SectionNo)

CourseID CourseName StudentID SectionNo

ISM 3113 Syst Analysis 38214 2714


ISM 3112 Syst Design 54907 2714
ISM 4212 Database 54907 2715
ISM 4930 Networking 66324 2713
... ...

M06_HOFF3359_13_GE_C06.indd 325 23/02/19 1:01 PM


326 Part III  •  Database Implementation and Use

6-27. Write an SQL query to answer the following question: Is 6-31. Determine the relationships among the four relations in
any instructor qualified to teach ISM 3113 and not quali- Figure 6-16. List primary keys for each relation and any
fied to teach ISM 4930? If yes, list the faculty ID and name foreign keys necessary to establish the relationships and
of the instructor. maintain referential integrity. Pay particular attention to
6-28. Write SQL queries to answer the following questions: the data contained in TUTOR REPORT when you set up
a. How many students were enrolled in section 2714 dur- its primary key.
ing semester I-2018? 6-32. Write the SQL command to add column MATH SCORE to
b. How many students were enrolled in ISM 3113 during the STUDENT table.
semester I-2018? 6-33. Write the SQL command to add column SUBJECT to
6-29. Write SQL queries to answer the following questions: TUTOR. The only values allowed for SUBJECT will be
a. What are the names of the course(s) that student Reading, Math, and ESL.
­Altvater took during the semester I-2018? 6-34. What do you need to do if a tutor signs up and wants
b. List the names of the students who have taken at least to tutor in both reading and math? Draw the new ERD,
one course that Professor Collins is qualified to teach. create new relations, and write any SQL statements that
c. List the names of the students who took at least one would be needed to handle this development.
course with “Syst” in its name during the semester 6-35. Write a SQL query to identify all students who have
I-2018. been matched in 2018 with a tutor whose status is Temp
d. How many students did Professor Collins teach during Stop.
the semester I-2018? 6-36. Write the SQL query to find any tutors who have not sub-
e. List the names of the courses that at least two faculty mitted a report for July.
members are qualified to teach. 6-37. Where do you think student and tutor information such
6-30. Write an SQL query to answer the following questions: as name, address, phone, and e-mail should be kept?
a. Which students were not enrolled in any courses Write the necessary SQL commands to capture this infor-
­during semester I-2018? mation.
b. Which faculty members are not qualified to teach any 6-38. Write an SQL query to determine the total number of
courses? hours and the total number of lessons Tutor 106 taught in
Problems and Exercises 6-31 through 6-44 are based on Figure 6-16. June and July 2018.
This problem set continues from C
­ hapter 5, Problems and Exercises 6-39. Write an SQL query to list the Read scores of students who
5-46 through 5-56, which were based on Figure 5-12. were ever taught by tutors whose status is Dropped.

FIGURE 6-16  Adult literacy program (for Problems and Exercises 6-31—6-44)

TUTOR (TutorID, CertDate, Status)


MATCH HISTORY (MatchID, TutorID, StudentID,
TutorID CertDate Status
StartDate, EndDate)
100 1/05/2018 Active MatchID TutorID StudentID StartDate EndDate
101 1/05/2018 Temp Stop 1 100 3000 1/10/2018
102 1/05/2018 Dropped
103 5/22/2018 Active
2 101 3001 1/15/2018 5/15/2018
104 5/22/2018 Active
3 102 3002 2/10/2018 3/01/2018
105 5/22/2018 Temp Stop
4 106 3003 5/28/2018
106 5/22/2018 Active

5 103 3004 6/01/2018 6/15/2018


STUDENT (StudentID, Group, Read)
6 104 3005 6/01/2018 6/28/2018
StudentID Group Read 7 104 3006 6/01/2018
3000 3 2.3
3001 2 5.6
3002 3 1.3 TUTOR REPORT (MatchID, Month, Hours, Lessons)
3003 1 3.3
MatchID Month Hours Lessons
3004 2 2.7
1 6/18 8 4
3005 4 4.8
4 6/18 8 6
3006 3 7.8
5 6/18 4 4
3007 4 1.5
4 7/18 10 5
1 7/18 4 2

M06_HOFF3359_13_GE_C06.indd 326 23/02/19 1:01 PM


6  •  Advanced SQL     327

6-40. List all active students in June by name. (Make up names 6-57. For every order that has been received, display the order
and other data if you are actually building a prototype ID, the total dollar amount owed on that order (you’ll
database.) Include the number of hours students received have to calculate this total from attributes in one or more
tutoring and how many lessons they completed. tables; label this result TotalDue), and the amount received
6-41. For each student group, list the number of tutors who in payments on that order (assume that there is only one
have been matched with that group. payment made on each order). To make this query a little
6-42. List the total number of lessons taught in 2018 by tutors in simpler, you don’t have to include those orders for which
each of the three Status categories (Active, Temp Stop, and no payment has yet been received. List the results in
Dropped). decreasing order of the difference between total due and
6-43. Which tutors, by name, are available to tutor? Write the amount paid.
SQL query. 6-58. Write an SQL query to list each customer who has bought
6-44. Which tutor needs to be reminded to turn in reports? computer desks and the number of units sold to each cus-
Write the SQL query. Show how you constructed this tomer. Show how you constructed this query using a Venn
query using a Venn or other type of diagram. or other type of diagram.
6-59. Write an SQL query to list each customer who bought at
Problems and Exercises 6-45 least one product that belongs to product line Basic in
through 6-85 are based on the March 2018. List each customer only once.
entire (“big” ­version) Pine Val- 6-60. Modify Problem and Exercise 6-59 so that you include
ley Furniture Company data- the number of products in product line Basic that the cus-
base. Note: Depending on what tomer ordered in March 2018.
DBMS you are using, some field names may have changed to avoid 6-61. Modify Problem and Exercise 6-60 so that the list includes
conflicting with reserved words for the DBMS. When you first use the the number of products each customer bought in each
DBMS, check the table definitions to see what the field names are for product line in March 2018.
the DBMS you are using. See the Preface and inside ­covers of this book 6-62. List, in alphabetical order, the names of all employees
for instructions on where to find this database, including on www. (managers) who are now managing people with skill ID
teradatauniversitynetwork.com. BS12; list each manager’s name only once, even if that
6-45. Write an SQL query that will find any customers who manager manages several people with this skill.
have not placed orders. 6-63. Display the salesperson name, product finish, and total
6-46. Write an SQL query to list all product line names and, for quantity sold (label as TotSales) for each finish by each
each product line, the number of products and the aver- salesperson.
age product price. Make sure to include all product lines 6-64. Write a query to list the number of products produced in
separately. each work center (label as TotalProducts). If a work center
6-47. Modify P&E 6-46 to include only those product lines the does not produce any products, display the result with a
average price of which is higher than $200. total of 0.
6-48. List the names and number of employees supervised 6-65. The production manager at PVFC is concerned about sup-
(label this value HeadCount) for each supervisor who port for purchased parts in products owned by custom-
supervises more than two employees. ers. A simple analysis he wants done is to determine for
6-49. List the name of each employee, his or her birth date, the each customer how many vendors are in the same state as
name of his or her manager, and the manager’s birth date that customer. Develop a list of all the PVFC customers by
for those employees who were born before their man- name with the number of vendors in the same state as that
ager was born; label the manager’s data Manager and customer. (Label this computed result NumVendors.)
ManagerBirth. Show how you constructed this query 6-66. Display the order IDs for customers who have not made
using a Venn or other type of diagram. any payment, yet, on that order. Use the set command
6-50. Write an SQL query to display the order number, customer UNION, INTERSECT, or MINUS in your query.
number, order date, and items ordered for some particular 6-67. Display the names of the states in which customers reside
customer. but for which there is no salesperson residing in that state.
6-51. Write an SQL query to display each item ordered for order There are several ways to write this query. Try to write it
number 1, its standard price, and the total price for each without any WHERE clause. Write this query two ways,
item ordered. using the set command UNION, INTERSECT, or MINUS
6-52. Write an SQL query to display the total number of employ- and not using any of these commands. Which was the
ees working at each work center (include ID and location most natural approach for you, and why?
for each work center). 6-68. Write an SQL query to produce a list of all the products
6-53. Write an SQL query that lists those work centers that (i.e., product description) and the number of times each
employ at least one person who has the skill ‘QC1’. product has been ordered. Show how you constructed this
6-54. Write an SQL query to total the cost of order number 1. query using a Venn or other type of diagram.
6-55. Write an SQL query that lists for each vendor (including 6-69. Display the customer ID, name, and order ID for all cus-
vendor ID and vendor name) those materials that the ven- tomer orders. For those customers who do not have any
dor supplies where the supply unit prices is at least four orders, include them in the display once.
times the material standard price. 6-70. Display the EmployeeID and EmployeeName for those
6-56. Calculate the total raw material cost (label TotCost) for employees who do not possess the skill Router. Display
each product compared to its standard product price. the results in order by EmployeeName. Show how you
Display product ID, product description, standard price, constructed this query using a Venn or other type of dia-
and the total cost in the result. gram.

M06_HOFF3359_13_GE_C06.indd 327 23/02/19 1:01 PM


328 Part III  •  Database Implementation and Use

6-71. Display the name of customer 16 and the names of all the 6-84. The head of marketing is interested in some opportunities
customers that are in the same zip code as customer 16. for cross-selling of products. She thinks that the way to iden-
(Be sure this query will work for any customer.) tify cross-selling opportunities is to know for each product
6-72. Rewrite your answer to Problem and Exercise 6-71 for how many other products are sold to the same customer on
each customer, not just customer 16. the same order (e.g., a product that is bought by a customer
6-73. Display the customer ID, name, and order ID for all cus- in the same order with lots of other products is a better can-
tomer orders. For those customers who do not have any didate for cross-selling than a product bought by itself).
orders, include them in the display once by showing order a. To help the marketing manager, first list the IDs for all
ID 0. the products that have sold in total more than 20 units
6-74. Show the customer ID and name for all the customers across all orders. (These are popular products, which
who have ordered both products with IDs 3 and 4 on the are the only products she wants to consider as triggers
same order. for potential cross-selling.)
6-75. Display the customer names of all customers who have b. Make a new query that lists all the IDs for the orders
ordered (on the same or different orders) both products that include products that satisfy the first query, along
with IDs 3 and 4. with the number of products on those orders. Only
6-76. Write an SQL query that lists the vendor ID, vendor name, orders with three or more products on them are of inter-
material ID, material name, and supply unit prices for all est to the marketing manager. Write this query as gen-
those materials that are provided by more than one vendor. eral as possible to cover any answer to the first query,
6-77. Review the first query in the “Correlated Subqueries” sec- which might change over time. To clarify, if product X
tion. Can you identify a special set of standard prices for is one of the products that is in the answer set from part
which this query will not yield the desired result? How a, then in part b we want to see the desired order infor-
might you rewrite the query to handle this situation? mation for orders that include product X.
6-78. List the IDs and names of all products that cost less than c. The marketing manager needs to know what other
the average product price in their product line. products were sold on the orders that are in the result
6-79. List the IDs and names of those sales territories that have for part b. (Again, write this query for the general, not
at least 50 percent more customers as the average number specific, result to the query in part b.) These are prod-
of customers per territory. ucts that are sold, for example, with product X from
6-80. Write an SQL query to list the order number, product ID, part a, and these are the ones that if people buy that
and ordered quantity for all ordered products for which product, we’d want to try to cross-sell them product X
the ordered quantity is greater than the average ordered because history says they are likely to buy it along with
quantity for that product. what else they are buying. Write a query to identify
6-81. Write an SQL query to list the salesperson who has sold these other products by ID and description. It is okay
the most computer desks. to include “product X” in your result (i.e., you don’t
6-82. Display in product ID order the product ID and total need to exclude the products in the result of part a).
amount ordered of that product by the customer who has 6-85. For each product, display in ascending order, by product
bought the most of that product; use a derived table in a ID, the product ID and description, along with the cus-
FROM clause to answer this query. tomer ID and name for the customer who has bought the
6-83. Display employee information for all the employees in most of that product; also show the total quantity ordered
each state who were hired before the most recently hired by that customer (who has bought the most of that prod-
person in that state. uct). Use a correlated subquery.

Field Exercises
6-86. Conduct a Web search on security issues relating to poorly five similarities and three dissimilarities in the SQL code
designed SQL. Identify the most common ones and sug- from these two SQL systems. Do the dissimilarities cause
gest what measures can be taken to address them. results to differ?
6-87. Compare two versions of SQL to which you have access,
such as Microsoft Access and Oracle. Identify at least

References
American National Standards Institute. 2016. “New Edition of Record 33,1 (March): 119–26.
Database Language SQL Standard Published.” Available at Gulutzan, P., and T. Pelzer. 1999. SQL-99 Complete, Really!
https://share.ansi.org/Shared%20Documents/News%20 ­Lawrence, KS: R&D Books.
and%20Publications/Links%20Within%20Stories/SQL%20 Gulutzan, P., and T. Pelzer. 2002. SQL Performance Tuning.
standard%20published_POST.pdf. Reading, MA: Addison-Wesley.
DeLoach, A. 1987. “The Path to Writing Efficient Queries in SQL/ Gulutzan, P. 2017. “The SQL Standard is SQL:2016.” Available
DS.” Database Programming & Design 1,1 (January): 26–32. at www.dataarchitect.cloud/the-sql-standard-is-sql2016.
Eisenberg, A., J. Melton, K. Kulkarni, J. E. Michels, and F. Holmes, J. 1996. “More Paths to Better Performance.” Database
Zemke. 2004. “SQL:2003 Has Been Published.” SIGMOD Programming & Design 9,2 (February): 47–48.

M06_HOFF3359_13_GE_C06.indd 328 23/02/19 1:01 PM


6  •  Advanced SQL     329

Kulkarni, K., and J-E. Michels. 2012. “Temporal Features in PSM.” Available at www.abis.be/html/en2012-10_MySQL_
SQL:2011.” SIGMOD Record 41,3: 34–43. procedures.html.
Mullins, C. S. 1995. “The Procedural DBA.” Database Program- Zemke, F. 2012. “What’s New in SQL:2011.” SIGMOD Record
ming & Design 8,12 (December): 40–45. 41,1: 67–73.
Rennhackkamp, M. 1996. “Trigger Happy.” DBMS 9,5 (May): Zemke, F., K. Kulkarni, A. Witkowski, and B. Lyle. 1999. “Intro-
89–91, 95. duction to OLAP Functions.” ISO/IEC JTC1/SC32 WG3:
Vanroose, P. 2012. “MySQL: Stored Procedures and SQL/ YGJ.068 ANSI NCITS H2–99–154r2.

Further Reading
American National Standards Institute. 2000. ANSI Standards Itzik, B., A. Machanic, D. Sarka, and K. Farlee. 2015. T-SQL
Action 31,11 (June 2): 20. Querying. Redmond, WA: Microsoft Press.
Celko, J. 2006. Analytics and OLAP in SQL. San Francisco: Itzik B., D. Sarka, and R. Wolter. 2010. Inside Microsoft SQL
­Morgan Kaufmann. Server 2008: T-SQL Programming. Redmond, WA: Microsoft
Codd, E. F. 1970. “A Relational Model of Data for Large Press.
Shared Data Banks.” Communications of the ACM 13,6 Kulkarni, K. 2004. “Overview of SQL:2003.” Available at www
(June): 77–87. .wiscorp.com/SQLStandards.html#keyreadings.
Date, C. J., and H. Darwen. 1997. A Guide to the SQL Standard. Melton, J. 1997. “A Case for SQL Conformance Testing.” Data-
Reading, MA: Addison-Wesley. base Programming & Design 10,7 (July): 66–69.
Date, C. J., and H. Darwen. 2014. Time and Relational Theory. van der Lans, R. F. 2006. Introduction to SQL. 4th ed.
Temporal Databases in the Relational Model and SQL. Waltham, ­Workingham: Addison-Wesley.
MA: Morgan Kaufmann. Winter, R. 2000. “SQL-99’s New OLAP Functions.” Intelligent
Fehily, C. 2015. SQL Database Programming. Pacific Grove, CA: Enterprise 3,2 (January 20): 62, 64–65.
Questing Vole Press. Winter, R. 2000. “The Extra Mile.” Intelligent Enterprise 3,10
Helland, P. 2016. “The Singular Success of SQL.” Communica- (June 26): 62–64.
tions of the ACM 59,8 (August): 38–41. See also “Further Reading” in Chapter 5.

Web Resources
www.ansi.org Web site of the American National Standards http://standards.ieee.org The home page of the IEEE standards
Institute. Contains information on the ANSI federation and organization.
the latest national and international standards. www.tizag.com/sqlTutorial Web site that provides a set of
www.fluffycat.com/SQL Web site that defines a sample database tutorials on SQL concepts and commands.
and shows examples of SQL queries against this d­ atabase. http://troelsarvin.blogspot.com Blog that provides a
www.iso.ch The International Organization for Standardiza- detailed comparison of different SQL implementations,
tion’s (ISO’s) Web site, which provides information about the including DB2, Microsoft SQL, MySQL, Oracle, and Post-
ISO. Copies of current standards may be purchased here. GreSQL
www.khanacademy.org/computing/computer-programming/sql www.teradatauniversitynetwork.com Web site where your
An SQL tutorial section of a well-known educational resource instructor may have created some course environments for
site in mathematics, science, computing, and other fields. you to use Teradata SQL Assistant, Web Edition, with one or
https://richardfoote.wordpress.com A Web site with expert more of the Pine Valley Furniture and Mountain View Com-
commentary particularly on issues related to indexing. munity Hospital data sets for this text.
www.sqlcourse.com and www.sqlcourse2.com Web sites that www.w3schools.com/SQL/deFault.asp Comprehensive SQL
provide tutorials for a subset of ANSI SQL with a practice tutorials by offered by W3schools.com.
database.

M06_HOFF3359_13_GE_C06.indd 329 23/02/19 1:01 PM


330 Part III  •  Database Implementation and Use

CASE
Forondo Artist Management Excellence Inc.

Case Description specify for which reports or displays you should write
queries, how many queries you are to write, and their
In Chapter 5, you implemented the database for FAME and
complexity.
populated it with sample data. You will use the same database
6-89. Identify opportunities for using triggers in your data-
to complete the exercises below.
base and write the appropriate DDL queries for them.
6-90. Create a strategy for reviewing your database imple-
Project Questions
mentation with the appropriate stakeholders. Which
6-88. Write and execute queries for the various reports and stakeholders should you meet with? What information
displays you identified as being required by the vari- would you bring to this meeting? Who do you think
ous stakeholders in 5-98 in Chapter 5. Make sure you should sign off on your database implementation before
use both subqueries and joins. Your instructor may you move to the next phase of the project?

M06_HOFF3359_13_GE_C06.indd 330 23/02/19 1:01 PM

You might also like