erc4 - pudn.comread.pudn.com/downloads138/ebook/592377/cf134xs0.pdf · aix as/400 bookmaster...

102
DB2 SQL Workshop for Experienced Users (Course Code CF13) Student Exercises ERC4.1 IBM Learning Services Worldwide Certified Material

Upload: others

Post on 11-Mar-2020

13 views

Category:

Documents


0 download

TRANSCRIPT

DB2 SQL Workshopfor Experienced Users(Course Code CF13)

Student ExercisesERC4.1

IBM Learning ServicesWorldwide Certified Material

Student Exercises

Publishing Information

This publication has been produced using BookMaster (Program Number5668-015), the Document Composition Facility (Program Number 5748-XX9), andFreelance for Windows. It was printed on the IBM 3820 Page Printer.

Trademarks

IBM is a registered trademark of International Business Machines Corporation.

The following are trademarks International Business Machines Corporation in theUnited States, or other countries, or both:

Freelance Graphics and Lotus are trademarks of Lotus Development Corporation inthe United States, or other countries, or both.

Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in theUnited States, other countries, or both.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of MicrosoftCorporation in the United States, other countries, or both.

Intel is a registered trademark of Intel Corporation in the United States, othercountries, or both.

UNIX is a registered trademark in the United States and other countries licensedexclusively through The Open Group.

Linux is a trademark of Linus Torvalds.

Other company, product, and service names may be trademarks or service marks ofothers.

AIXAS/400BookMasterDataJoiner

DB2DB2 Universal DatabaseOS/2

OS/390OS/400QMFSQL/DS

January, 2001

The information contained in this document has not been submitted to any formal IBM test and isdistributed on an “as is” basis without any warranty either express or implied. The use of thisinformation or the implementation of any of these techniques is a customer responsibility and dependson the customer's ability to evaluate and integrate them into the customer's operational environment.While each item may have been reviewed by IBM for accuracy in a specific situation, there is noguarantee that the same or similar results will result elsewhere. Customers attempting to adapt thesetechniques to their own environments do so at their own risk. The original repository material for thiscourse has been certified as being Year 2000 compliant.

Copyright International Business Machines Corporation 1998, 2001. All rights reserved.This document may not be reproduced in whole or in part without the prior written permission of IBM.Note to U.S. Government Users — Documentation related to restricted rights — Use, duplication ordisclosure is subject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp.

Student Exercises

Contents

Exercises Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v

Table Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Table Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

Exercises

Exercise 1. SQL Basics Review, CUBE AND ROLLUP . . . . . . . . . . . . . . . . . . . . 1-1

Exercise 2. Create Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1

Exercise 3. Joins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1

Exercise 4. CASE and CAST . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1

Exercise 5. Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1

Exercise 6. Scalar Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1

Exercise 7. Table Expressions and Recursive SQL . . . . . . . . . . . . . . . . . . . . . . 7-1

Exercise 8. Performance and UDT/UDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1

Contents iii Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

iv DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercises Description

Be sure to read the General Information section and thedescription of the lab tables before attempting the exercises.

Feel free to consult with the instructor if you need a hint orencounter difficulties while you are formulating the query.

Expected Results — repeats the problem and shows the resultsthat you should get if you run the query. In most cases, thecomplete result is shown. In cases where the result set is toolarge, an ellipsis (...) is shown to indicate that there are additionalrows in the result. In these cases, the correct number of rows forthe result set is shown so that you can be sure that you got theright result.

Solutions — contains the correct query that solves the problem.Remember that sometimes there can be several correct answers.Your solution may be different than the one shown in thedocument. If you have any doubts about whether your solution iscorrect or if it is as good as the given solution from a performancepoint of view, please consult your instructor.

General Information

This lab guide provides the information necessary to complete therequired and optional labs for the IBM DB2 SQL Workshop forExperienced Users course.

In countries that provide several query tools for each environment,this lab guide will be supplemented by additional documentationthat describes the basics of each query tool.

You can do the exercises for this course in OS/390 or in aWorkstation environment. Depending on where you are taking thecourse, these Workstation platforms may be available for your use:OS/2, AIX, Windows 95/98 or Windows NT. Be sure to read theinstructions for the operating system you chose before attemptingthe exercises. All of the workstation platforms use the sameinstructions.

You will be able to use any of the query tools that we haveinstalled on each operating system. Please note that the emphasisof this course is on teaching you SQL, not how to use the tools.Therefore, you will only see the basics of using the tool in thiscourse. If you want more information about these tools, ask theinstructor for recommendations on the best manuals to read orcourses to take for this purpose.

Exercises Description v Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

You do not need to save your solutions or show them to theinstructor but feel free to do so if you like.

Full solutions are provided for every question but if you wish tosave your own solutions to diskette or print them, ask yourinstructor when you begin the first exercise . In some cases,diskettes or printers may not be available.

vi DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

General Information for OS/390 Users

There are many different query tools that work with DB2 forOS/390, including SPUFI, QMF, and others. You can use any toolinstalled to do the labs. The following query tools are available forthis course:

__________________________

__________________________

__________________________

The instructor will tell you how to logon to the OS/390 system andwhat specific user ID and password to use. In addition, you willprobably be given a team number: this number will be usedoccasionally during the exercises so that you can distinguish yourfiles or objects from those of other students.

Your logon ID is __________________________________________.

Your password is __________________________________________.

Your team number is _______________________________________.

The instructor will give you brief verbal or written instructions onhow to use the tool you choose so that you will have enoughinformation to get started. If you want to know more about a tool,for example how to save a query, be sure to ask the instructor.

You will need a partitioned dataset in order to complete theexercises. This dataset already exists.

The dataset name is ________________________________________.

Each of the tables described in the Table Relationships section ofthis document already exists and has the same qualifier.

The qualifier is _______________.

When you refer to these tables in your SQL, you will need to prefixthe table names with the qualifier identified above. For example, ifyou want to display the complete contents of the EMPLOYEE table,enter the following, substituting the qualifier you were given:

SELECT * FROM qualifier .EMPLOYEE

Note: Using member CRTAB to create table TESTEMP, if the tablehas not been provided in advance. You may need to add an INclause to your CREATE TABLE statements that identifies where thetable is being created. The IN clause you need to add is:

IN _________________________________.

Exercises Description vii Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

When you are using the TESTEMP table, you will have to omit thequalifier or use your logon ID as qualifier. For example, if you aretrying to read the TESTEMP table, you will have to write:

SELECT * FROM TESTEMPor SELECT * FROM logon ID .TESTEMP

You do not have to save your SQL but if you want to save it, youmay put it in your partitioned dataset.

viii DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

General Information for DB2 UDB on UNIX, Windows and OS/2 Users

There are many different query tools that work with DB2 on theworkstation platforms, including Command Center, CLP, andothers. You can use any tool installed to do the labs. Thefollowing query tools are available for this course:

__________________________

__________________________

__________________________

Students doing the exercises on workstation platforms do not needa team number. Each workstation student has a completestandalone environment and will not share any files or tables withother students. Each student will have to sign on with thefollowing information:

USERID is _____________________

PASSWORD is ____________________

The instructor will give you brief verbal or written instructions onhow to use the tool you choose so that you have enoughinformation to get started. If you want to know more about a tool,for example how to save a query, be sure to ask the instructor.

A database named sample has already been created for you.

To connect in a single-user environment, enter the following ata command prompt:

db2 connect to sample

To connect in a client/server environment, enter the followingat a command prompt, substituting the userid and passwordyou were assigned:

db2 connect to sample user userid using password

Each of the tables described in the Table Relationships section ofthis document already exists and has the same qualifier.

The qualifier is _________________.

When you refer to these tables in your SQL, you will need to prefixthe table names with the qualifier identified above. For example, ifyou want to display the complete contents of the EMPLOYEE table,enter the following, substituting the qualifier you were given:

SELECT * FROM qualifier .EMPLOYEE

Exercises Description ix Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Note: Using member CRTAB to create table TESTEMP, if the tablehas not been provided in advance. Using the following commandto create table TESTEMP:

DB2 -tvf CRTAB

In cases where you are using your TESTEMP table you need toomit the qualifier or use your logon ID as qualifier. For example, ifyou are trying to read the TESTEMP table, you will need to write:

SELECT * FROM TESTEMPor SELECT * FROM logon ID .TESTEMP

If you choose to do the labs in CLP, you may create your SQL inthe \CF13 directory.

x DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Figure 0-1. Table Relationships (CF13X010)

Notes:: This diagram illustrates the relationships between the tables used in theexercises for this course. The lines show the connection between the tables.

Exercises Description xi Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

xii DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Table Descriptions

The tables are described in hierarchical order, as shown in the Table Relationships onthe previous page.

DEPARTMENT

There is one row in the DEPARTMENT table for each department in the company.

EMPLOYEE

There is one row in the EMPLOYEE table for each of the employees in the company.

Column Name Meaning Data Type NULLS allowedDEPTNO Department Number CHAR(3) NDEPTNAME Department Name VARCHAR(36) NMGRNO Employee Number of the Responsible

ManagerCHAR(6) Y

ADMRDEPT Department Number of theDepartment to which the Departmentreports

CHAR(3) N

LOCATION Location Number CHAR(5) Y

Column Name Meaning Data Type NULLS allowedEMPNO Employee Number CHAR(6) NFIRSTNME First Name VARCHAR(20) NMIDINIT Middle Initial CHAR(1) NLASTNAME Last Name VARCHAR(15) NWORKDEPT Department in which the Employee

WorksCHAR(3) Y

PHONENO Phone Number CHAR(4) YHIREDATE Date of Hire DATE YJOB Job CHAR(8) YEDLEVEL Number of Years of Formal Education SMALLINT YSEX Sex (M male, F female) CHAR(1) YBIRTHDATE Date of Birth DATE YSALARY Yearly Salary DECIMAL(9, 2) YBONUS Yearly Bonus DECIMAL(9, 2) YCOMM Yearly Commission DECIMAL(9, 2) Y

Table Descriptions xiii Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

PROJECT

There is one row in the PROJECT table for each project.

EMP_ACT

There are many rows in the EMP_ACT table for any employee or any project.

Column Name Meaning Data Type NULLS allowedPROJNO Project Number CHAR(6) NPROJNAME Project Name VARCHAR(24) NDEPTNO Responsible Department CHAR(3) NRESPEMP Employee Number of the Responsible

EmployeeCHAR(6) N

PRSTAFF Estimated Mean Staffing DECIMAL(5, 2) YPRSTDATE Estimated Start Date DATE YPRENDATE Estimated End Date DATE YMAJPROJ Major Project for a Subproject CHAR(6) Y

Column Name Meaning Data Type NULLS allowedEMPNO Employee Number of Employee

Performing the ActivityCHAR(6) N

PROJNO Project Number CHAR(6) NACTNO Activity Number SMALLINT NEMPTIME Proportion of Employee's Time Spent

on ProjectDECIMAL(5, 2) Y

EMSTDATE Date Activity Starts DATE YEMENDATE Date Activity Ends DATE Y

xiv DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Table Content

DEPARTMENT Table

DEPTNO DEPTNAME MGRNO ADMRDEPT LOCATION------ ------------------------------ ------ -------- --------A00 SPIFFY COMPUTER SERVICE DIV. 000010 A00B01 PLANNING 000020 A00C01 INFORMATION CENTER 000030 A00D01 DEVELOPMENT CENTER - A00D11 MANUFACTURING SYSTEMS 000060 D01D21 ADMINISTRATION SYSTEMS 000070 D01E01 SUPPORT SERVICES 000050 A00E11 OPERATIONS 000090 E01E21 SOFTWARE SUPPORT 000100 E01

Table Content xv Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

EMPLOYEE Table

EMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO HIREDATE------ ---------- ------- ---------- -------- ------- ----------000010 CHRISTINE I HAAS A00 3978 1965-01-01000020 MICHAEL L THOMPSON B01 3476 1973-10-10000030 SALLY A KWAN C01 4738 1975-04-05000050 JOHN B GEYER E01 6789 1949-08-17000060 IRVING F STERN D11 6423 1973-09-14000070 EVA D PULASKI D21 7831 1980-09-30000090 EILEEN W HENDERSON E11 5498 1970-08-15000100 THEODORE Q SPENSER E21 0972 1980-06-19000110 VINCENZO G LUCCHESI A00 3490 1958-05-16000120 SEAN O'CONNELL A00 2167 1963-12-05000130 DOLORES M QUINTANA C01 4578 1971-07-28000140 HEATHER A NICHOLLS C01 1793 1976-12-15000150 BRUCE ADAMSON D11 4510 1972-02-12000160 ELIZABETH R PIANKA D11 3782 1977-10-11000170 MASATOSHI J YOSHIMURA D11 2890 1978-09-15000180 MARILYN S SCOUTTEN D11 1682 1973-07-07000190 JAMES H WALKER D11 2986 1974-07-26000200 DAVID BROWN D11 4501 1966-03-03000210 WILLIAM T JONES D11 0942 1979-04-11000220 JENNIFER K LUTZ D11 0672 1968-08-29000230 JAMES J JEFFERSON D21 4265 1966-11-21000240 SALVATORE M MARINO D21 3780 1979-12-05000250 DANIEL S SMITH D21 0961 1969-10-30000260 SYBIL V JOHNSON D21 8953 1975-09-11000270 MARIA L PEREZ D21 9001 1980-09-30000280 ETHEL R SCHNEIDER E11 8997 1967-03-24000290 JOHN R PARKER E11 4502 1980-05-30000300 PHILIP X SMITH E11 2095 1972-06-19000310 MAUDE F SETRIGHT E11 3332 1964-09-12000320 RAMLAL V MEHTA E21 9990 1965-07-07000330 WING LEE E21 2103 1976-02-23000340 JASON R GOUNOT E21 5698 1947-05-05

xvi DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

EMPLOYEE Table (Cont)

JOB EDLEVEL SEX BIRTHDATE SALARY BONUS COMM--------- ------- --- ---------- --------- -------- --------PRES 18 F 1933-08-14 52750.00 1000.00 4220.00MANAGER 18 M 1948-02-02 41250.00 800.00 3300.00MANAGER 20 F 1941-05-11 38250.00 800.00 3060.00MANAGER 16 M 1925-09-15 40175.00 800.00 3214.00MANAGER 16 M 1945-07-07 32250.00 600.00 2580.00MANAGER 16 F 1953-05-26 36170.00 700.00 2893.00MANAGER 16 F 1941-05-15 29750.00 600.00 2380.00MANAGER 14 M 1956-12-18 26150.00 500.00 2092.00SALESREP 19 M 1929-11-05 46500.00 900.00 3720.00CLERK 14 M 1942-10-18 29250.00 600.00 2340.00ANALYST 16 F 1925-09-15 23800.00 500.00 1904.00ANALYST 18 F 1946-01-19 28420.00 600.00 2274.00DESIGNER 16 M 1947-05-17 25280.00 500.00 2022.00DESIGNER 17 F 1955-04-12 22250.00 400.00 1780.00DESIGNER 16 M 1951-01-05 24680.00 500.00 1974.00DESIGNER 17 F 1949-02-21 21340.00 500.00 1707.00DESIGNER 16 M 1952-06-25 20450.00 400.00 1636.00DESIGNER 16 M 1941-05-29 27740.00 600.00 2217.00DESIGNER 17 M 1953-02-23 18270.00 400.00 1462.00DESIGNER 18 F 1948-03-19 29840.00 600.00 2387.00CLERK 14 M 1935-05-30 22180.00 400.00 1774.00CLERK 17 M 1954-03-31 28760.00 600.00 2301.00CLERK 15 M 1939-11-12 19180.00 400.00 1534.00CLERK 16 F 1936-10-05 17250.00 300.00 1380.00CLERK 15 F 1953-05-26 27380.00 500.00 2190.00OPERATOR 17 F 1936-03-28 26250.00 500.00 2100.00OPERATOR 12 M 1946-07-09 15340.00 300.00 1227.00OPERATOR 14 M 1936-10-27 17750.00 400.00 1420.00OPERATOR 12 F 1931-04-21 15900.00 300.00 1272.00FIELDREP 16 M 1932-08-11 19950.00 400.00 1596.00FIELDREP 14 M 1941-07-18 25370.00 500.00 2030.00FIELDREP 16 M 1926-05-17 23840.00 500.00 1907.00

Table Content xvii Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

PROJECT Table

DEPT PRPROJNO PROJNAME NO RESPEMP STAFF PRSTDATE PRENDATE MAJPROJ------ --------------------------------- ----- ---------- ---------- -------AD3100 ADMIN SERVICES D01 000010 6.50 1982-01-01 1983-02-01 -AD3110 GENERAL AD SYSTEMS D21 000070 6.00 1982-01-01 1983-02-01 AD3100AD3111 PAYROLL PROGRAMMING D21 000230 2.00 1982-01-01 1983-02-01 AD3110AD3112 PERSONNEL PROGRAMMG D21 000250 1.00 1982-01-01 1983-02-01 AD3110AD3113 ACCOUNT.PROGRAMMING D21 000270 2.00 1982-01-01 1983-02-01 AD3110IF1000 QUERY SERVICES C01 000030 2.00 1982-01-01 1983-02-01 -IF2000 USER EDUCATION C01 000030 1.00 1982-01-01 1983-02-01 -MA2100 WELD LINE AUTOMATION D01 000010 12.00 1982-01-01 1983-02-01 -MA2110 W L PROGRAMMING D11 000060 9.00 1982-01-01 1983-02-01 MA2100MA2111 W L PROGRAM DESIGN D11 000220 2.00 1982-01-01 1982-12-01 MA2110MA2112 W L ROBOT DESIGN D11 000150 3.00 1982-01-01 1982-12-01 MA2110MA2113 W L PROD CONT PROGS D11 000160 3.00 1982-02-15 1982-12-01 MA2110OP1000 OPERATION SUPPORT E01 000050 6.00 1982-01-01 1983-02-01 -OP1010 OPERATION E11 000090 5.00 1982-01-01 1983-02-01 OP1000OP2000 GEN SYSTEMS SERVICES E01 000050 5.00 1982-01-01 1983-02-01 -OP2010 SYSTEMS SUPPORT E21 000100 4.00 1982-01-01 1983-02-01 OP2000OP2011 SCP SYSTEMS SUPPORT E21 000320 1.00 1982-01-01 1983-02-01 OP2010OP2012 APPLICATIONS SUPPORT E21 000330 1.00 1982-01-01 1983-02-01 OP2010OP2013 DB/DC SUPPORT E21 000340 1.00 1982-01-01 1983-02-01 OP2010PL2100 WELD LINE PLANNING B01 000020 1.00 1982-01-01 1982-09-15 MA2100

xviii DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

EMP_ACT Table

EMPNO PROJNO ACTNO EMPTIME EMSTDATE EMENDATE------ ------ ------ -------- ---------- ----------000010 AD3100 10 0.50 1982-01-01 1982-07-01000070 AD3110 10 1.00 1982-01-01 1983-02-01000230 AD3111 60 1.00 1982-01-01 1982-03-15000230 AD3111 60 0.50 1982-03-15 1982-04-15000230 AD3111 70 0.50 1982-03-15 1982-10-15000230 AD3111 80 0.50 1982-04-15 1982-10-15000230 AD3111 180 1.00 1982-10-15 1983-01-01000240 AD3111 70 1.00 1982-02-15 1982-09-15000240 AD3111 80 1.00 1982-09-15 1983-01-01000250 AD3112 60 0.50 1982-02-01 1982-03-15000250 AD3112 60 1.00 1982-01-01 1982-02-01000250 AD3112 60 1.00 1983-01-01 1983-02-01000250 AD3112 60 0.50 1982-12-01 1983-01-01000250 AD3112 70 1.00 1982-03-15 1982-08-15000250 AD3112 70 0.50 1982-02-01 1982-03-15000250 AD3112 70 0.25 1982-08-15 1982-10-15000250 AD3112 80 0.25 1982-08-15 1982-10-15000250 AD3112 80 0.50 1982-10-15 1982-12-01000250 AD3112 180 0.50 1982-08-15 1983-01-01000260 AD3113 70 0.50 1982-06-15 1982-07-01000260 AD3113 70 1.00 1982-07-01 1983-02-01000260 AD3113 80 1.00 1982-01-01 1982-03-01000260 AD3113 80 0.50 1982-03-01 1982-04-15000260 AD3113 180 0.50 1982-03-01 1982-04-15000260 AD3113 180 0.50 1982-06-01 1982-07-01000260 AD3113 180 1.00 1982-04-15 1982-06-01000270 AD3113 60 0.25 1982-09-01 1982-10-15000270 AD3113 60 1.00 1982-04-01 1982-09-01000270 AD3113 60 0.50 1982-03-01 1982-04-01000270 AD3113 70 0.75 1982-09-01 1982-10-15000270 AD3113 70 1.00 1982-10-15 1983-02-01000270 AD3113 80 1.00 1982-01-01 1982-03-01000270 AD3113 80 0.50 1982-03-01 1982-04-01000030 IF1000 10 0.50 1982-06-01 1983-01-01000130 IF1000 90 1.00 1982-01-01 1982-10-01000130 IF1000 100 0.50 1982-10-01 1983-01-01000140 IF1000 90 0.50 1982-10-01 1983-01-01

Table Content xix Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

EMP_ACT Table (Cont)

EMPNO PROJNO ACTNO EMPTIME EMSTDATE EMENDATE------ ------ ------ -------- ---------- ----------000030 IF2000 10 0.50 1982-01-01 1983-01-01000140 IF2000 100 1.00 1982-01-01 1982-03-01000140 IF2000 100 0.50 1982-03-01 1982-07-01000140 IF2000 110 0.50 1982-03-01 1982-07-01000140 IF2000 110 0.50 1982-10-01 1983-01-01000010 MA2100 10 0.50 1982-01-01 1982-11-01000110 MA2100 20 1.00 1982-01-01 1982-03-01000010 MA2110 10 1.00 1982-01-01 1983-02-01000200 MA2111 50 1.00 1982-01-01 1982-06-15000200 MA2111 60 1.00 1982-06-15 1983-02-01000220 MA2111 40 1.00 1982-01-01 1983-02-01000150 MA2112 60 1.00 1982-01-01 1982-07-15000150 MA2112 180 1.00 1982-07-15 1983-02-01000170 MA2112 60 1.00 1982-01-01 1983-06-01000170 MA2112 70 1.00 1982-06-01 1983-02-01000190 MA2112 70 1.00 1982-02-01 1982-10-01000190 MA2112 80 1.00 1982-10-01 1983-10-01000160 MA2113 60 1.00 1982-07-15 1983-02-01000170 MA2113 80 1.00 1982-01-01 1983-02-01000180 MA2113 70 1.00 1982-04-01 1982-06-15000210 MA2113 80 0.50 1982-10-01 1983-02-01000210 MA2113 180 0.50 1982-10-01 1983-02-01000050 OP1000 10 0.25 1982-01-01 1983-02-01000090 OP1010 10 1.00 1982-01-01 1983-02-01000280 OP1010 130 1.00 1982-01-01 1983-02-01000290 OP1010 130 1.00 1982-01-01 1983-02-01000300 OP1010 130 1.00 1982-01-01 1983-02-01000310 OP1010 130 1.00 1982-01-01 1983-02-01000050 OP2010 10 0.75 1982-01-01 1983-02-01000100 OP2010 10 1.00 1982-01-01 1983-02-01000320 OP2011 140 0.75 1982-01-01 1983-02-01000320 OP2011 150 0.25 1982-01-01 1983-02-01000330 OP2012 140 0.25 1982-01-01 1983-02-01000330 OP2012 160 0.75 1982-01-01 1983-02-01000340 OP2013 140 0.50 1982-01-01 1983-02-01000340 OP2013 170 0.50 1982-01-01 1983-02-01000020 PL2100 30 1.00 1982-01-01 1982-09-15

xx DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

CARS Table

The CARS table is to use in unit 7 (recursive SQL).

LEVEL ASSEMBLY COMPONENT QUANTITY------ ------------------------- ------------------------- --------

1 HONDA ACCORD ENGINE COMPARTMENT 11 HONDA ACCORD PASSENGER COMPARTMENT 12 ENGINE COMPARTMENT ENGINE 12 ENGINE COMPARTMENT IGNITION SYSTEM 12 PASSENGER COMPARTMENT SEAT GROUP 32 PASSENGER COMPARTMENT DASHBOARD 12 PASSENGER COMPARTMENT TRUNK 13 ENGINE CAMSHAFT 13 ENGINE CRANKSHAFT 13 ENGINE PISTON 43 ENGINE CONNECTING ROD 43 SEAT GROUP FRONT SEAT ASSEMBLY 23 SEAT GROUP REAR SEAT ASSEMBLY 13 DASHBOARD VENT 43 DASHBOARD STEREO SYSTEM 13 DASHBOARD GAUGE CLUSTER 13 DASHBOARD CONTROL CLUSTER 13 TRUNK TOOL KIT 14 STEREO SYSTEM RADIO 14 STEREO SYSTEM CD PLAYER 14 GAUGE CLUSTER SPEEDOMETER 14 GAUGE CLUSTER ODOMETER 14 CONTROL CLUSTER FOG LAMP CONTROL 14 CONTROL CLUSTER FOUR WAY FLASHER CONTROL 14 CONTROL CLUSTER TURN SIGNAL CONTROL 14 FRONT SEAT ASSEMBLY FRONT SEAT 14 FRONT SEAT ASSEMBLY LAP/SHOULDER BELT 14 REAR SEAT ASSEMBLY REAR SEAT 14 REAR SEAT ASSEMBLY LAP/SHOULDER BELT 34 REAR SEAT ASSEMBLY SHOULDER BELT 3

Table Content xxi Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

TESTEMP Table

The TESTEMP table is to use in unit 2 (views).

EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS---------------- -------- ---------- -------- -------000111 SMITH C01 25.06.1998 25000.00 .00000010 HAAS A00 01.01.1965 52750.00 1000.00000020 THOMPSON B01 10.10.1973 41250.00 800.00000030 KWAN C01 05.04.1975 38250.00 800.00000050 GEYER E01 17.08.1949 40175.00 800.00

xxii DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Content of VIEWS

The listed views have to be used for the exercises in unit 3. Data types are listed inthe table description.

VEMPLOYEE View

EMPNO LASTNAME SALARY WORKDEPT------ --------- -------- --------000010 HAAS 52750.00 A00000030 KWAN 38250.00 C01000120 O'CONNELL 29250.00 A00000130 QUINTANA 23800.00 C01000140 NICHOLLS 28420.00 C01

VDEPARTMENT View

DEPTNO DEPTNAME MGRNO------ ---------------------------- ------A00 SPIFFY COMPUTER SERVICE DIV. 000010C01 INFORMATION CENTER 000030D01 DEVELOPMENT CENTER ------

VPROJECT View

PROJNO PROJNAME DEPTNO RESPEMP------ -------------- ------ -------AD3100 ADMIN SERVICES D01 000010IF1000 QUERY SERVICES C01 000030IF2000 USER EDUCATION C01 000030

Table Content xxiii Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Each exercise in this course is divided into sections as described below. Select thesection that best fits your method of performing labs. You may elect to use acombination of these sections as appropriate.

Exercise Instructions — This section contains what it is you are to accomplish. Thereare no definitive details on how to perform the tasks. You can work through theexercises based on what you have learned in the unit presentation, as well as the unitStudent Notebook, your past experience and some intuition.

Exercise Instructions With Hints — This section is an exact duplicate of the ExerciseInstructions section except that in addition, specific details and/or hints are providedto help step you through the exercise. A combination of using the Instructions sectionalong with Instructions With Hints section can make for a rewarding combinationproviding you with no hints when you don't want them and hints when you need them.

xxiv DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise 1. SQL Basics Review, CUBE AND ROLLUP

What This Exercise Is About

This exercise provides an opportunity to review some basic topics

What You Should Be Able to Do

At the end of the lab, you should be able to:

Code SELECT statements with multiple conditions

Use the GROUP BY clause

Use column functions

Use the new super groups features, CUBE & ROLLUP

Introduction

See the data model at the start of this Exercise Guide to get thecolumn names and descriptions for each table.

Required Materials

Student handoutSQL Reference

Exercise 1. SQL Basics Review, CUBE & ROLLUP 1-1 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions

Ron is the SQL specialist in the department. Joe is a colleague of Ron anddoes not have SQL knowledge. Joe asked Ron for help to solve the followingproblems.

Note: See the data model at the beginning of this exercise guide fordescriptions of the tables used in the labs and for their column names.

Problem 1

Joe's manager wants information about employees which match thefollowing criteria:

Their yearly salary is between 22000 and 24000.

They work in departments D11 or D21.

List the employee number, last name, yearly salary, and departmentnumber of the appropriate employees.

Problem 2

Now, Joe's manager wants information about the yearly salary. Hewants to know the minimum, the maximum, and average yearly salary ofall employees with an education level of 16. He also wants to know howmany employees have this education level.

Problem 3

Joe's manager is interested in some additional salary information. Thistime, he wants information for every department that appears in theEMPLOYEE table, provided that the department has more than fiveemployees. The report needs to show the department number, theminimum, maximum, and average yearly salary, and the number ofemployees who work in the department.

Problem 4

Joe's manager wants information about employees grouped bydepartment, grouped by sex and in addition by the combination ofdepartment and sex. List only those who work in a department whichstart with the letter D.

List the department, the sex, sum of the salaries, minimum salary andmaximum salary.

Note, the solution of this problem can only be used on DB2 UDB forUNIX, Windows and OS/2.

END OF LAB

1-2 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

Joe's manager wants information about employees which match thefollowing criteria:

Their yearly salary is between 22000 and 24000.

They work in departments D11 or D21.

List the employee number, last name, yearly salary, and departmentnumber of the appropriate employees.

Result

EMPNO LASTNAME SALARY WORKDEPT------ --------- -------- ---------000160 PIANKA 22250.00 D11000230 JEFFERSON 22180.00 D21

Problem 2

Now, Joe's manager wants information about the yearly salary. Hewants to know the minimum, the maximum, and average yearly salary ofall employees with an education level of 16. He also wants to know howmany employees have this education level.

Result

MIN MAX AVG COUNT-------- -------- -------------- -----17250.00 40175.00 26777.91666666 12

Problem 3

Joe's manager is interested in some additional salary information. Thistime, he wants information for every department that appears in theEMPLOYEE table, provided that the department has more than fiveemployees. The report needs to show the department number, theminimum, maximum, and average yearly salary, and the number ofemployees who work in the department.

Result

WORKDEPT MIN MAX AVG COUNT-------- -------- -------- -------------- -----D11 18270.00 32250.00 24677.77777777 9D21 17250.00 36170.00 25153.33333333 6

Problem 4

Joe's manager wants information about employees grouped bydepartment, grouped by sex and in addition by the combination ofdepartment and sex. List only those who work in a department whichstart with the letter D.

List the department, the sex, sum of the salaries, minimum salary andmaximum salary.

Exercise 1. SQL Basics Review, CUBE & ROLLUP 1-3 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Note, the solution of this problem can only be used on DB2 UDB forUNIX, Windows and OS/2.

Result

WORKDEPT SEX MIN MAX SUM-------- --- ----------- ----------- --------------------D11 - 18270.00 32250.00 222100.00D21 - 17250.00 36170.00 150920.00- - 17250.00 36170.00 373020.00- F 17250.00 36170.00 154230.00- M 18270.00 32250.00 218790.00D11 F 21340.00 29840.00 73430.00D21 F 17250.00 36170.00 80800.00D11 M 18270.00 32250.00 148670.00D21 M 19180.00 28760.00 70120.00

9 record(s) selected.

END OF LAB (with hints)

1-4 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Solution

Problem 1

SELECT EMPNO, LASTNAME, SALARY, WORKDEPTFROM EMPLOYEEWHERE WORKDEPT IN ('D11', 'D21')AND SALARY BETWEEN 22000 AND 24000

Problem 2

SELECT MIN(SALARY) AS MIN, MAX(SALARY) AS MAX,AVG(SALARY) AS AVG, COUNT(*) AS COUNT

FROM EMPLOYEEWHERE EDLEVEL = 16

Problem 3

SELECT WORKDEPT, MIN(SALARY) AS MIN, MAX(SALARY) AS MAX,AVG(SALARY) AS AVG, COUNT(*) AS COUNT

FROM EMPLOYEEGROUP BY WORKDEPTHAVING COUNT(*) > 5

Problem 4

SELECT WORKDEPT,SEX,MIN(SALARY) AS MIN,MAX(SALARY) AS MAX,SUM(SALARY) AS SUM

FROM EMPLOYEEWHERE WORKDEPT LIKE 'D%'GROUP BY CUBE (WORKDEPT,SEX)

END OF SOLUTION

Exercise 1. SQL Basics Review, CUBE & ROLLUP 1-5 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

1-6 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise 2. Create Objects

What This Exercise Is About

This exercise gives you an opportunity to implement a small datamodel.

What You Should Be Able to Do

At the end of the lab, you should be able to:

Create tables with check constraints

Create index

Use referential integrity

Create triggers

Create views

Understand the effect of CHECK OPTION in a view

Appreciate some of the advantages of using views

Introduction

See the data model at the start of this Exercise Guide to get thecolumn names and descriptions for each table.

OS/390 Users: Be sure to add the correct IN clause to yourCREATE TABLE statements. Ask the instructor if you forgot whichIN clause to use.

Required Materials

Student handoutSQL Reference

Exercise 2. Create Objects 2-1 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions

Harvey needs your help to create a database for his test environment. He hasaccurately defined the requirements, but he does not know the SQL syntax.You should help him to do the subsequent steps.

Problem 1

Create the table EMPDEPT with these columns:

EMPNOLASTNAMESALARYDEPTNODEP_NAME

The data types and null characteristics for these columns should be thesame as for the columns with the same names in the EMPLOYEE andDEPARTMENT tables. These tables are described in our course datamodel.

The definition of the table should limit the values for the yearly salary(SALARY) column to ensure that:

The yearly salary for employees in department E11 (operations) mustnot exceed 28000.

No employee in any department may have a yearly salary thatexceeds 50000.

The values in the EMPNO column should be unique. The uniquenessshould be guaranteed via a unique index.

Create the table HIGH_SALARY_RAISE with the following columns:

EMPNOPREV_SALNEW_SAL

The data type for column EMPNO is CHAR(6). The other columnsshould be defined as DECIMAL(9,2). All columns in this table should bedefined with NOT NULL.

2-2 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 2

After creating the table, you should add referential constraints.

The primary key for the EMPDEPT table should be EMPNO.

The EMPDEPT table should only allow values in column EMPNO whichexist in the EMPLOYEE table. If an employee is deleted from the EMPtable, the corresponding row in the EMPDEPT table should also beimmediately deleted.

The EMPDEPT table should only allow values in column DEPTNO whichexist in the DEPARTMENT table. It should not be possible to delete adepartment from the DEPARTMENT table as long as a correspondingDEPTNO exists in the EMPDEPT table.

Note: In DB2 for OS/390 the used sample tables are originally definedas views. You can not have a foreign key reference a view. Ask yourinstructor for the name and the qualifier of the tables which should bereferenced.

Problem 3

Klaus must update the yearly salaries for the employees of theEMPDEPT table. If the new value for a salary exceeds the previousvalue by 10 percent or more, Harvey wants to insert a row into theHIGH_SALARY_RAISE table. The values in this row should be theemployee number, the previous salary, and the new salary. Createsomething in DB2 that will ensure that a row is inserted into theHIGH_SALARY_RAISE table whenever an employee of the EMPDEPTtable gets a raise of 10 percent or more.

Problem 4

Now, you should insert data in the EMPDEPT table. Use the combinedcontents of tables EMPLOYEE and DEPARTMENT as the source for yourdata.

Did your insert work?

If not, correct your INSERT statement so that you get only rows whichsatisfy the check constraints on the EMPDEPT table.

Exercise 2. Create Objects 2-3 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 5

Harvey wants to test the table-level check constraint on the EMPDEPTtable.

Ethel Schneider works in the operations department. Her departmentnumber is E11, and her employee number is 000280. Try to set heryearly salary to the value of 30000. Does it work?

Problem 6

Harvey wants to see if the trigger works.

Elizabeth Pianka, whose employee number is 000160, has been given araise. Set her yearly salary to 25000. Inspect the HIGH_SALARY_RAISEtable to see if the trigger worked.

Problem 7

Create a view named VEMPPAY that contains one row for eachemployee in the company. Each row should contain employee number,last name, department number, and total earnings for the correspondingemployee. Total earnings means salary plus bonus plus commission forthe employee. Then, determine the average of the earnings for thedepartments by using the view you just created.

Problem 8

Create a view named VEMP1 containing employee number, last name,yearly salary, and work department based on your TESTEMP table.Only employees with a yearly salary less than 50000 should bedisplayed when you use the view.

Note: It is very important that you base this view on the TESTEMP tablethat was created for you or you created with the CRTABS member.Otherwise, you may get incorrect results in a later lab.

Display the rows in the view in employee number sequence.

Our employee with the employee number 000020 (Thompson) changedjobs and will get a new salary of 51000. Update the data for employeenumber 000020 using the view VEMP1.

Display the view again, arranging the rows in employee numbersequence.

What happened? Is Thompson still in the view?

Query the row of employee number 000020 in your TESTEMP table.

Did the update work?

Problem 9

Reset the salary of employee Thompson (empno = '000020') to thevalue of 41250.

Create a view named VEMP2 which has the same definition as inproblem 8, but add a CHECK OPTION. Again, base the view on yourTESTEMP table.

2-4 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Display the rows in the view in employee number sequence.

Our employee with the employee number 000050 (Geyer) also changedjobs and will have a new salary of 55000. Update the data for employeenumber 000050 using the view VEMP2. Does the UPDATE statementwork?

Display the view again, arranging the rows in employee numbersequence.

Query Geyer's row in your TESTEMP table.

Did the data in the base table change?

END OF LAB

Exercise 2. Create Objects 2-5 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

Create the table EMPDEPT with these columns:

EMPNOLASTNAMESALARYDEPTNODEP_NAME

The data types and null characteristics for these columns should be thesame as for the columns with the same names in the EMPLOYEE andDEPARTMENT tables. These tables are described in our course datamodel.

The definition of the table should limit the values for the yearly salary(SALARY) column to ensure that:

The yearly salary for employees in department E11 (operations) mustnot exceed 28000.

No employee in any department may have a yearly salary thatexceeds 50000.

The values in the EMPNO column should be unique. The uniquenessshould be guaranteed via a unique index.

Create the table HIGH_SALARY_RAISE with the following columns:

EMPNOPREV_SALNEW_SAL

The data type for column EMPNO is CHAR(6). The other columnsshould be defined as DECIMAL(9,2). All columns in this table should bedefined with NOT NULL.

Result

The CREATE statements for the EMPDEPT table, the unique index on theEMPDEPT table, and the HIGH_SALARY_RAISE table should all besuccessful.

2-6 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 2

After creating the table, you should add referential constraints.

The primary key for the EMPDEPT table should be EMPNO.

The EMPDEPT table should only allow values in column EMPNO whichexist in the EMPLOYEE table. If an employee is deleted from the EMPtable, the corresponding row in the EMPDEPT table should also beimmediately deleted.

The EMPDEPT table should only allow values in column DEPTNO whichexist in the DEPARTMENT table. It should not be possible to delete adepartment from the DEPARTMENT table as long as a correspondingDEPTNO exists in the EMPDEPT table.

Note: In DB2 for OS/390 the used sample tables are originally definedas views. You can not have a foreign key reference a view. Ask yourinstructor for the name and the qualifier of the tables which should bereferenced.

Result

The ALTER statements which add the primary key and the foreign keysshould execute successfully.

Problem 3

Klaus must update the yearly salaries for the employees of theEMPDEPT table. If the new value for a salary exceeds the previousvalue by 10 percent or more, Harvey wants to insert a row into theHIGH_SALARY_RAISE table. The values in this row should be theemployee number, the previous salary, and the new salary. Createsomething in DB2 that will ensure that a row is inserted into theHIGH_SALARY_RAISE table whenever an employee of the EMPDEPTtable gets a raise of 10 percent or more.

Result

The CREATE TRIGGER statement should execute successfully.

Problem 4

Now, you should insert data in the EMPDEPT table. Use the combinedcontents of tables EMPLOYEE and DEPARTMENT as the source for yourdata.

Did your insert work?

If not, correct your INSERT statement so that you get only rows whichsatisfy the check constraints on the EMPDEPT table.

Result

The initial INSERT should fail due to a check constraint violation. TheINSERT should work after it has been modified so that none of the rowsviolates a check constraint.

Exercise 2. Create Objects 2-7 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 5

Harvey wants to test the table-level check constraint on the EMPDEPTtable.

Ethel Schneider works in the operations department. Her departmentnumber is E11, and her employee number is 000280. Try to set heryearly salary to the value of 30000. Does it work?

Result

The UPDATE for Ethel Schneider will fail because it violates a checkconstraint.

Problem 6

Harvey wants to see if the trigger works.

Elizabeth Pianka, whose employee number is 000160, has been given araise. Set her yearly salary to 25000. Inspect the HIGH_SALARY_RAISEtable to see if the trigger worked.

Result

The UPDATE for Elizabeth Pianka should succeed and should fire thetrigger. You can verify that the trigger has fired by examining thecontents of the HIGH_SALARY_RAISE table. You should see a row therefor Elizabeth Pianka (EMPNO = 000160).

EMPNO PREV_SAL NEW_SAL------ -------- --------000160 22250.00 25000.00

Problem 7

Create a view named VEMPPAY that contains one row for eachemployee in the company. Each row should contain employee number,last name, department number, and total earnings for the correspondingemployee. Total earnings means salary plus bonus plus commission forthe employee. Then, determine the average of the earnings for thedepartments by using the view you just created.

Result

WORKDEPT AVG_TOTAL_EARNINGS-------- ------------------A00 47093.333333B01 45350.000000C01 33202.666666D11 27151.666666D21 27648.666666E01 44189.000000E11 23097.800000E21 26208.750000

Problem 8

Create a view named VEMP1 containing employee number, last name,yearly salary, and work department based on your TESTEMP table.

2-8 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Only employees with a yearly salary less than 50000 should bedisplayed when you use the view.

Note: It is very important that you base this view on the TESTEMP tablethat was created for you or you created with the CRTABS member.Otherwise, you may get incorrect results in a later lab.

Display the rows in the view in employee number sequence.

Our employee with the employee number 000020 (Thompson) changedjobs and will get a new salary of 51000. Update the data for employeenumber 000020 using the view VEMP1.

Display the view again, arranging the rows in employee numbersequence.

What happened? Is Thompson still in the view?

Query the row of employee number 000020 in your TESTEMP table.

Did the update work?Result

You should see the following when you first display the view contents:

EMPNO LASTNAME SALARY WORKDEPT------ -------- -------- --------000020 THOMPSON 41250.00 B01000030 KWAN 38250.00 C01000050 GEYER 40175.00 E01000111 SMITH 25000.00 C01

You should see the following when you display the view contents afterthe update:

EMPNO LASTNAME SALARY WORKDEPT------ -------- -------- --------000030 KWAN 38250.00 C01000050 GEYER 40175.00 E01000111 SMITH 25000.00 C01

You should see the following when you query the TESTEMP table:

EMPNO LASTNAME SALARY WORKDEPT------ -------- -------- --------000020 THOMPSON 51000.00 B01

The update worked.

Problem 9

Reset the salary of employee Thompson (empno = '000020') to thevalue of 41250.

Create a view named VEMP2 which has the same definition as inproblem 8, but add a CHECK OPTION. Again, base the view on yourTESTEMP table.

Display the rows in the view in employee number sequence.

Exercise 2. Create Objects 2-9 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Our employee with the employee number 000050 (Geyer) also changedalso jobs and will have a new salary of 55000. Update the data foremployee number 000050 using the view VEMP2. Does the UPDATEstatement work?

Display the view again, arranging the rows in employee numbersequence.

Query Geyer's row in your TESTEMP table.

Did the data in the base table change?Result

You should see the following when you first display the view contents:

EMPNO LASTNAME SALARY WORKDEPT------ -------- -------- --------000020 THOMPSON 41250.00 B01000030 KWAN 38250.00 C01000050 GEYER 40175.00 E01000111 SMITH 25000.00 C01

The SQLCODE (-161 in OS/390, SQL0161N on the workstation) indicatesthat the UPDATE did not work. The desired value for Geyer's SALARY,that is, 55000, was outside of the scope of the view (SALARY < 50000).The CHECK OPTION prevented the UPDATE.

You should see the following when displaying the view after the update:

EMPNO LASTNAME SALARY WORKDEPT------ -------- -------- --------000020 THOMPSON 41250.00 B01000030 KWAN 38250.00 C01000050 GEYER 40175.00 E01000111 SMITH 25000.00 C01

You should see the following when you query the TESTEMP table afterthe update:

EMPNO LASTNAME SALARY WORKDEPT------ -------- -------- --------000050 GEYER 40175.00 E01

The data in the base table did not change. Remember that the dataseen through the view is actually the base table data so this should notbe a surprise.

END OF LAB (with hints)

2-10 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Solution

Problem 1

CREATE TABLE EMPDEPT(EMPNO CHAR(6) NOT NULL,

LASTNAME VARCHAR(15) NOT NULL,SALARY DECIMAL(9,2) CHECK(SALARY <= 50000),DEPTNO CHAR(3) NOT NULL,DEP_NAME VARCHAR(36) NOT NULL,CONSTRAINT DEPT_SAL

CHECK (SALARY <= 28000 or DEPTNO <> 'E11'))--IN clause (OS/390 users only);

CREATE UNIQUE INDEX EMPIND ON EMPDEPT(EMPNO);

CREATE TABLE HIGH_SALARY_RAISE(EMPNO CHAR(6) NOT NULL,

PREV_SAL DECIMAL(9,2) NOT NULL,NEW_SAL DECIMAL(9,2) NOT NULL)

--IN clause (OS/390 users only);

Problem 2

ALTER TABLE EMPDEPTADD PRIMARY KEY (EMPNO);

ALTER TABLE EMPDEPTADD FOREIGN KEY (EMPNO) REFERENCES EMPLOYEE ON DELETE CASCADE;

ALTER TABLE EMPDEPTADD FOREIGN KEY (DEPTNO) REFERENCES DEPARTMENT ON DELETE RESTRICT;

Problem 3

CREATE TRIGGER HIGH_SALAFTER UPDATE OF SALARY ON EMPDEPTREFERENCING OLD AS O NEW AS NFOR EACH ROWMODE DB2SQLWHEN (N.SALARY >= O.SALARY * 1.1)INSERT INTO HIGH_SALARY_RAISE

VALUES (N.EMPNO, O.SALARY, N.SALARY);

Remember, OLD identifies the value that is in column SALARY beforethe update and NEW the value after the update.

Problem 4

Exercise 2. Create Objects 2-11 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

The correct version of the INSERT is as follows:

INSERT INTO EMPDEPTSELECT E.EMPNO, E.LASTNAME, E.SALARY, D.DEPTNO, D.DEPTNAME

FROM EMPLOYEE E, DEPARTMENT DWHERE E.WORKDEPT = D.DEPTNO

AND ((E.SALARY <= 50000 and E.WORKDEPT <> 'E11')OR (E.SALARY <= 28000 and E.WORKDEPT = 'E11'))

;

The WHERE condition satisfies the check condition on the SALARYcolumn of the EMPDEPT table (SALARY < 50000). The table constraintDEPT_SAL ensures that employees in department E11 have a yearlysalary of 2800 or less.

The condition "E.SALARY < = 50000 AND E.WORKDEPT < > 'E11'"selects employees who are not in department E11 and have a salary ofless than 50000.

The condition "E.SALARY < = 28000 AND E.WORKDEPT = 'E11'"selects employees who are in department E11 and have a salary of lessthan 28000.

Problem 5

UPDATE EMPDEPTSET SALARY = 30000WHERE EMPNO = '000280'

The update fails because the table constraint DEPT_SAL ensures thatemployees in department E11 have a yearly salary of less than 28000.

UPDATE EMPDEPTSET SALARY = 27999WHERE EMPNO = '000280'

This statement works. 28000 is the maximum yearly salary for EthelSchneider unless she changed departments.

Problem 6

UPDATE EMPDEPTSET SALARY = 25000WHERE EMPNO = '000160';

SELECT * FROM HIGH_SALARY_RAISE;

Problem 7

Create the view:

CREATE VIEW VEMPPAY (EMPNO, LASTNAME, WORKDEPT, TOTAL_EARNINGS)AS SELECT EMPNO, LASTNAME, WORKDEPT, SALARY + BONUS + COMM

FROM EMPLOYEE;

Use the view to determine the average total earnings for eachdepartment:

2-12 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

SELECT WORKDEPT, AVG(TOTAL_EARNINGS) AS AVG_TOTAL_EARNINGSFROM VEMPPAYGROUP BY WORKDEPT

Problem 8

Create the view:

CREATE VIEW VEMP1AS SELECT EMPNO, LASTNAME, SALARY, WORKDEPT

FROM TESTEMPWHERE SALARY < 50000;

Determine which employees appear in the view:

SELECT * FROM VEMP1ORDER BY EMPNO;

Update the data using the view:

UPDATE VEMP1SET SALARY = 51000

WHERE EMPNO = '000020';

Display the view again.

SELECT * FROM VEMP1ORDER BY EMPNO;

See if the update worked:

SELECT EMPNO, LASTNAME, SALARY, WORKDEPTFROM TESTEMPWHERE EMPNO = '000020';

Problem 9

Reset the salary for Thompson:

UPDATE TESTEMPSET SALARY = 41250

WHERE EMPNO = '000020'

Create the view:

CREATE VIEW VEMP2AS SELECT EMPNO, LASTNAME, SALARY, WORKDEPT

FROM TESTEMPWHERE SALARY < 50000

WITH CHECK OPTION;

Determine which employees appear in the view:

SELECT * FROM VEMP2ORDER BY EMPNO;

Update the data using the view:

Exercise 2. Create Objects 2-13 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

UPDATE VEMP2SET SALARY = 55000

WHERE EMPNO = '000050';

Display the view again.

SELECT * FROM VEMP2ORDER BY EMPNO;

See if the update worked:

SELECT EMPNO, LASTNAME, SALARY, WORKDEPTFROM TESTEMPWHERE EMPNO = '000050';

END OF SOLUTION

2-14 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise 3. Joins

What This Exercise Is About

This exercise will give you the opportunity to code inner and outerjoins.

What You Should Be Able to Do

At the end of the lab, you should be able to:

Code Inner and Outer Joins

Introduction

See the data model at the start of this Exercise Guide to get thecolumn names and descriptions for each table.

Note: Use the views VDEPARTMENT, VEMPLOYEE, andVPROJECT during this unit.

Required Materials

Student handoutSQL Reference

Exercise 3. Joins 3-1 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions

Problem 1

Display all employees who work in the INFORMATION CENTERdepartment. Show department number, employee number and lastname for all employees in that department. Use the "old" SQL syntaxthat puts the join condition in the WHERE clause.

Note: Use the views VDEPARTMENT, VEMPLOYEE, and VPROJECTduring this unit.

Problem 2

Solve problem 1 again using the newer SQL syntax that places the joincondition in the ON clause.

Problem 3

Bill needs a list of those employees whose departments are involved inprojects. The list needs to show employee number, last name,department number, and project name. The list should be ordered byproject names.

Problem 4

Now Bill wants to see all employees, whether or not their departmentsare involved a project. The list needs to show the employee number,last name, department number, and project name. If the department ofan employee is not involved in a project, display NULLs instead of theproject name. The list should be ordered by employee number.

Problem 5

Now Bill wants to see all projects, including those assigned todepartments without employees. The list needs to show employeenumber, last name, department number, and project name. If a projectis not assigned to a department having employees, NULLS should bedisplayed instead of the department number, employee number and lastname. The list should be ordered by project name.

3-2 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 6

Last, Bill wants to see all projects and all employees in one report.Projects not assigned to departments having employees should also belisted as well as employees who work in departments which are notinvolved in projects. The list needs to show employee number, lastname, department number, and project name. If a project is notassigned to a department having employees, NULLS should bedisplayed instead of the department number, employee number and lastname. If the department of an employee is not involved in a project,display NULLs instead of the project name.

END OF LAB

Exercise 3. Joins 3-3 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

Display all employees who work in the INFORMATION CENTERdepartment. Show department number, employee number and lastname for all employees in that department. Use the "old" SQL syntaxthat puts the join condition in the WHERE clause.

Note: Use the views VDEPARTMENT, VEMPLOYEE, and VPROJECTduring this unit.

Result

WORKDEPT EMPNO LASTNAME-------- ------ ----------C01 000030 KWANC01 000130 QUINTANAC01 000140 NICHOLLS

Problem 2

Solve problem 1 again using the newer SQL syntax that places the joincondition in the ON clause.

Result

WORKDEPT EMPNO LASTNAME-------- ------ ----------C01 000030 KWANC01 000130 QUINTANAC01 000140 NICHOLLS

Problem 3

Bill needs a list of those employees whose departments are involved inprojects. The list needs to show employee number, last name,department number, and project name. The list should be ordered byproject names.

Result

EMPNO LASTNAME WORKDEPT PROJNAME---------------- -------- --------------000140 NICHOLLS C01 QUERY SERVICES000130 QUINTANA C01 QUERY SERVICES000030 KWAN C01 QUERY SERVICES000030 KWAN C01 USER EDUCATION000130 QUINTANA C01 USER EDUCATION000140 NICHOLLS C01 USER EDUCATION

3-4 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 4

Now Bill wants to see all employees, whether or not their departmentsare involved a project. The list needs to show the employee number,last name, department number, and project name. If the department ofan employee is not involved in a project, display NULLs instead of theproject name. The list should be ordered by employee number.

Result

EMPNO LASTNAME WORKDEPT PROJNAME---------------- ------------------------------000010 HAAS A00 --------------000030 KWAN C01 QUERY SERVICES000030 KWAN C01 USER EDUCATION000120 O'CONNELL A00 --------------000130 QUINTANA C01 QUERY SERVICES000130 QUINTANA C01 USER EDUCATION000140 NICHOLLS C01 QUERY SERVICES000140 NICHOLLS C01 USER EDUCATION

Problem 5

Now Bill wants to see all projects, including those assigned todepartments without employees. The list needs to show employeenumber, last name, department number, and project name. If a projectis not assigned to a department having employees, NULLS should bedisplayed instead of the department number, employee number and lastname. The list should be ordered by project name.

Result

EMPNO LASTNAME WORKDEPT PROJNAME------ -------- -------- -------------------- -------- -------- ADMIN SERVICES000140 NICHOLLS C01 QUERY SERVICES000130 QUINTANA C01 QUERY SERVICES000030 KWAN C01 QUERY SERVICES000030 KWAN C01 USER EDUCATION000140 NICHOLLS C01 USER EDUCATION000130 QUINTANA C01 USER EDUCATION

Exercise 3. Joins 3-5 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 6

Last, Bill wants to see all projects and all employees in one report.Projects not assigned to departments having employees should also belisted as well as employees who work in departments which are notinvolved in projects. The list needs to show employee number, lastname, department number, and project name. If a project is notassigned to a department having employees, NULLS should bedisplayed instead of the department number, employee number and lastname. If the department of an employee is not involved in a project,display NULLs instead of the project name.

Result

EMPNO LASTNAME WORKDEPT PROJNAME------ --------- -------- --------------000010 HAAS A00 --------------000120 O'CONNELL A00 --------------000030 KWAN C01 USER EDUCATION000030 KWAN C01 QUERY SERVICES000140 NICHOLLS C01 USER EDUCATION000140 NICHOLLS C01 QUERY SERVICES000130 QUINTANA C01 USER EDUCATION000130 QUINTANA C01 QUERY SERVICES------ --------- ------- ADMIN SERVICES

END OF LAB (with hints)

3-6 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Solution

Problem 1

SELECT WORKDEPT, EMPNO, LASTNAMEFROM VEMPLOYEE, VDEPARTMENTWHERE WORKDEPT = DEPTNOAND DEPTNAME = 'INFORMATION CENTER'

Problem 2

SELECT WORKDEPT, EMPNO, LASTNAMEFROM VEMPLOYEE INNER JOIN VDEPARTMENTON WORKDEPT = DEPTNOWHERE DEPTNAME = 'INFORMATION CENTER'

Problem 3

SELECT EMPNO, LASTNAME, WORKDEPT, PROJNAMEFROM VEMPLOYEE INNER JOIN VPROJECTON WORKDEPT = DEPTNOORDER BY PROJNAME

Problem 4

SELECT EMPNO, LASTNAME, WORKDEPT, PROJNAMEFROM VEMPLOYEE LEFT OUTER JOIN VPROJECTON WORKDEPT = DEPTNOORDER BY EMPNO

Problem 5

SELECT EMPNO, LASTNAME, WORKDEPT, PROJNAMEFROM VEMPLOYEE RIGHT OUTER JOIN VPROJECTON WORKDEPT = DEPTNOORDER BY PROJNAME

The problem could also be solved by means of a left outer join. In thiscase, the names must be changed.

Exercise 3. Joins 3-7 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 6

SELECT EMPNO, LASTNAME, WORKDEPT, PROJNAMEFROM VEMPLOYEE FULL OUTER JOIN VPROJECTON WORKDEPT = DEPTNO

END OF SOLUTION

3-8 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise 4. CASE and CAST

What This Exercise Is About

This exercise give you the possibility to work with CASE and CASTexpressions.

What You Should Be Able to Do

At the end of the lab, you should be able to:

Use CASE expressions in the SELECT list

Use CASE expressions in the WHERE clause

Use CAST to convert between data types

Introduction

See the data model at the start of this Exercise Guide to get thecolumn names and descriptions for each table.

Required Materials

Student handoutSQL Reference

Exercise 4. CASE & CAST 4-1 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions

Problem 1

For all employees in department D11, display their employee number,last name and text specifying if the employee's salary is low, high ornormal.

SALARY INCOME-------- --------less than 25000 LOWbetween 25000 and 30000 NORMALhigher than 30000 HIGH

Problem 2

For all employees in department D11, display their last name, salaryand the difference between their salary and 30000. Sort the list in orderby the difference with the lowest difference first.

Problem 3

For each department, list the percentage of the bonus paid to theemployees relative to the total income (salary + bonus + commission)of the employees in that department. Take into account that somedepartments might not pay a bonus.

Problem 4

List the employees who have a commission of at least 8 percent of thesalary. Protect from division by 0 in case someone has 0 salary. Listthe last name and use CAST to list percentage with three decimals.

END OF LAB

4-2 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

For all employees in department D11, display their employee number,last name and text specifying if the employee's salary is low, high ornormal.

SALARY INCOME-------- --------less than 25000 LOWbetween 25000 and 30000 NORMALhigher than 30000 HIGH

Result

EMPNO FIRSTNME LASTNAME INCOME------ --------- --------- ---------------000060 IRVING STERN HIGH000150 BRUCE ADAMSON NORMAL000160 ELIZABETH PIANKA LOW000170 MASATOSHI YOSHIMURA LOW000180 MARILYN SCOUTTEN LOW000190 JAMES WALKER LOW000200 DAVID BROWN NORMAL000210 WILLIAM JONES LOW000220 JENNIFER LUTZ NORMAL

Exercise 4. CASE & CAST 4-3 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 2

For all employees in department D11, display their last name, salaryand the difference between their salary and 30000. Sort the list in orderby the difference with the lowest difference first.

Result

LASTNAME SALARY DIFFERENCE--------------- ----------- ----------------LUTZ 29840.00 160.00STERN 32250.00 2250.00BROWN 27740.00 2260.00ADAMSON 25280.00 4720.00YOSHIMURA 24680.00 5320.00PIANKA 22250.00 7750.00SCOUTTEN 21340.00 8660.00WALKER 20450.00 9550.00JONES 18270.00 11730.00

4-4 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 3

For each department, list the percentage of the bonus paid to theemployees relative to the total income (salary + bonus + commission)of the employees in that department. Take into account that somedepartments might not pay a bonus.

Result

WORKDEPT PERCENTAGE_BONUS-------- ---------------------------------A00 1.76B01 1.76C01 1.90D11 1.80D21 1.74E01 1.81E11 1.81E21 1.81

Problem 4

List the employees who have a commission of at least 8 percent of thesalary. Protect from division by 0 in case someone has 0 salary. Listthe last name and use CAST to list percentage with three decimals.

Result

LASTNAME COMM_PERCENTAGE--------------- ---------------NICHOLLS 8.001JONES 8.002MARINO 8.000LEE 8.001

END OF LAB (with hints)

Exercise 4. CASE & CAST 4-5 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Solution

Problem 1

SELECT EMPNO, FIRSTNME, LASTNAME,CASE

WHEN SALARY < 25000 THEN 'LOW'WHEN SALARY BETWEEN 25000 AND 30000 THEN 'NORMAL'WHEN SALARY > 30000 THEN 'HIGH'ELSE NULL

END AS INCOMEFROM EMPLOYEEWHERE WORKDEPT = 'D11'

Problem 2

SELECT LASTNAME, SALARY,CASE WHEN SALARY >= 30000 THEN SALARY - 30000ELSE 30000 - SALARYEND AS DIFFERENCE

FROM EMPLOYEEWHERE WORKDEPT='D11'ORDER BY DIFFERENCE

Problem 3

SELECT WORKDEPT,CASE WHEN SUM(BONUS) > 0 AND SUM(SALARY+BONUS+COMM)> 0

THENDECIMAL(DECIMAL(SUM(BONUS),8,2)*100.00 /DECIMAL(SUM(SALARY+BONUS+COMM),8,2),8,2)ELSE NULL

END AS PERCENTAGE_BONUSFROM EMPLOYEEGROUP BY WORKDEPT

4-6 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 4

SELECT LASTNAME,CAST(100*COMM/SALARY AS DECIMAL(8,3)) AS COMM_PERCENTAGE

FROM EMPLOYEEWHERE CASE WHEN COMM=0 OR SALARY=0

THEN NULLELSE COMM/SALARY

END > 0.08

END OF SOLUTION

Exercise 4. CASE & CAST 4-7 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

4-8 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise 5. Subqueries

What This Exercise Is About

This exercise gives you the opportunity to work with subqueries.

What You Should Be Able to Do

At the end of the lab, you should be able to:

Code simple subqueries using the = and > operators

Code more complex subqueries using the keywords ANY, ALL,IN

Code the NOT EXISTS subquery

Code correlated subqueries

Introduction

See the data model at the start of this Exercise Guide to get thecolumn names and descriptions for each table.

Required Materials

Student handoutSQL Reference

Exercise 5. Subqueries 5-1 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions

Problem 1

Retrieve all employees who are not involved in a project. Not involvedin a project are those employees who have no row in the EMP_ACTtable. Display employee number, last name, and department name.

Problem 2

Retrieve all employees whose yearly salary is more than the averagesalary of the employees in their department. For example, if theaverage yearly salary for department E11 is 20998, show all people indepartment E11 whose individual salary is higher than 20998. Displayemployee number, department number, and yearly salary. Sort theresult by department number and employee number.

Problem 3

Retrieve all departments having the same number of employees asdepartment A00. List department number and number of employees.Department A00 should not be part of the result.

Problem 4

Display employee number, last name, salary, and department number ofemployees who earn more than at least one employee in departmentD11. Employees in department D11 should not be included in the result.In other words, report on any employees in departments other than D11whose individual yearly salary is higher than that of at least oneemployee of department D11. List the employees in employee numbersequence.

Problem 5

Display employee number, last name, salary, and department number ofall employees who earn more than everybody belonging to departmentD11. Employees in department D11 should not be included in the result.In other words, report on all employees in departments other than D11whose individual yearly salary is higher than that of every employee indepartment D11. List the employees in employee number sequence.

Problem 6

Display employee number,last name, and number of activities of theemployee with the largest number of activities. Each activity is storedas one row in the EMP_ACT table.

5-2 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 7

Display employee number, last name, and activity number of allactivities in the EMP_ACT table. However, the list should only beproduced if there were any activities in 1982.

END OF LAB

Exercise 5. Subqueries 5-3 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

Retrieve all employees who are not involved in a project. Not involvedin a project are those employees who have no row in the EMP_ACTtable. Display employee number, last name, and department name.

Result

EMPNO LASTNAME DEPTNAME----------------- ----------------------------000060 STERN MANUFACTURING SYSTEMS000120 O'CONNELL SPIFFY COMPUTER SERVICE DIV.

Problem 2

Retrieve all employees whose yearly salary is more than the averagesalary of the employees in their department. For example, if theaverage yearly salary for department E11 is 20998, show all people indepartment E11 whose individual salary is higher than 20998. Displayemployee number, department number, and yearly salary. Sort theresult by department number and employee number.

Result

EMPNO SALARY WORKDEPT------ -------- --------000010 52750.00 A00000110 46500.00 A00000030 38250.00 C01000060 32250.00 D11000150 25280.00 D11000170 24680.00 D11000200 27740.00 D11000220 29840.00 D11000070 36170.00 D21000240 28760.00 D21000270 27380.00 D21000090 29750.00 E11000280 26250.00 E11000100 26150.00 E21000330 25370.00 E21000340 23840.00 E21

5-4 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 3

Retrieve all departments having the same number of employees asdepartment A00. List department number and number of employees.Department A00 should not be part of the result.

Result

WORKDEPT EMP_COUNT-------- ---------C01 3

Problem 4

Display employee number, last name, salary, and department number ofemployees who earn more than at least one employee in departmentD11. Employees in department D11 should not be included in the result.In other words, report on any employees in departments other than D11whose individual yearly salary is higher than that of at least oneemployee of department D11. List the employees in employee numbersequence.

Result

EMPNO LASTNAME SALARY WORKDEPT------ --------- -------- --------000010 HAAS 52750.00 A00000020 THOMPSON 41250.00 B01000030 KWAN 38250.00 C01000050 GEYER 40175.00 E01000070 PULASKI 36170.00 D21000090 HENDERSON 29750.00 E11000100 SPENSER 26150.00 E21000110 LUCCHESI 46500.00 A00000120 O'CONNELL 29250.00 A00000130 QUINTANA 23800.00 C01000140 NICHOLLS 28420.00 C01000230 JEFFERSON 22180.00 D21000240 MARINO 28760.00 D21000250 SMITH 19180.00 D21000270 PEREZ 27380.00 D21000280 SCHNEIDER 26250.00 E11000320 MEHTA 19950.00 E21000330 LEE 25370.00 E21000340 GOUNOT 23840.00 E21

Exercise 5. Subqueries 5-5 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 5

Display employee number, last name, salary, and department number ofall employees who earn more than everybody belonging to departmentD11. Employees in department D11 should not be included in the result.In other words, report on all employees in departments other than D11whose individual yearly salary is higher than that of every employee indepartment D11. List the employees in employee number sequence.

Result

EMPNO LASTNAME SALARY WORKDEPT------ -------- -------- --------000010 HAAS 52750.00 A00000020 THOMPSON 41250.00 B01000030 KWAN 38250.00 C01000050 GEYER 40175.00 E01000070 PULASKI 36170.00 D21000110 LUCCHESI 46500.00 A00

Problem 6

Display employee number,last name, and number of activities of theemployee with the largest number of activities. Each activity is storedas one row in the EMP_ACT table.

Result

EMPNO LASTNAME COUNT_ACT------ -------- ---------000250 SMITH 10

5-6 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 7

Display employee number, last name, and activity number of allactivities in the EMP_ACT table. However, the list should only beproduced if there were any activities in 1982.

Result

EMPNO LASTNAME ACTNO------ --------- -----000010 HAAS 10000010 HAAS 10000010 HAAS 10000020 THOMPSON 30000030 KWAN 10000030 KWAN 10000050 GEYER 10000050 GEYER 10000070 PULASKI 10000090 HENDERSON 10000100 SPENSER 10000110 LUCCHESI 20

..... ....... ..

The complete result contains 75 rows.

END OF LAB (with hints)

Exercise 5. Subqueries 5-7 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Solution

Problem 1

SELECT EMPNO, LASTNAME, DEPTNAMEFROM EMPLOYEE , DEPARTMENTWHERE WORKDEPT = DEPTNOAND EMPNO NOT IN (SELECT EMPNO FROM EMP_ACT)

Problem 2

SELECT EMPNO, SALARY, WORKDEPTFROM EMPLOYEE EWHERE SALARY > (SELECT AVG(SALARY)

FROM EMPLOYEEWHERE WORKDEPT = E.WORKDEPT)

ORDER BY WORKDEPT, EMPNO;

Problem 3

SELECT WORKDEPT, COUNT(*) AS EMP_COUNTFROM EMPLOYEEWHERE WORKDEPT <> 'A00'GROUP BY WORKDEPTHAVING COUNT(*) = (SELECT COUNT(*)

FROM EMPLOYEEWHERE WORKDEPT = 'A00');

Problem 4

SELECT EMPNO, LASTNAME, SALARY, WORKDEPTFROM EMPLOYEEWHERE WORKDEPT <> 'D11'AND SALARY > ANY (SELECT SALARY

FROM EMPLOYEEWHERE WORKDEPT = 'D11')

ORDER BY EMPNO;

An alternate solution is:

SELECT EMPNO, LASTNAME, SALARY, WORKDEPTFROM EMPLOYEEWHERE WORKDEPT <> 'D11'

AND SALARY > (SELECT MIN(SALARY)FROM EMPLOYEEWHERE WORKDEPT = 'D11')

ORDER BY EMPNO;

5-8 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 5

SELECT EMPNO, LASTNAME, SALARY, WORKDEPTFROM EMPLOYEEWHERE WORKDEPT <> 'D11'AND SALARY > ALL (SELECT SALARY

FROM EMPLOYEEWHERE WORKDEPT = 'D11')

ORDER BY EMPNO;

An alternate solution is:

SELECT EMPNO, LASTNAME, SALARY, WORKDEPTFROM EMPLOYEEWHERE WORKDEPT <> 'D11'

AND SALARY > (SELECT MAX(SALARY)FROM EMPLOYEEWHERE WORKDEPT = 'D11')

ORDER BY EMPNO;

Problem 6

SELECT E.EMPNO, LASTNAME, COUNT(*) AS COUNT_ACTFROM EMPLOYEE E, EMP_ACT EAWHERE E.EMPNO = EA.EMPNOGROUP BY E.EMPNO, LASTNAMEHAVING COUNT(*) >= ALL(SELECT COUNT(*)

FROM EMP_ACTGROUP BY EMPNO)

Problem 7

SELECT E.EMPNO, LASTNAME, ACTNOFROM EMPLOYEE E JOIN EMP_ACT EAON E.EMPNO = EA.EMPNOWHERE EXISTS (SELECT * FROM

EMP_ACTWHERE YEAR(EMSTDATE) = 1982)

END OF SOLUTION

Exercise 5. Subqueries 5-9 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

5-10 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise 6. Scalar Functions

What This Exercise Is About

This exercise gives you the opportunity to work with scalarfunctions.

What You Should Be Able to Do

At the end of the lab, you should be able to:

Code queries using scalar functions

Introduction

See the data model at the start of this Exercise Guide to get thecolumn names and descriptions for each table.

Required Materials

Student handoutSQL Reference

Exercise 6. Scalar Functions 6-1 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions

Problem 1

Produce a report listing all employees whose last name ends with 'N'.List the employee number, the last name, and the last character of thelast name used to control the result. The LASTNAME column is definedas VARCHAR. There is a function which provides the length of the lastname.

Problem 2

For each project, display the project number, project name, departmentnumber, and project number of its associated major project (COLUMN= MAJPROJ). If the value in MAJPROJ is NULL, show a literal of yourchoice instead of displaying a null value. List only projects assigned todepartments D01 or D11. The rows should be listed in project numbersequence.

Problem 3

The salaries of the employees in department E11 will be increased by3.75 percent. What will be the increase in dollars? Display the lastname, actual yearly salary, and the salary increase rounded to thenearest dollar. Do not show any cents.

Problem 4

Repeat Problem 3 but this time express the amount of salary increase asan integer, that is, a number with no decimal places and no decimalpoint. (QMF users, you do not get a decimal point even for Problem 3,so there is no point in doing this problem if you are using QMF.)

Problem 5

For each female employee in the company present her department, herjob and her last name with only one blank between job and last name.

Problem 6

Calculate the difference between the date of birth and the hiring date forall employees for whom the hiring date is more than 30 years later thanthe date of birth. Display employee number and calculated difference.The difference should be shown in years, months, and days - each ofwhich should be shown in a separate column. Make sure that the rowsare in employee number sequence.

6-2 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 7

Display project number, project name, project start date, and projectend date of those projects whose duration was less than 10 months.Display the project duration in days.

Problem 8

List the employees in department D11 who had activities. Displayemployee number, last name, and first name. Also, show the activitynumber and the activity duration (in days) of the activities started last.Multiple activities may have been started on the same day.

Problem 9

How many weeks are between the first manned landing on the moon(July 20, 1969) and the first day of the year 2000?

Problem 10

Find out which employees were hired on a Saturday or a Sunday. Listtheir last names and their hiring dates.

END OF LAB

Exercise 6. Scalar Functions 6-3 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

Produce a report listing all employees whose last name ends with 'N'.List the employee number, the last name, and the last character of thelast name used to control the result. The LASTNAME column is definedas VARCHAR. There is a function which provides the length of the lastname.

Result

EMPNO LASTNAME LASTCHAR------ --------- --------000020 THOMPSON N000030 KWAN N000060 STERN N000090 HENDERSON N000150 ADAMSON N000180 SCOUTTEN N000200 BROWN N000230 JEFFERSON N000260 JOHNSON N

Problem 2

For each project, display the project number, project name, departmentnumber, and project number of its associated major project (COLUMN= MAJPROJ). If the value in MAJPROJ is NULL, show a literal of yourchoice instead of displaying a null value. List only projects assigned todepartments D01 or D11. The rows should be listed in project numbersequence.

Result

PROJNO PROJNAME DEPTNO MAJPROJ------ -------------------- ------ ----------------AD3100 ADMIN SERVICES D01 NO MAJOR PROJECT <----noteMA2100 WELD LINE AUTOMATION D01 NO MAJOR PROJECTMA2110 W L PROGRAMMING D11 MA2100MA2111 W L PROGRAM DESIGN D11 MA2110MA2112 W L ROBOT DESIGN D11 MA2110MA2113 W L PROD CONT PROGS D11 MA2110

The first row in the resultset above will not have the text 'NO MAJORPROJECT' when the query is run on DB2 UDB for UNIX, Windows andOS/2 as MAJPROJ is blank and not null for PROJNO AD3100.

6-4 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 3

The salaries of the employees in department E11 will be increased by3.75 percent. What will be the increase in dollars? Display the lastname, actual yearly salary, and the salary increase rounded to thenearest dollar. Do not show any cents.

Result

EMPNO LASTNAME WORKDEPT SALARY AMOUNT------ --------- -------- -------- ------000090 HENDERSON E11 29750.00 1116.000280 SCHNEIDER E11 26250.00 984.000290 PARKER E11 15340.00 575.000300 SMITH E11 17750.00 666.000310 SETRIGHT E11 15900.00 596.

Problem 4

Repeat Problem 3 but this time express the amount of salary increase asan integer, that is, a number with no decimal places and no decimalpoint. (QMF users, you do not get a decimal point even for Problem 3,so there is no point in doing this problem if you are using QMF.)

Result

EMPNO LASTNAME WORKDEPT SALARY AMOUNT------ --------- -------- -------- ------000090 HENDERSON E11 29750.00 1116000280 SCHNEIDER E11 26250.00 984000290 PARKER E11 15340.00 575000300 SMITH E11 17750.00 666000310 SETRIGHT E11 15900.00 596

Exercise 6. Scalar Functions 6-5 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 5

For each female employee in the company present her department, herjob and her last name with only one blank between job and last name.

Result

WORKDEPT LISTING-------- ---------------------------A00 PRES: HAASC01 MANAGER: KWAND21 MANAGER: PULASKIE11 MANAGER: HENDERSONC01 ANALYST: QUINTANAC01 ANALYST: NICHOLLSD11 DESIGNER: PIANKAD11 DESIGNER: SCOUTTEND11 DESIGNER: LUTZD21 CLERK: JOHNSOND21 CLERK: PEREZE11 OPERATOR: SCHNEIDERE11 OPERATOR: SETRIGHT

13 record(s) selected.

6-6 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 6

Calculate the difference between the date of birth and the hiring date forall employees for whom the hiring date is more than 30 years later thanthe date of birth. Display employee number and calculated difference.The difference should be shown in years, months, and days - each ofwhich should be shown in a separate column. Make sure that the rowsare in employee number sequence.

Result

EMPNO YEARS MONTHS DAYS------ ----- ------ ----000010 31 4 18000030 33 10 25000130 45 10 13000230 31 5 22000260 38 11 6000290 33 10 21000300 35 7 23000310 33 4 21000320 32 10 27000330 34 7 5

Problem 7

Display project number, project name, project start date, and projectend date of those projects whose duration was less than 10 months.Display the project duration in days.

Result

PROJNO PROJNAME PRSTDATE PRENDATE DAYS_DURATION------ ------------------- ---------- ---------- -------------MA2113 W L PROD CONT PROGS 1982-02-15 1982-12-01 289PL2100 WELD LINE PLANNING 1982-01-01 1982-09-15 257

Exercise 6. Scalar Functions 6-7 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 8

List the employees in department D11 who had activities. Displayemployee number, last name, and first name. Also, show the activitynumber and the activity duration (in days) of the activities started last.Multiple activities may have been started on the same day.

Result

EMPNO LASTNAME FIRSTNME ACTNO EMSTDATE DAYS_DURATION------ --------- --------- ----- ---------- -------------000150 ADAMSON BRUCE 180 1982-07-15 201000160 PIANKA ELIZABETH 60 1982-07-15 201000170 YOSHIMURA MASATOSHI 70 1982-06-01 245000180 SCOUTTEN MARILYN 70 1982-04-01 75000190 WALKER JAMES 80 1982-10-01 365000200 BROWN DAVID 60 1982-06-15 231000210 JONES WILLIAM 80 1982-10-01 123000210 JONES WILLIAM 180 1982-10-01 123000220 LUTZ JENNIFER 40 1982-01-01 396

Problem 9

How many weeks are between the first manned landing on the moon(July 20, 1969) and the first day of the year 2000?

Result

WEEKS-----

1588

Problem 10

Find out which employees were hired on a Saturday or a Sunday. Listtheir last names and their hiring dates.

Result

HIREDATE LASTNAME---------- ---------------1975-04-05 KWAN1970-08-15 HENDERSON1972-02-12 ADAMSON1973-07-07 SCOUTTEN1964-09-12 SETRIGHT

5 record(s) selected.

END OF LAB (with hints)

6-8 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Solution

Problem 1

SELECT EMPNO,LASTNAME,SUBSTR(LASTNAME,LENGTH(LASTNAME),1) AS LASTCHAR

FROM EMPLOYEEWHERE LASTNAME LIKE '%N'

An alternate solution is:

SELECT EMPNO,LASTNAME,SUBSTR(LASTNAME,LENGTH(LASTNAME),1) AS LASTCHAR

FROM EMPLOYEEWHERE SUBSTR(LASTNAME,LENGTH(LASTNAME),1) = 'N'

If the column LASTNAME had been defined as CHAR(x) one way to codethis WHERE clause could be:

WHERE LASTNAME LIKE '%N %' OR LASTNAME LIKE '%N'

Problem 2

SELECT PROJNO, PROJNAME, DEPTNO,COALESCE(MAJPROJ,'NO MAJOR PROJECT') AS MAJPROJ

FROM PROJECTWHERE DEPTNO IN ('D01','D11')ORDER BY PROJNO;

Problem 3

SELECT EMPNO, LASTNAME, WORKDEPT, SALARY,DECIMAL(SALARY * 0.0375 + 0.5, 5,0) AS AMOUNT

FROM EMPLOYEEWHERE WORKDEPT = 'E11'

or by using ROUND():

SELECT EMPNO, LASTNAME, WORKDEPT, SALARY,ROUNDL(SALARY * 0.0375 + ,0) AS AMOUNT

FROM EMPLOYEEWHERE WORKDEPT = 'E11'

Round() gives in OS/390 a DECIMAL; in UNIX, Windows and OS/2a FLOATING point value.

Exercise 6. Scalar Functions 6-9 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 4

SELECT EMPNO, LASTNAME, WORKDEPT, SALARY,INTEGER(SALARY * 0.0375 + 0.5) AS AMOUNT

FROM EMPLOYEEWHERE WORKDEPT = 'E11'

Problem 5

SELECT WORKDEPT, CAST(RTRIM(JOB) AS VARCHAR(10))!! ': '!! LASTNAME AS LISTING

FROM EMPLOYEEWHERE SEX='F'

Problem 6

SELECT EMPNO, YEAR(HIREDATE - BIRTHDATE) AS YEARS,MONTH(HIREDATE - BIRTHDATE) AS MONTHS,

DAY(HIREDATE - BIRTHDATE) AS DAYSFROM EMPLOYEEWHERE YEAR(HIREDATE - BIRTHDATE) > 30ORDER BY EMPNO

Problem 7

SELECT PROJNO, PROJNAME, PRSTDATE, PRENDATE,DAYS(PRENDATE) - DAYS(PRSTDATE) AS DAYS_DURATION

FROM PROJECTWHERE PRENDATE - 10 MONTHS < PRSTDATE

Problem 8

SELECT E.EMPNO, LASTNAME, FIRSTNME, ACTNO, EMSTDATE,DAYS(EMENDATE) - DAYS(EMSTDATE) AS DAYS_DURATION

FROM EMPLOYEE E JOIN EMP_ACT EAON E.EMPNO = EA.EMPNO

WHERE EMSTDATE = (SELECT MAX(EMSTDATE) FROM EMP_ACTWHERE EMPNO = E.EMPNO)

AND E.WORKDEPT = 'D11'

6-10 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 9

SELECT (DAYS('2000-01-01') - DAYS('1969-07-20') ) / 7 AS WEEKSFROM EMPLOYEEWHERE EMPNO = '000010'

Note that the scalar function WEEK only gives the week-number of theyear for a date.

Problem 10

SELECT HIREDATE,LASTNAMEFROM EMPLOYEEWHERE DAYOFWEEK(HIREDATE) IN (1,7)

END OF SOLUTION

Exercise 6. Scalar Functions 6-11 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

6-12 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise 7. Table Expressions and Recursive SQL

What This Exercise Is About

This exercise gives you the opportunity to work with tableexpressions and recursive SQL.

What You Should Be Able to Do

At the end of the lab, you should be able to:

Code SQL statements using nested table expressions

Code SQL statements using common table expressions

Code recursive SQL statements that control the depth ofrecursion

Introduction

See the data model at the start of this Exercise Guide to get thecolumn names and descriptions for each table.

Note: OS/390 Users: Students using DB2 for OS/390 will not beable to perform Problem 4. Skip the problem or do it on aworkstation platform.

Required Materials

Student handoutSQL Reference

Exercise 7. Table Expressions and Recursive SQL 7-1 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions

Problem 1

Prepare a report giving information about the average total earnings ofall employees hired in the same year. The report should includeemployees hired from the beginning of 1970 till the end of 1980.

Problem 2

Now, find out the highest average from the list produced during Problem1. You can use your query from Problem1 and modify it to solve theproblem. If you want, try to list the respective hiring year in addition tothe highest average. This is a little bit more complex.

Problem 3

For each employee, display employee number, salary, and averagesalary and department number. The list should be sorted bydepartment number and employee number.

Problem 4

This problem can not be done on DB2 for OS/390.

A table named CARS contains the bill-of-materials for making a specificmodel of a Honda Accord. You created the CARS table when youexecuted the CRTABS member at the beginning of the labs. Determineall the major parts necessary to construct the Passenger Compartmentof the car. In other words, do not take the recursion to the maximumpossible depth:, control the recursion so that it does not iterate morethan once after the initialization.

You can determine the contents of the CARS table with the followingSELECT statement.

SELECT * FROM CARSORDER BY 1, 2, 3, 4

The CARS table should contain the following data:

7-2 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

LEVEL ASSEMBLY COMPONENT QUANTITY------ ------------------------- ------------------------- --------

1 HONDA ACCORD ENGINE COMPARTMENT 11 HONDA ACCORD PASSENGER COMPARTMENT 12 ENGINE COMPARTMENT ENGINE 12 ENGINE COMPARTMENT IGNITION SYSTEM 12 PASSENGER COMPARTMENT SEAT GROUP 32 PASSENGER COMPARTMENT DASHBOARD 12 PASSENGER COMPARTMENT TRUNK 13 ENGINE CAMSHAFT 13 ENGINE CRANKSHAFT 13 ENGINE PISTON 43 ENGINE CONNECTING ROD 43 SEAT GROUP FRONT SEAT ASSEMBLY 23 SEAT GROUP REAR SEAT ASSEMBLY 13 DASHBOARD VENT 43 DASHBOARD STEREO SYSTEM 13 DASHBOARD GAUGE CLUSTER 13 DASHBOARD CONTROL CLUSTER 13 TRUNK TOOL KIT 14 STEREO SYSTEM RADIO 14 STEREO SYSTEM CD PLAYER 14 GAUGE CLUSTER SPEEDOMETER 14 GAUGE CLUSTER ODOMETER 14 CONTROL CLUSTER FOG LAMP CONTROL 14 CONTROL CLUSTER FOUR WAY FLASHER CONTROL 14 CONTROL CLUSTER TURN SIGNAL CONTROL 14 FRONT SEAT ASSEMBLY FRONT SEAT 14 FRONT SEAT ASSEMBLY LAP/SHOULDER BELT 14 REAR SEAT ASSEMBLY REAR SEAT 14 REAR SEAT ASSEMBLY LAP/SHOULDER BELT 34 REAR SEAT ASSEMBLY SHOULDER BELT 3

30 record(s) selected.

END OF LAB

Exercise 7. Table Expressions and Recursive SQL 7-3 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions With Hints

Problem 1

Prepare a report giving information about the average total earnings ofall employees hired in the same year. The report should includeemployees hired from the beginning of 1970 till the end of 1980.

Result

HIREYEAR AVG_TOTAL_EARNINGS------+- ------+---------+-

1970 32730.0000001971 26204.0000001972 23686.0000001973 34775.6666661974 22486.0000001975 30520.0000001976 29597.0000001977 24430.0000001978 27154.0000001979 25896.5000001980 28860.500000

Problem 2

Now, find out the highest average from the list produced during Problem1. You can use your query from Problem1 and modify it to solve theproblem. If you want, try to list the respective hiring year in addition tothe highest average. This is a little bit more complex.

Result

HIGHEST_AVERAGE---------------

34775.666666

To list this second result is more complex then the first solution. Maybe you want to try it.

HIREYEAR AVG_TOTAL_PAYMENT-------- -----------------

1973 34775.666666

7-4 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 3

For each employee, display employee number, salary, and averagesalary and department number. The list should be sorted bydepartment number and employee number.

Result

EMPNO SALARY AVG_SAL WORKDEPT------ -------- -------------- --------000010 52750.00 42833.33333333 A00000110 46500.00 42833.33333333 A00000120 29250.00 42833.33333333 A00000020 41250.00 41250.00000000 B01000030 38250.00 30156.66666666 C01000130 23800.00 30156.66666666 C01000140 28420.00 30156.66666666 C01000060 32250.00 24677.77777777 D11000150 25280.00 24677.77777777 D11000160 22250.00 24677.77777777 D11000170 24680.00 24677.77777777 D11000180 21340.00 24677.77777777 D11000190 20450.00 24677.77777777 D11

..... ........ .............. ...

The complete result set contains 32 rows.

Problem 4

This problem can not be done on DB2 for OS/390.

A table named CARS contains the bill-of-materials for making a specificmodel of a Honda Accord. You created the CARS table when youexecuted the CRTABS member at the beginning of the labs. Determineall the major parts necessary to construct the Passenger Compartmentof the car. In other words, do not take the recursion to the maximumpossible depth:, control the recursion so that it does not iterate morethan once after the initialization.

You can determine the contents of the CARS table with the followingSELECT statement.

SELECT * FROM CARSORDER BY 1, 2, 3, 4

The CARS table should contain the following data:

Exercise 7. Table Expressions and Recursive SQL 7-5 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

LEVEL ASSEMBLY COMPONENT QUANTITY------ ------------------------- ------------------------- --------

1 HONDA ACCORD ENGINE COMPARTMENT 11 HONDA ACCORD PASSENGER COMPARTMENT 12 ENGINE COMPARTMENT ENGINE 12 ENGINE COMPARTMENT IGNITION SYSTEM 12 PASSENGER COMPARTMENT SEAT GROUP 32 PASSENGER COMPARTMENT DASHBOARD 12 PASSENGER COMPARTMENT TRUNK 13 ENGINE CAMSHAFT 13 ENGINE CRANKSHAFT 13 ENGINE PISTON 43 ENGINE CONNECTING ROD 43 SEAT GROUP FRONT SEAT ASSEMBLY 23 SEAT GROUP REAR SEAT ASSEMBLY 13 DASHBOARD VENT 43 DASHBOARD STEREO SYSTEM 13 DASHBOARD GAUGE CLUSTER 13 DASHBOARD CONTROL CLUSTER 13 TRUNK TOOL KIT 14 STEREO SYSTEM RADIO 14 STEREO SYSTEM CD PLAYER 14 GAUGE CLUSTER SPEEDOMETER 14 GAUGE CLUSTER ODOMETER 14 CONTROL CLUSTER FOG LAMP CONTROL 14 CONTROL CLUSTER FOUR WAY FLASHER CONTROL 14 CONTROL CLUSTER TURN SIGNAL CONTROL 14 FRONT SEAT ASSEMBLY FRONT SEAT 14 FRONT SEAT ASSEMBLY LAP/SHOULDER BELT 14 REAR SEAT ASSEMBLY REAR SEAT 14 REAR SEAT ASSEMBLY LAP/SHOULDER BELT 34 REAR SEAT ASSEMBLY SHOULDER BELT 3

30 record(s) selected.

7-6 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Result

LEVEL ASSEMBLY COMPONENT QUANTITY----- --------------------- ------------------ --------

0 PASSENGER COMPARTMENT DASHBOARD 10 PASSENGER COMPARTMENT SEAT GROUP 30 PASSENGER COMPARTMENT TRUNK 11 DASHBOARD CONTROL CLUSTER 11 DASHBOARD GAUGE CLUSTER 11 DASHBOARD STEREO SYSTEM 11 DASHBOARD VENT 41 SEAT GROUP FRONT SEAT ASSEMBLY 21 SEAT GROUP REAR SEAT ASSEMBLY 11 TRUNK TOOL KIT 1

END OF LAB (with hints)

Exercise 7. Table Expressions and Recursive SQL 7-7 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Solution

Problem 1

SELECT TEMP.HIREYEAR, AVG(TEMP.TOTAL_EARNINGS) AS AVG_TOTAL_EARNINGSFROM(SELECT YEAR(HIREDATE) AS HIREYEAR,

SALARY + BONUS + COMM AS TOTAL_EARNINGSFROM EMPLOYEEWHERE HIREDATE BETWEEN '1970-01-01' AND '1980-12-31' )AS TEMP

GROUP BY TEMP.HIREYEAR

Problem 2

SELECT MAX(TEMP1.AVG_TOTAL_EARNINGS) AS HIGHEST_AVERAGEFROM(SELECT TEMP.HIREYEAR AS HIRED,

AVG(TEMP.TOTAL_EARNINGS) AS AVG_TOTAL_EARNINGSFROM(SELECT YEAR(HIREDATE) AS HIREYEAR,

SALARY + BONUS + COMM AS TOTAL_EARNINGSFROM EMPLOYEEWHERE HIREDATE BETWEEN '1970-01-01' AND '1980-12-31' )AS TEMP

GROUP BY TEMP.HIREYEAR) AS TEMP1

This query does not list the hiring years of the employees with theaverage total earnings. To list their hiring year you can use thefollowing query:

SELECT TEMP.HIREYEAR, AVG(TEMP.TOTAL_EARNINGS) AS AVG_TOTAL_EARNINGSFROM(SELECT YEAR(HIREDATE) AS HIREYEAR,

SALARY + BONUS + COMM AS TOTAL_EARNINGSFROM EMPLOYEEWHERE HIREDATE BETWEEN '1970-01-01' AND '1980-12-31' )AS TEMP

GROUP BY TEMP.HIREYEARHAVING AVG(TEMP.TOTAL_EARNINGS) >= ALL

(SELECT AVG(TEMP1.TOTAL_EARNINGS)FROM

(SELECT YEAR(HIREDATE) AS HIREYEAR,SALARY + BONUS + COMMAS TOTAL_EARNINGSFROM EMPLOYEEWHERE HIREDATE BETWEEN '1970-01-01'AND '1980-12-31' ) AS TEMP1GROUP BY TEMP1.HIREYEAR)

7-8 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 3

SELECT EMPNO, SALARY, AVG_TAB.AVG_SAL, E.WORKDEPTFROM EMPLOYEE E INNER JOIN (SELECT WORKDEPT ,AVG(SALARY) AS AVG_SAL

FROM EMPLOYEEGROUP BY WORKDEPT) AS AVG_TAB

ON E.WORKDEPT = AVG_TAB.WORKDEPTORDER BY E.WORKDEPT, EMPNO

It is not necessary to restrict yourself to the 'new' join syntax to solvethis problem. The 'old' join syntax could also be used. For example,the following work:

SELECT EMPNO, SALARY, AVG_TAB.AVG_SAL, E.WORKDEPTFROM EMPLOYEE E , (SELECT WORKDEPT ,AVG(SALARY) AS AVG_SAL

FROM EMPLOYEEGROUP BY WORKDEPT) AS AVG_TAB

WHERE E.WORKDEPT = AVG_TAB.WORKDEPTORDER BY E.WORKDEPT, EMPNO

Problem 4

WITH CAR_PARTS (LEVEL, ASSEMBLY, COMPONENT, QUANTITY) AS(SELECT 0, ROOT.ASSEMBLY, ROOT.COMPONENT, ROOT.QUANTITY

FROM CARS ROOTWHERE ROOT.LEVEL = 2AND ASSEMBLY = 'PASSENGER COMPARTMENT'UNION ALLSELECT PARENT.LEVEL + 1, CHILD.ASSEMBLY, CHILD.COMPONENT, CHILD.QUANTITYFROM CAR_PARTS PARENT, CARS CHILDWHERE PARENT.COMPONENT = CHILD.ASSEMBLYAND PARENT.LEVEL < 1)

SELECT LEVEL, ASSEMBLY, COMPONENT, QUANTITYFROM CAR_PARTSORDER BY LEVEL, ASSEMBLY, COMPONENT

END OF SOLUTION

Exercise 7. Table Expressions and Recursive SQL 7-9 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

7-10 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise 8. Performance and UDT/UDF

What This Exercise Is About

This exercise will help you predict whether or not specific SQLstatements will use indexes.

What You Should Be Able to Do

At the end of the lab, you should:

Have a feeling for efficient and inefficient SQL statements

Understand that DB2 performance is dependent on manyfactors

Have some experience with UDT and sourced UDF

Introduction

Note: The first part is a paper exercise. You do not have to writeor execute any SQL statements to solve problem 1-7.

Assume that table EMPLOYEE has the following indexes:

A unique index on column EMPNO.

A non-unique multi-column index on columns LASTNAME andFIRSTNME, in that order.

A non-unique index on column WORKDEPT.

The table contains one million rows and the catalog statistics forthis table just were refreshed.

Required Materials

You can use the student handout

Exercise 8. Performance & UDT/UDF 8-1 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Exercise Instructions

Problem 1

Can DB2 use an index for the following query? Why?

SELECT FIRSTNME, LASTNAMEFROM EMPLOYEEWHERE PHONENO = '1793'

Problem 2

Can DB2 use an index for the following query? Why?

SELECT EMPNO, FIRSTNME, LASTNAME, WORKDEPTFROM EMPLOYEE

Problem 3

Can DB2 use an index for the following query? Why?

SELECT EMPNO, FIRSTNME, LASTNAME, PHONENO, HIREDATEFROM EMPLOYEEWHERE LASTNAME LIKE 'J%'

Problem 4

Can DB2 use an index for the following query? Why?

SELECT FIRSTNME, LASTNAMEFROM EMPLOYEEWHERE SUBSTR(LASTNAME,1,1) = 'J'

8-2 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 5

Can DB2 use only an index to obtain the result when performing thefollowing query? This means that table EMPLOYEE would not beaccessed. Why?

SELECT FIRSTNMEFROM EMPLOYEEWHERE LASTNAME = 'STERN'

Problem 6

Can DB2 use an index for the following query? Why?

SELECT COUNT(*)FROM EMPLOYEE

Problem 7

Can DB2 use the index on WORKDEPT for the following query? Why?

SELECT *FROM EMPLOYEEWHERE WORKDEPT BETWEEN 'C01' AND 'D11'

Problem 8

Create two User-Defined Distinct Data types, one for German markscalled GER_MARK and one for British pounds called UK_POUND. Letthem both be based on DECIMAL(9,2).

Problem 9

Add two columns to the EMPLOYEE table. One called GER_SAL and theother UK_SAL. Define GER_SAL as GER_MARK and UK_SAL asUK_POUND. OS/390 user will have to use table TESTEMP instead ofEMPLOYEE as EMPLOYEE is a view in OS/390.

Exercise 8. Performance & UDT/UDF 8-3 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 10

Create sourced column functions to calculate average, find minimumand maximum values for the new data types.

UPDATE the new columns in EMPLOYEE with following values:

EMPNO GER_SAL UK_SAL000010 100000 40000000020 80000 31000000030 72000 29000

Use your new user defined functions to calculate the average salary inGerman marks and British Pounds for these three employees.

END OF LAB

8-4 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Solution

Problem 1

DB2 is unlikely to use an index in this case because there is no indexon column PHONENO.

Problem 2

DB2 is unlikely to use an index in this case because the result set willcontain all rows of the table. Using an index would not reduce the sizeof the result set and would only add extra reads to the processing. DB2normally reads the whole table without using an index when all of therows are required for the result set.

Problem 3

DB2 can use an index in this case because the leftmost part of the lastname is known and the index of LASTNAME and FIRSTNME hasLASTNAME as its leftmost column.

Problem 4

This query is logically equivalent to the one in Problem 3. However, ituses the SUBSTR() function, which is considered an expression.Normally, DB2 does not consider an index when a predicate contains anexpression.

Problem 5

Rows do not have to be read from the EMPLOYEE table because theindex on LASTNAME, FIRSTNME contains the selected columnFIRSTNME. This is called index only access.

Problem 6

DB2 uses an index in this case if the cost of counting index entries isless than the cost of counting the rows in the table. The size andfragmentation of the table and of the index are an important factor here.

Exercise 8. Performance & UDT/UDF 8-5 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 7

DB2 might use the index on the WORKDEPT column if its analysis showsthat there are relatively few departments in the range from 'C01' to'D11'. Otherwise, it is unlikely to use an index. DB2 keeps statistics onthe most frequently occurring values in a given index. These statisticsare used in cases like this one to determine whether or not there is anysignificant benefit in using the index on the WORKDEPT column. Theactual statistics kept vary somewhat from platform to platform andversion to version.

Problem 8

create distinct type UK_POUND as decimal(9,2) with comparisons;create distinct type GER_MARK as decimal(9,2) with comparisons;

Problem 9

ALTER TABLE EMPLOYEE ADD GER_SAL GER_MARK;ALTER TABLE EMPLOYEE ADD UK_SAL UK_POUND;

8-6 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

Problem 10

Create sourced column functions to calculate average, find minimumand maximum values for the new data types.

CREATE FUNCTION AVG(UK_POUND)RETURNS UK_POUNDSOURCE AVG(DECIMAL);

CREATE FUNCTION MIN(UK_POUND)RETURNS UK_POUNDSOURCE MIN(DECIMAL);

CREATE FUNCTION MAX(UK_POUND)RETURNS UK_POUNDSOURCE MAX(DECIMAL);

CREATE FUNCTION AVG(GER_MARK)RETURNS GER_MARKSOURCE AVG(DECIMAL);

CREATE FUNCTION MIN(GER_MARK)RETURNS GER_MARKSOURCE AVG(DECIMAL);

CREATE FUNCTION MAX(GER_MARK)RETURNS GER_MARKSOURCE AVG(DECIMAL);

UPDATE the new columns in EMPLOYEE with following values:

EMPNO GER_SAL UK_SAL000010 100000 40000000020 80000 31000000030 72000 29000

UPDATE EMPLOYEE SET GER_SAL=100000, UK_SAL=40000 WHERE EMPNO='000010';UPDATE EMPLOYEE SET GER_SAL=80000, UK_SAL=31000 WHERE EMPNO='000020';UPDATE EMPLOYEE SET GER_SAL=72000, UK_SAL=29000 WHERE EMPNO='000030';

Use your new user defined functions to calculate the average salary inGerman Marks and British Pounds for these three employees.

SELECT AVG(GER_SAL) AS MARKS,AVG(UK_SAL) AS POUNDSFROM EMPLOYEEWHERE EMPNO IN ('000010','000020','000030')

END OF SOLUTION

Exercise 8. Performance & UDT/UDF 8-7 Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.

Student Exercises

8-8 DB2 SQL for Experienced Users Copyright IBM Corp. 1998, 2001Course materials may not be reproduced in whole or in part

without the prior written permission of IBM.