104
DB2 SQL Workshop for Experienced Users (Course Code CF13) Student Exercises ERC 5.0 Worldwide Certified Material IBM Learning Services V1.2.2.2 cover

Student Exercises - comp.hkbu.edu.hk

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Student Exercises - comp.hkbu.edu.hk

DB2 SQL Workshopfor Experienced Users (Course Code CF13)

Student ExercisesERC 5.0

Worldwide Certified MaterialIBM Learning Services

V1.2.2.2

cover

Page 2: Student Exercises - comp.hkbu.edu.hk

Student Exercises

The information contained in this document has not been submitted to any formal IBM test and is distributed on an “as is” basis withoutany warranty either express or implied. The use of this information or the implementation of any of these techniques is a customerresponsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment. Whileeach item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results willresult elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk. The originalrepository material for this course has been certified as being Year 2000 compliant.

© Copyright International Business Machines Corporation 1998, 2002. 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 or disclosure is subject to restrictionsset forth in GSA ADP Schedule Contract with IBM Corp.

Trademarks

IBM® is a registered trademark of International Business Machines Corporation.

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

Linux is a registered trademark of Linus Torvalds in the United States and other countries.

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

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

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

AIX AS/400 DataJoinerDB2 DB2 Universal Database IBMOS/2 OS/390 OS/400Perform PowerPC PS/2QMF SQL/DS

November 2002 Edition

Page 3: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

TOC

Contents

Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v

Exercises Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Table Descriptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv

Table Content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Contents iii

Page 4: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

iv DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 5: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

TMK

Trademarks

The reader should recognize that the following terms, which appear in the content of this training document, are official trademarks of IBM or other companies:

IBM® is a registered trademark of International Business Machines Corporation.

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

Linux is a registered trademark of Linus Torvalds in the United States and other countries.

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

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

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

AIX AS/400 DataJoinerDB2 DB2 Universal Database IBMOS/2 OS/390 OS/400Perform PowerPC PS/2QMF SQL/DS

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Trademarks v

Page 6: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

vi DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 7: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

Exercises Description

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

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

Expected Results — repeats the problem and shows the results that you should get if you run the query. In most cases, the complete result is shown. In cases where the result set is too large, an ellipsis (...) is shown to indicate that there are additional rows in the result. In these cases, the correct number of rows for the result set is shown so that you can be sure that you got the right 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 the document. If you have any doubts about whether your solution is correct or if it is as good as the given solution from a performance point of view, please consult your instructor.

General Information

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

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

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

You will be able to use any of the query tools that we have installed on each operating system. Please note that the emphasis of 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 this course. If you want more information about these tools, ask the instructor for recommendations on the best manuals to read or courses to take for this purpose.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercises Description vii

Page 8: Student Exercises - comp.hkbu.edu.hk

Student Exercises

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

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

viii DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 9: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

General Information for OS/390 Users

There are many different query tools that work with DB2 for OS/390, including DB2 UDB Connect, SPUFI, QMF, and others. You can use any tool installed to do the labs. The following query tools are available for this course:

• __________________________ • __________________________ • __________________________

The instructor will tell you how to logon to the OS/390 system and what specific user ID and password to use. In addition, you will probably be given a team number: this number will be used occasionally during the exercises so that you can distinguish your files 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 on how to use the tool you choose so that you will have enough information 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 the exercises. This dataset already exists.

The dataset name is __________________________________________.

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

The qualifier is _______________.

When you refer to these tables in your SQL, you will need to prefix the table names with the qualifier identified above. For example, if you 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 table has not been provided in advance. You may need to add an IN clause to your CREATE TABLE statements that identifies where the table is being created. The IN clause you need to add is:

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercises Description ix

Page 10: Student Exercises - comp.hkbu.edu.hk

Student Exercises

IN _________________________________.

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

SELECT * FROM TESTEMP or SELECT * FROM logon ID.TESTEMP

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

x DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 11: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

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

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

• __________________________ • __________________________ • __________________________

Students doing the exercises on workstation platforms do not need a team number. Each workstation student has a complete standalone environment and will not share any files or tables with other students. Each student will have to sign on with the following information:

USERID is ______________________ PASSWORD is ____________________

The instructor will give you brief verbal or written instructions on how to use the tool you choose so that you have enough information 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 at a command prompt:

db2 connect to sample

• To connect in a client/server environment, enter the following at a command prompt, substituting the userid and password you were assigned:

db2 connect to sample user userid using password

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

The qualifier is _________________.

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

SELECT * FROM qualifier.EMPLOYEE

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercises Description xi

Page 12: Student Exercises - comp.hkbu.edu.hk

Student Exercises

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

DB2 -tvf CRTAB

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

SELECT * FROM TESTEMP or SELECT * FROM logon ID.TESTEMP

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xii DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 13: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

Figure 0-1. Table Relationships CF135.0

Notes:

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

�������������

������ ����

�����������

����� ������

����������

����� �����

����������

����� ������ � ����

��� � ����������

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercises Description xiii

Page 14: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xiv DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 15: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

Table Descriptions

The tables are described in hierarchical order, as shown in the Table Relationships on the 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 allowed

DEPTNO Department Number CHAR(3) N

DEPTNAME Department Name VARCHAR(36) N

MGRNO Employee Number of the Responsible Manager

CHAR(6) Y

ADMRDEPT Department Number of the Department to which the Department reports

CHAR(3) N

LOCATION Location Number CHAR(5) Y

Column Name Meaning Data Type NULLS allowed

EMPNO Employee Number CHAR(6) N

FIRSTNME First Name VARCHAR(20) N

MIDINIT Middle Initial CHAR(1) N

LASTNAME Last Name VARCHAR(15) N

WORKDEPT Department in which the Employee Works CHAR(3) Y

PHONENO Phone Number CHAR(4) Y

HIREDATE Date of Hire DATE Y

JOB Job CHAR(8) Y

EDLEVEL Number of Years of Formal Education SMALLINT Y

SEX Sex (M male, F female) CHAR(1) Y

BIRTHDATE Date of Birth DATE Y

SALARY Yearly Salary DECIMAL(9, 2) Y

BONUS Yearly Bonus DECIMAL(9, 2) Y

COMM Yearly Commission DECIMAL(9, 2) Y

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Table Descriptions xv

Page 16: Student Exercises - comp.hkbu.edu.hk

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 allowed

PROJNO Project Number CHAR(6) N

PROJNAME Project Name VARCHAR(24) N

DEPTNO Responsible Department CHAR(3) N

RESPEMP Employee Number of the Responsible Employee

CHAR(6) N

PRSTAFF Estimated Mean Staffing DECIMAL(5, 2) Y

PRSTDATE Estimated Start Date DATE Y

PRENDATE Estimated End Date DATE Y

MAJPROJ Major Project for a Subproject CHAR(6) Y

Column Name Meaning Data Type NULLS allowed

EMPNO Employee Number of Employee Performing the Activity

CHAR(6) N

PROJNO Project Number CHAR(6) N

ACTNO Activity Number SMALLINT N

EMPTIME Proportion of Employee's Time Spent on Project

DECIMAL(5, 2) Y

EMSTDATE Date Activity Starts DATE Y

EMENDATE Date Activity Ends DATE Y

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xvi DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 17: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

Table Content

DEPARTMENT Table

DEPTNO DEPTNAME MGRNO ADMRDEPT LOCATION ------ ------------------------------ ------ -------- -------- A00 SPIFFY COMPUTER SERVICE DIV. 000010 A00 B01 PLANNING 000020 A00 C01 INFORMATION CENTER 000030 A00 D01 DEVELOPMENT CENTER - A00 D11 MANUFACTURING SYSTEMS 000060 D01 D21 ADMINISTRATION SYSTEMS 000070 D01 E01 SUPPORT SERVICES 000050 A00 E11 OPERATIONS 000090 E01 E21 SOFTWARE SUPPORT 000100 E01

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Table Content xvii

Page 18: Student Exercises - comp.hkbu.edu.hk

Student Exercises

EMPLOYEE Table

EMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO HIREDATE ------ ---------- ------- ---------- -------- ------- ---------- 000010 CHRISTINE I HAAS A00 3978 1965-01-01 000020 MICHAEL L THOMPSON B01 3476 1973-10-10 000030 SALLY A KWAN C01 4738 1975-04-05 000050 JOHN B GEYER E01 6789 1949-08-17 000060 IRVING F STERN D11 6423 1973-09-14 000070 EVA D PULASKI D21 7831 1980-09-30 000090 EILEEN W HENDERSON E11 5498 1970-08-15 000100 THEODORE Q SPENSER E21 0972 1980-06-19 000110 VINCENZO G LUCCHESI A00 3490 1958-05-16 000120 SEAN O'CONNELL A00 2167 1963-12-05 000130 DOLORES M QUINTANA C01 4578 1971-07-28 000140 HEATHER A NICHOLLS C01 1793 1976-12-15 000150 BRUCE ADAMSON D11 4510 1972-02-12 000160 ELIZABETH R PIANKA D11 3782 1977-10-11 000170 MASATOSHI J YOSHIMURA D11 2890 1978-09-15 000180 MARILYN S SCOUTTEN D11 1682 1973-07-07 000190 JAMES H WALKER D11 2986 1974-07-26 000200 DAVID BROWN D11 4501 1966-03-03 000210 WILLIAM T JONES D11 0942 1979-04-11 000220 JENNIFER K LUTZ D11 0672 1968-08-29 000230 JAMES J JEFFERSON D21 4265 1966-11-21 000240 SALVATORE M MARINO D21 3780 1979-12-05 000250 DANIEL S SMITH D21 0961 1969-10-30 000260 SYBIL V JOHNSON D21 8953 1975-09-11 000270 MARIA L PEREZ D21 9001 1980-09-30 000280 ETHEL R SCHNEIDER E11 8997 1967-03-24 000290 JOHN R PARKER E11 4502 1980-05-30 000300 PHILIP X SMITH E11 2095 1972-06-19 000310 MAUDE F SETRIGHT E11 3332 1964-09-12 000320 RAMLAL V MEHTA E21 9990 1965-07-07 000330 WING LEE E21 2103 1976-02-23 000340 JASON R GOUNOT E21 5698 1947-05-05

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xviii DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 19: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

EMPLOYEE Table (Cont)

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Table Content xix

Page 20: Student Exercises - comp.hkbu.edu.hk

Student Exercises

PROJECT Table

DEPT PR PROJNO 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 AD3100 AD3111 PAYROLL PROGRAMMING D21 000230 2.00 1982-01-01 1983-02-01 AD3110 AD3112 PERSONNEL PROGRAMMG D21 000250 1.00 1982-01-01 1983-02-01 AD3110 AD3113 ACCOUNT.PROGRAMMING D21 000270 2.00 1982-01-01 1983-02-01 AD3110 IF1000 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 MA2100 MA2111 W L PROGRAM DESIGN D11 000220 2.00 1982-01-01 1982-12-01 MA2110 MA2112 W L ROBOT DESIGN D11 000150 3.00 1982-01-01 1982-12-01 MA2110 MA2113 W L PROD CONT PROGS D11 000160 3.00 1982-02-15 1982-12-01 MA2110 OP1000 OPERATION SUPPORT E01 000050 6.00 1982-01-01 1983-02-01 - OP1010 OPERATION E11 000090 5.00 1982-01-01 1983-02-01 OP1000 OP2000 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 OP2000 OP2011 SCP SYSTEMS SUPPORT E21 000320 1.00 1982-01-01 1983-02-01 OP2010 OP2012 APPLICATIONS SUPPORT E21 000330 1.00 1982-01-01 1983-02-01 OP2010 OP2013 DB/DC SUPPORT E21 000340 1.00 1982-01-01 1983-02-01 OP2010 PL2100 WELD LINE PLANNING B01 000020 1.00 1982-01-01 1982-09-15 MA2100

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xx DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 21: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

EMP_ACT Table

EMPNO PROJNO ACTNO EMPTIME EMSTDATE EMENDATE ------ ------ ------ -------- ---------- ---------- 000010 AD3100 10 0.50 1982-01-01 1982-07-01 000070 AD3110 10 1.00 1982-01-01 1983-02-01 000230 AD3111 60 1.00 1982-01-01 1982-03-15 000230 AD3111 60 0.50 1982-03-15 1982-04-15 000230 AD3111 70 0.50 1982-03-15 1982-10-15 000230 AD3111 80 0.50 1982-04-15 1982-10-15 000230 AD3111 180 1.00 1982-10-15 1983-01-01 000240 AD3111 70 1.00 1982-02-15 1982-09-15 000240 AD3111 80 1.00 1982-09-15 1983-01-01 000250 AD3112 60 0.50 1982-02-01 1982-03-15 000250 AD3112 60 1.00 1982-01-01 1982-02-01 000250 AD3112 60 1.00 1983-01-01 1983-02-01 000250 AD3112 60 0.50 1982-12-01 1983-01-01 000250 AD3112 70 1.00 1982-03-15 1982-08-15 000250 AD3112 70 0.50 1982-02-01 1982-03-15 000250 AD3112 70 0.25 1982-08-15 1982-10-15 000250 AD3112 80 0.25 1982-08-15 1982-10-15 000250 AD3112 80 0.50 1982-10-15 1982-12-01 000250 AD3112 180 0.50 1982-08-15 1983-01-01 000260 AD3113 70 0.50 1982-06-15 1982-07-01 000260 AD3113 70 1.00 1982-07-01 1983-02-01 000260 AD3113 80 1.00 1982-01-01 1982-03-01 000260 AD3113 80 0.50 1982-03-01 1982-04-15 000260 AD3113 180 0.50 1982-03-01 1982-04-15 000260 AD3113 180 0.50 1982-06-01 1982-07-01 000260 AD3113 180 1.00 1982-04-15 1982-06-01 000270 AD3113 60 0.25 1982-09-01 1982-10-15 000270 AD3113 60 1.00 1982-04-01 1982-09-01 000270 AD3113 60 0.50 1982-03-01 1982-04-01 000270 AD3113 70 0.75 1982-09-01 1982-10-15 000270 AD3113 70 1.00 1982-10-15 1983-02-01 000270 AD3113 80 1.00 1982-01-01 1982-03-01 000270 AD3113 80 0.50 1982-03-01 1982-04-01 000030 IF1000 10 0.50 1982-06-01 1983-01-01 000130 IF1000 90 1.00 1982-01-01 1982-10-01 000130 IF1000 100 0.50 1982-10-01 1983-01-01 000140 IF1000 90 0.50 1982-10-01 1983-01-01

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Table Content xxi

Page 22: Student Exercises - comp.hkbu.edu.hk

Student Exercises

EMP_ACT Table (Cont)

EMPNO PROJNO ACTNO EMPTIME EMSTDATE EMENDATE ------ ------ ------ -------- ---------- ---------- 000030 IF2000 10 0.50 1982-01-01 1983-01-01 000140 IF2000 100 1.00 1982-01-01 1982-03-01 000140 IF2000 100 0.50 1982-03-01 1982-07-01 000140 IF2000 110 0.50 1982-03-01 1982-07-01 000140 IF2000 110 0.50 1982-10-01 1983-01-01 000010 MA2100 10 0.50 1982-01-01 1982-11-01 000110 MA2100 20 1.00 1982-01-01 1982-03-01 000010 MA2110 10 1.00 1982-01-01 1983-02-01 000200 MA2111 50 1.00 1982-01-01 1982-06-15 000200 MA2111 60 1.00 1982-06-15 1983-02-01 000220 MA2111 40 1.00 1982-01-01 1983-02-01 000150 MA2112 60 1.00 1982-01-01 1982-07-15 000150 MA2112 180 1.00 1982-07-15 1983-02-01 000170 MA2112 60 1.00 1982-01-01 1983-06-01 000170 MA2112 70 1.00 1982-06-01 1983-02-01 000190 MA2112 70 1.00 1982-02-01 1982-10-01 000190 MA2112 80 1.00 1982-10-01 1983-10-01 000160 MA2113 60 1.00 1982-07-15 1983-02-01 000170 MA2113 80 1.00 1982-01-01 1983-02-01 000180 MA2113 70 1.00 1982-04-01 1982-06-15 000210 MA2113 80 0.50 1982-10-01 1983-02-01 000210 MA2113 180 0.50 1982-10-01 1983-02-01 000050 OP1000 10 0.25 1982-01-01 1983-02-01 000090 OP1010 10 1.00 1982-01-01 1983-02-01 000280 OP1010 130 1.00 1982-01-01 1983-02-01 000290 OP1010 130 1.00 1982-01-01 1983-02-01 000300 OP1010 130 1.00 1982-01-01 1983-02-01 000310 OP1010 130 1.00 1982-01-01 1983-02-01 000050 OP2010 10 0.75 1982-01-01 1983-02-01 000100 OP2010 10 1.00 1982-01-01 1983-02-01 000320 OP2011 140 0.75 1982-01-01 1983-02-01 000320 OP2011 150 0.25 1982-01-01 1983-02-01 000330 OP2012 140 0.25 1982-01-01 1983-02-01 000330 OP2012 160 0.75 1982-01-01 1983-02-01 000340 OP2013 140 0.50 1982-01-01 1983-02-01 000340 OP2013 170 0.50 1982-01-01 1983-02-01 000020 PL2100 30 1.00 1982-01-01 1982-09-15 The last row for employee 000020 has been added twice in the Sample database for DB2 UDB for Windows.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xxii DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 23: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

CARS Table

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

LEVEL ASSEMBLY COMPONENT QUANTITY ------ ------------------------- ------------------------- -------- 1 HONDA ACCORD ENGINE COMPARTMENT 1 1 HONDA ACCORD PASSENGER COMPARTMENT 1 2 ENGINE COMPARTMENT ENGINE 1 2 ENGINE COMPARTMENT IGNITION SYSTEM 1 2 PASSENGER COMPARTMENT SEAT GROUP 3 2 PASSENGER COMPARTMENT DASHBOARD 1 2 PASSENGER COMPARTMENT TRUNK 1 3 ENGINE CAMSHAFT 1 3 ENGINE CRANKSHAFT 1 3 ENGINE PISTON 4 3 ENGINE CONNECTING ROD 4 3 SEAT GROUP FRONT SEAT ASSEMBLY 2 3 SEAT GROUP REAR SEAT ASSEMBLY 1 3 DASHBOARD VENT 4 3 DASHBOARD STEREO SYSTEM 1 3 DASHBOARD GAUGE CLUSTER 1 3 DASHBOARD CONTROL CLUSTER 1 3 TRUNK TOOL KIT 1 4 STEREO SYSTEM RADIO 1 4 STEREO SYSTEM CD PLAYER 1 4 GAUGE CLUSTER SPEEDOMETER 1 4 GAUGE CLUSTER ODOMETER 1 4 CONTROL CLUSTER FOG LAMP CONTROL 1 4 CONTROL CLUSTER FOUR WAY FLASHER CONTROL 1 4 CONTROL CLUSTER TURN SIGNAL CONTROL 1 4 FRONT SEAT ASSEMBLY FRONT SEAT 1 4 FRONT SEAT ASSEMBLY LAP/SHOULDER BELT 1 4 REAR SEAT ASSEMBLY REAR SEAT 1 4 REAR SEAT ASSEMBLY LAP/SHOULDER BELT 3 4 REAR SEAT ASSEMBLY SHOULDER BELT 3

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Table Content xxiii

Page 24: Student Exercises - comp.hkbu.edu.hk

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 .00 000010 HAAS A00 01.01.1965 52750.00 1000.00 000020 THOMPSON B01 10.10.1973 41250.00 800.00 000030 KWAN C01 05.04.1975 38250.00 800.00 000050 GEYER E01 17.08.1949 40175.00 800.00

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xxiv DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 25: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2

pref

Content of VIEWS

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

VEMPLOYEE View

EMPNO LASTNAME SALARY WORKDEPT ------ --------- -------- -------- 000010 HAAS 52750.00 A00 000030 KWAN 38250.00 C01 000120 O'CONNELL 29250.00 A00 000130 QUINTANA 23800.00 C01 000140 NICHOLLS 28420.00 C01 VDEPARTMENT View DEPTNO DEPTNAME MGRNO ------ ---------------------------- ------ A00 SPIFFY COMPUTER SERVICE DIV. 000010 C01 INFORMATION CENTER 000030 D01 DEVELOPMENT CENTER ------ VPROJECT View PROJNO PROJNAME DEPTNO RESPEMP ------ -------------- ------ ------- AD3100 ADMIN SERVICES D01 000010 IF1000 QUERY SERVICES C01 000030 IF2000 USER EDUCATION C01 000030

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Table Content xxv

Page 26: Student Exercises - comp.hkbu.edu.hk

Student Exercises

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

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

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

xxvi DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 27: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

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, and RANK.

Introduction

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

Required Materials

• Student handout • SQL Reference

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 1. SQL Basics Review, CUBE and ROLLUP 1-1

Page 28: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions

Ron is the SQL specialist in the department. Joe is a colleague of Ron and does not have SQL knowledge. Joe asked Ron for help to solve the following problems.

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

Problem 1

Joe's manager wants information about employees which match the following 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 department number of the appropriate employees.

Problem 2

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

Problem 3

Joe's manager is interested in some additional salary information. This time, he wants information for every department that appears in the EMPLOYEE table, provided that the department has more than five employees. The report needs to show the department number, the minimum, maximum, and average yearly salary, and the number of employees who work in the department.

Problem 4

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

List the department, the sex, sum of the salaries, minimum salary and maximum salary.

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

Problem 5

Joe's manager wants information about the average total salary for all departments. List in department order, the department, average total salary and rank over the average total salary.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-2 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 29: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Exercise Instructions With Hints (Expected Results)

Problem 1

Joe's manager wants information about employees which match the following 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 department number of the appropriate employees.

Result

EMPNO LASTNAME SALARY WORKDEPT ------ --------- -------- --------- 000160 PIANKA 22250.00 D11 000230 JEFFERSON 22180.00 D21

Problem 2

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

Result

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

When returning the result of a calculation, the number of digits in the fractional part (scale) may differ for DB2 UDB on different platforms.

Problem 3

Joe's manager is interested in some additional salary information. This time, he wants information for every department that appears in the EMPLOYEE table, provided that the department has more than five employees. The report needs to show the department number, the minimum, maximum, and average yearly salary, and the number of employees who work in the department.

Result

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 1. SQL Basics Review, CUBE and ROLLUP 1-3

Page 30: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 4

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

List the department, the sex, minimum salary, maximum salary, and sum of the salaries.

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

Result

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

Problem 5

Joe's manager wants information about the average total salary for all departments. List in department order, the department, average total salary and rank over the average total salary.

Hint: RANK() OVER (ORDER BY AVG(SALARY+BONUS) DESC)

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

Result

WORKDEPT AVG_TOTAL_SALARY RANK_AVG_SAL -------- --------------------------------- --------------------A00 43666.66666666666666666666666 1B01 42050.00000000000000000000000 2C01 30790.00000000000000000000000 4D11 25166.66666666666666666666666 6D21 25636.66666666666666666666666 5E01 40975.00000000000000000000000 3E11 21418.00000000000000000000000 8E21 24302.50000000000000000000000 7

END OF LAB (with hints)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-4 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 31: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Solution

Problem 1

SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM EMPLOYEE WHERE 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 EMPLOYEE WHERE EDLEVEL = 16

Problem 3

SELECT WORKDEPT, MIN(SALARY) AS MIN, MAX(SALARY) AS MAX, AVG(SALARY) AS AVG, COUNT(*) AS COUNT FROM EMPLOYEE GROUP BY WORKDEPT HAVING COUNT(*) > 5

Problem 4

SELECT WORKDEPT,SEX,MIN(SALARY) AS MIN,MAX(SALARY) AS MAX, SUM(SALARY) AS SUM FROM EMPLOYEE WHERE WORKDEPT LIKE 'D%' GROUP BY CUBE (WORKDEPT,SEX)

Problem 5

SELECT WORKDEPT, AVG(SALARY+BONUS) AS AVG_TOTAL_SALARY, RANK() OVER (ORDER BY AVG(SALARY+BONUS) DESC) AS RANK_AVG_SAL FROM EMPLOYEE GROUP BY WORKDEPT ORDER BY WORKDEPT

END OF SOLUTION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 1. SQL Basics Review, CUBE and ROLLUP 1-5

Page 32: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

1-6 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 33: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Exercise 2. Create Objects

What This Exercise Is About

This exercise gives you an opportunity to implement a small data model.

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 the column names and descriptions for each table.

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

Required Materials

• Student handout • SQL Reference

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 2. Create Objects 2-1

Page 34: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions

Harvey needs your help to create a database for his test environment. He has accurately 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:

• EMPNO • LASTNAME • SALARY • DEPTNO • DEP_NAME

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

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) must not exceed 28000.

• No employee in any department may have a yearly salary that exceeds 50000.

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

Create the table HIGH_SALARY_RAISE with the following columns:

• EMPNO • PREV_SAL • NEW_SAL

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-2 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 35: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

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 which exist in the EMPLOYEE table. If an employee is deleted from the EMP table, the corresponding row in the EMPDEPT table should also be immediately deleted.

The EMPDEPT table should only allow values in column DEPTNO which exist in the DEPARTMENT table. It should not be possible to delete a department from the DEPARTMENT table as long as a corresponding DEPTNO exists in the EMPDEPT table.

Note: In DB2 for OS/390 the used sample tables are originally defined as views. You can not have a foreign key reference a view. Ask your instructor for the name and the qualifier of the tables which should be referenced.

Problem 3

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

Problem 4

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

Did your insert work?

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 2. Create Objects 2-3

Page 36: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 5

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

Ethel Schneider works in the operations department. Her department number is E11, and her employee number is 000280. Try to set her yearly 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 a raise. Set her yearly salary to 25000. Inspect the HIGH_SALARY_RAISE table to see if the trigger worked.

Problem 7

Create a view named VEMPPAY that contains one row for each employee in the company. Each row should contain employee number, last name, department number, and total earnings for the corresponding employee. Total earnings means salary plus bonus plus commission for the employee. Then, determine the average of the earnings for the departments 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 be displayed when you use the view.

Note: It is very important that you base this view on the TESTEMP table that 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) changed jobs and will get a new salary of 51000. Update the data for employee number 000020 using the view VEMP1.

Display the view again, arranging the rows in employee number sequence.

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 the value of 41250.

Create a view named VEMP2 which has the same definition as in problem 8, but add a CHECK OPTION. Again, base the view on your TESTEMP table.

Display the rows in the view in employee number sequence.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-4 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 37: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

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

Display the view again, arranging the rows in employee number sequence.

Query Geyer's row in your TESTEMP table.

Did the data in the base table change?

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 2. Create Objects 2-5

Page 38: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

Create the table EMPDEPT with these columns:

• EMPNO • LASTNAME • SALARY • DEPTNO • DEP_NAME

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

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) must not exceed 28000.

• No employee in any department may have a yearly salary that exceeds 50000.

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

Create the table HIGH_SALARY_RAISE with the following columns:

• EMPNO • PREV_SAL • NEW_SAL

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

Result

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-6 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 39: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

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 which exist in the EMPLOYEE table. If an employee is deleted from the EMP table, the corresponding row in the EMPDEPT table should also be immediately deleted.

The EMPDEPT table should only allow values in column DEPTNO which exist in the DEPARTMENT table. It should not be possible to delete a department from the DEPARTMENT table as long as a corresponding DEPTNO exists in the EMPDEPT table.

Note: In DB2 for OS/390 the used sample tables are originally defined as views. You can not have a foreign key reference a view. Ask your instructor for the name and the qualifier of the tables which should be referenced.

Result

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

Problem 3

Klaus must update the yearly salaries for the employees of the EMPDEPT table. If the new value for a salary exceeds the previous value by 10 percent or more, Harvey wants to insert a row into the HIGH_SALARY_RAISE table. The values in this row should be the employee number, the previous salary, and the new salary. Create something in DB2 that will ensure that a row is inserted into the HIGH_SALARY_RAISE table whenever an employee of the EMPDEPT table 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 combined contents of tables EMPLOYEE and DEPARTMENT as the source for your data.

Did your insert work?

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

Result

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 2. Create Objects 2-7

Page 40: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 5

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

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

Result

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

Problem 6

Harvey wants to see if the trigger works.

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

Result

The UPDATE for Elizabeth Pianka should succeed and should fire the trigger. You can verify that the trigger has fired by examining the contents of the HIGH_SALARY_RAISE table. You should see a row there for 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 each employee in the company. Each row should contain employee number, last name, department number, and total earnings for the corresponding employee. Total earnings means salary plus bonus plus commission for the employee. Then, determine the average of the earnings for the departments by using the view you just created.

Result

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-8 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 41: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

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 be displayed when you use the view.

Note: It is very important that you base this view on the TESTEMP table that 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) changed jobs and will get a new salary of 51000. Update the data for employee number 000020 using the view VEMP1.

Display the view again, arranging the rows in employee number sequence.

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 B01 000030 KWAN 38250.00 C01 000050 GEYER 40175.00 E01 000111 SMITH 25000.00 C01

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

EMPNO LASTNAME SALARY WORKDEPT ------ -------- -------- -------- 000030 KWAN 38250.00 C01 000050 GEYER 40175.00 E01 000111 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.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 2. Create Objects 2-9

Page 42: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 9

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

Create a view named VEMP2 which has the same definition as in problem 8, but add a CHECK OPTION. Again, base the view on your TESTEMP table.

Display the rows in the view in employee number sequence.

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

Display the view again, arranging the rows in employee number sequence.

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 B01 000030 KWAN 38250.00 C01 000050 GEYER 40175.00 E01 000111 SMITH 25000.00 C01

The SQLCODE (-161 in OS/390, SQL0161N on the workstation) indicates that 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 B01 000030 KWAN 38250.00 C01 000050 GEYER 40175.00 E01 000111 SMITH 25000.00 C01

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

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

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

END OF LAB (with hints)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-10 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 43: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

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 EMPDEPT ADD PRIMARY KEY (EMPNO) ALTER TABLE EMPDEPT ADD FOREIGN KEY (EMPNO) REFERENCES EMPLOYEE ON DELETE CASCADE ALTER TABLE EMPDEPT ADD FOREIGN KEY (DEPTNO) REFERENCES DEPARTMENT ON DELETE RESTRICT

Problem 3

CREATE TRIGGER HIGH_SAL AFTER UPDATE OF SALARY ON EMPDEPT REFERENCING OLD AS O NEW AS N FOR EACH ROW MODE DB2SQL WHEN (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 before the update and NEW the value after the update.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 2. Create Objects 2-11

Page 44: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 4

The correct version of the INSERT is as follows:

INSERT INTO EMPDEPT SELECT E.EMPNO, E.LASTNAME, E.SALARY, D.DEPTNO, D.DEPTNAME FROM EMPLOYEE E, DEPARTMENT D WHERE 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 SALARY column of the EMPDEPT table (SALARY < 50000). The table constraint DEPT_SAL ensures that employees in department E11 have a yearly salary 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 of less than 50000.

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

Problem 5

UPDATE EMPDEPT SET SALARY = 30000 WHERE EMPNO = '000280'

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

UPDATE EMPDEPT SET SALARY = 27999 WHERE EMPNO = '000280'

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

Problem 6

UPDATE EMPDEPT SET SALARY = 25000 WHERE 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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-12 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 45: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Use the view to determine the average total earnings for each department:

SELECT WORKDEPT, AVG(TOTAL_EARNINGS) AS AVG_TOTAL_EARNINGS FROM VEMPPAY GROUP BY WORKDEPT

Problem 8

Create the view:

CREATE VIEW VEMP1 AS SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM TESTEMP WHERE SALARY < 50000

Determine which employees appear in the view:

SELECT * FROM VEMP1 ORDER BY EMPNO

Update the data using the view:

UPDATE VEMP1 SET SALARY = 51000 WHERE EMPNO = '000020'

Display the view again.

SELECT * FROM VEMP1 ORDER BY EMPNO

See if the update worked:

SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM TESTEMP WHERE EMPNO = '000020'

Problem 9

Reset the salary for Thompson:

UPDATE TESTEMP SET SALARY = 41250 WHERE EMPNO = '000020'

Create the view:

CREATE VIEW VEMP2 AS SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM TESTEMP WHERE SALARY < 50000 WITH CHECK OPTION

Determine which employees appear in the view:

SELECT * FROM VEMP2

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 2. Create Objects 2-13

Page 46: Student Exercises - comp.hkbu.edu.hk

Student Exercises

ORDER BY EMPNO

Update the data using the view:

UPDATE VEMP2 SET SALARY = 55000 WHERE EMPNO = '000050'

Display the view again.

SELECT * FROM VEMP2 ORDER BY EMPNO

See if the update worked:

SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM TESTEMP WHERE EMPNO = '000050'

END OF SOLUTION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

2-14 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 47: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Exercise 3. Joins

What This Exercise Is About

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

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 the column names and descriptions for each table.

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

Required Materials

• Student handout • SQL Reference

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 3. Joins 3-1

Page 48: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions

Problem 1

Display all employees who work in the INFORMATION CENTER department. Show department number, employee number and last name for all employees in that department. The list should be ordered by employee number. Use the "old" SQL syntax that puts the join condition in the WHERE clause.

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

Problem 2

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

Problem 3

Bill needs a list of those employees whose departments are involved in projects. The list needs to show employee number, last name, department number, and project name. The list should be ordered by project names within employee numbers.

Problem 4

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

Problem 5

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-2 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 49: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 6

Last, Bill wants to see all projects and all employees in one report. Projects not assigned to departments having employees should also be listed as well as employees who work in departments which are not involved in projects. The list needs to show employee number, last name, department number, and project name. If a project is not assigned to a department having employees, NULLS should be displayed instead of the department number, employee number and last name. If the department of an employee is not involved in a project, display NULLs instead of the project name. The list should be ordered by project name within last name.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 3. Joins 3-3

Page 50: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

Display all employees who work in the INFORMATION CENTER department. Show department number, employee number and last name for all employees in that department. The list should be ordered by employee number. Use the "old" SQL syntax that puts the join condition in the WHERE clause.

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

Result

WORKDEPT EMPNO LASTNAME -------- ------ ---------- C01 000030 KWAN C01 000130 QUINTANA C01 000140 NICHOLLS

Problem 2

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

Result

WORKDEPT EMPNO LASTNAME -------- ------ ---------- C01 000030 KWAN C01 000130 QUINTANA C01 000140 NICHOLLS

Problem 3

Bill needs a list of those employees whose departments are involved in projects. The list needs to show employee number, last name, department number, and project name. The list should be ordered by project names within employee numbers.

Result

EMPNO LASTNAME WORKDEPT PROJNAME ------ --------------- -------- ------------------------000030 KWAN C01 QUERY SERVICES 000030 KWAN C01 USER EDUCATION 000130 QUINTANA C01 QUERY SERVICES 000130 QUINTANA C01 USER EDUCATION 000140 NICHOLLS C01 QUERY SERVICES 000140 NICHOLLS C01 USER EDUCATION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-4 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 51: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 4

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

Result

EMPNO LASTNAME WORKDEPT PROJNAME ------ --------------- -------- ------------------------000010 HAAS A00 - 000030 KWAN C01 QUERY SERVICES 000030 KWAN C01 USER EDUCATION 000120 O'CONNELL A00 - 000130 QUINTANA C01 QUERY SERVICES 000130 QUINTANA C01 USER EDUCATION 000140 NICHOLLS C01 QUERY SERVICES 000140 NICHOLLS C01 USER EDUCATION

Problem 5

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

Result

EMPNO LASTNAME WORKDEPT PROJNAME ------ --------------- -------- ------------------------- - - ADMIN SERVICES 000030 KWAN C01 QUERY SERVICES 000130 QUINTANA C01 QUERY SERVICES 000140 NICHOLLS C01 QUERY SERVICES 000030 KWAN C01 USER EDUCATION 000130 QUINTANA C01 USER EDUCATION 000140 NICHOLLS C01 USER EDUCATION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 3. Joins 3-5

Page 52: Student Exercises - comp.hkbu.edu.hk

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 be listed as well as employees who work in departments which are not involved in projects. The list needs to show employee number, last name, department number, and project name. If a project is not assigned to a department having employees, NULLS should be displayed instead of the department number, employee number and last name. If the department of an employee is not involved in a project, display NULLs instead of the project name. The list should be ordered by project name within last name.

Result

EMPNO LASTNAME WORKDEPT PROJNAME ------ --------------- -------- ------------------------000010 HAAS A00 - 000030 KWAN C01 QUERY SERVICES 000030 KWAN C01 USER EDUCATION 000140 NICHOLLS C01 QUERY SERVICES 000140 NICHOLLS C01 USER EDUCATION 000120 O'CONNELL A00 - 000130 QUINTANA C01 QUERY SERVICES 000130 QUINTANA C01 USER EDUCATION - - - ADMIN SERVICES

END OF LAB (with hints)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-6 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 53: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Solution

Problem 1

SELECT WORKDEPT, EMPNO, LASTNAME FROM VEMPLOYEE, VDEPARTMENT WHERE WORKDEPT = DEPTNO AND DEPTNAME = 'INFORMATION CENTER' ORDER BY EMPNO

Problem 2

SELECT WORKDEPT, EMPNO, LASTNAME FROM VEMPLOYEE INNER JOIN VDEPARTMENT ON WORKDEPT = DEPTNO WHERE DEPTNAME = 'INFORMATION CENTER' ORDER BY EMPNO

Problem 3

SELECT EMPNO, LASTNAME, WORKDEPT, PROJNAME FROM VEMPLOYEE INNER JOIN VPROJECT ON WORKDEPT = DEPTNO ORDER BY EMPNO, PROJNAME

Problem 4

SELECT EMPNO, LASTNAME, WORKDEPT, PROJNAME FROM VEMPLOYEE LEFT OUTER JOIN VPROJECT ON WORKDEPT = DEPTNO ORDER BY EMPNO

Problem 5

SELECT EMPNO, LASTNAME, WORKDEPT, PROJNAME FROM VEMPLOYEE RIGHT OUTER JOIN VPROJECT ON WORKDEPT = DEPTNO ORDER BY PROJNAME

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 3. Joins 3-7

Page 54: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 6

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

END OF SOLUTION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

3-8 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 55: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Exercise 4. CASE and CAST

What This Exercise Is About

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

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 the column names and descriptions for each table.

Required Materials

• Student handout • SQL Reference

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 4. CASE and CAST 4-1

Page 56: Student Exercises - comp.hkbu.edu.hk

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 or normal.

SALARY INCOME -------- -------- less than 25000 LOW between 25000 and 30000 NORMAL higher than 30000 HIGH

Problem 2

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

Problem 3

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

Problem 4

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

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-2 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 57: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

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 or normal.

SALARY INCOME -------- -------- less than 25000 LOW between 25000 and 30000 NORMAL higher than 30000 HIGH

Result

EMPNO FIRSTNME LASTNAME INCOME------ ------------ --------------- ------000060 IRVING STERN HIGH 000150 BRUCE ADAMSON NORMAL000160 ELIZABETH PIANKA LOW 000170 MASATOSHI YOSHIMURA LOW 000180 MARILYN SCOUTTEN LOW 000190 JAMES WALKER LOW 000200 DAVID BROWN NORMAL000210 WILLIAM JONES LOW 000220 JENNIFER LUTZ NORMAL

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 4. CASE and CAST 4-3

Page 58: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 2

For all employees in department D11, display their last name, salary and the difference between their salary and 30000. Sort the list in order by 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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-4 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 59: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 3

For each department, list the percentage of the bonus paid to the employees relative to the total income (salary + bonus + commission) of the employees in that department. Take into account that some departments 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 the salary. Protect from division by 0 in case someone has 0 salary. List the 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)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 4. CASE and CAST 4-5

Page 60: Student Exercises - comp.hkbu.edu.hk

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 INCOME FROM EMPLOYEE WHERE WORKDEPT = 'D11'

Problem 2

SELECT LASTNAME, SALARY, CASE WHEN SALARY >= 30000 THEN SALARY - 30000 ELSE 30000 - SALARY END AS DIFFERENCE FROM EMPLOYEE WHERE WORKDEPT='D11' ORDER BY DIFFERENCE

Problem 3

SELECT WORKDEPT, CASE WHEN SUM(BONUS) > 0 AND SUM(SALARY+BONUS+COMM)> 0 THEN DECIMAL(DECIMAL(SUM(BONUS),8,2)*100.00 / DECIMAL(SUM(SALARY+BONUS+COMM),8,2),8,2) ELSE NULL END AS PERCENTAGE_BONUS FROM EMPLOYEE GROUP BY WORKDEPT

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-6 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 61: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 4

SELECT LASTNAME, CAST(100.0 * COMM / SALARY AS DECIMAL(8,3)) AS COMM_PERCENTAGE FROM EMPLOYEE WHERE CASE WHEN COMM=0 OR SALARY=0 THEN NULL ELSE COMM/SALARY END > 0.08

END OF SOLUTION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 4. CASE and CAST 4-7

Page 62: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

4-8 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 63: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

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 the column names and descriptions for each table.

Required Materials

• Student handout • SQL Reference

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 5. Subqueries 5-1

Page 64: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions

Problem 1

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

Problem 2

Retrieve all employees whose yearly salary is more than the average salary of the employees in their department. For example, if the average yearly salary for department E11 is 20998, show all people in department E11 whose individual salary is higher than 20998. Display department number, employee number, and yearly salary. Sort the result by department number and employee number.

Problem 3

Retrieve all departments having the same number of employees as department 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 of employees who earn more than at least one employee in department D11. Employees in department D11 should not be included in the result. In other words, report on any employees in departments other than D11 whose individual yearly salary is higher than that of at least one employee of department D11. List the employees in employee number sequence.

Problem 5

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

Problem 6

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-2 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 65: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 7

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

Note: The EMP_ACT table in the Sample database of Windows has a duplicate row for employee number ‘000020’. This may effect the result.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 5. Subqueries 5-3

Page 66: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions With Hints (Expected Results)

Problem 1

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

Result

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

Problem 2

Retrieve all employees whose yearly salary is more than the average salary of the employees in their department. For example, if the average yearly salary for department E11 is 20998, show all people in department E11 whose individual salary is higher than 20998. Display department number, employee number, and yearly salary. Sort the result by department number and employee number.

Result

EMPNO SALARY WORKDEPT ------ -------- -------- 000010 52750.00 A00 000110 46500.00 A00 000030 38250.00 C01 000060 32250.00 D11 000150 25280.00 D11 000170 24680.00 D11 000200 27740.00 D11 000220 29840.00 D11 000070 36170.00 D21 000240 28760.00 D21 000270 27380.00 D21 000090 29750.00 E11 000280 26250.00 E11 000100 26150.00 E21 000330 25370.00 E21 000340 23840.00 E21

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-4 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 67: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 3

Retrieve all departments having the same number of employees as department 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 of employees who earn more than at least one employee in department D11. Employees in department D11 should not be included in the result. In other words, report on any employees in departments other than D11 whose individual yearly salary is higher than that of at least one employee of department D11. List the employees in employee number sequence.

Result

EMPNO LASTNAME SALARY WORKDEPT ------ --------- -------- -------- 000010 HAAS 52750.00 A00 000020 THOMPSON 41250.00 B01 000030 KWAN 38250.00 C01 000050 GEYER 40175.00 E01 000070 PULASKI 36170.00 D21 000090 HENDERSON 29750.00 E11 000100 SPENSER 26150.00 E21 000110 LUCCHESI 46500.00 A00 000120 O'CONNELL 29250.00 A00 000130 QUINTANA 23800.00 C01 000140 NICHOLLS 28420.00 C01 000230 JEFFERSON 22180.00 D21 000240 MARINO 28760.00 D21 000250 SMITH 19180.00 D21 000270 PEREZ 27380.00 D21 000280 SCHNEIDER 26250.00 E11 000320 MEHTA 19950.00 E21 000330 LEE 25370.00 E21 000340 GOUNOT 23840.00 E21

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 5. Subqueries 5-5

Page 68: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 5

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

Result

EMPNO LASTNAME SALARY WORKDEPT ------ -------- -------- -------- 000010 HAAS 52750.00 A00 000020 THOMPSON 41250.00 B01 000030 KWAN 38250.00 C01 000050 GEYER 40175.00 E01 000070 PULASKI 36170.00 D21 000110 LUCCHESI 46500.00 A00

Problem 6

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

Result

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-6 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 69: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 7

Display employee number, last name, and activity number of all activities in the EMP_ACT table. Duplicate rows should be avoided. However, the list should only be produced if there were any activities in 1982. Note: The EMP_ACT table in the Sample database of Windows has a duplicate row for employee number ‘000020’. This may effect the result.

Result

EMPNO LASTNAME ACTNO ------ --------------- ------000010 HAAS 10000020 THOMPSON 30000030 KWAN 10000050 GEYER 10000070 PULASKI 10000090 HENDERSON 10000100 SPENSER 10000110 LUCCHESSI 20000130 QUINTANA 90000130 QUINTANA 100000140 NICHOLLS 90000140 NICHOLLS 100000140 NICHOLLS 110000150 ADAMSON 60000150 ADAMSON 180000160 PIANKA 60000170 YOSHIMURA 60000170 YOSHIMURA 70000170 YOSHIMURA 80000180 SCOUTTEN 70000190 WALKER 70000190 WALKER 80000200 BROWN 50000200 BROWN 60000210 JONES 80000210 JONES 180000220 LUTZ 40000230 JEFFERSON 60000230 JEFFERSON 70000230 JEFFERSON 80...... .................. ...

53 record(s) selected.

END OF LAB (with hints)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 5. Subqueries 5-7

Page 70: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Solution

Problem 1

SELECT EMPNO, LASTNAME, DEPTNAME FROM EMPLOYEE , DEPARTMENT WHERE WORKDEPT = DEPTNO AND EMPNO NOT IN (SELECT EMPNO FROM EMP_ACT)

Problem 2

SELECT EMPNO, SALARY, WORKDEPT FROM EMPLOYEE E WHERE SALARY > (SELECT AVG(SALARY) FROM EMPLOYEE WHERE WORKDEPT = E.WORKDEPT) ORDER BY WORKDEPT, EMPNO

Problem 3

SELECT WORKDEPT, COUNT(*) AS EMP_COUNT FROM EMPLOYEE WHERE WORKDEPT <> 'A00' GROUP BY WORKDEPT HAVING COUNT(*) = (SELECT COUNT(*) FROM EMPLOYEE WHERE WORKDEPT = 'A00')

Problem 4

SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM EMPLOYEE WHERE WORKDEPT <> 'D11' AND SALARY > ANY (SELECT SALARY FROM EMPLOYEE WHERE WORKDEPT = 'D11') ORDER BY EMPNO

An alternate solution is:

SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM EMPLOYEE WHERE WORKDEPT <> 'D11' AND SALARY > (SELECT MIN(SALARY) FROM EMPLOYEE WHERE WORKDEPT = 'D11') ORDER BY EMPNO

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-8 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 71: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 5

SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM EMPLOYEE WHERE WORKDEPT <> 'D11' AND SALARY > ALL (SELECT SALARY FROM EMPLOYEE WHERE WORKDEPT = 'D11') ORDER BY EMPNO

An alternate solution is:

SELECT EMPNO, LASTNAME, SALARY, WORKDEPT FROM EMPLOYEE WHERE WORKDEPT <> 'D11' AND SALARY > (SELECT MAX(SALARY) FROM EMPLOYEE WHERE WORKDEPT = 'D11') ORDER BY EMPNO

Problem 6

SELECT E.EMPNO, LASTNAME, COUNT(*) AS COUNT_ACT FROM EMPLOYEE E, EMP_ACT EA WHERE E.EMPNO = EA.EMPNO GROUP BY E.EMPNO, LASTNAME HAVING COUNT(*) >= ALL(SELECT COUNT(*) FROM EMP_ACT GROUP BY EMPNO)

Problem 7

SELECT DISTINCT E.EMPNO, LASTNAME, ACTNO FROM EMPLOYEE E JOIN EMP_ACT EA ON E.EMPNO = EA.EMPNO WHERE EXISTS (SELECT * FROM EMP_ACT WHERE 1982 BETWEEN YEAR(EMSTDATE) AND YEAR(EMENDATE))

END OF SOLUTION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 5. Subqueries 5-9

Page 72: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

5-10 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 73: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Exercise 6. Scalar Functions

What This Exercise Is About

This exercise gives you the opportunity to work with scalar functions.

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 the column names and descriptions for each table.

Required Materials

• Student handout • SQL Reference

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 6. Scalar Functions 6-1

Page 74: Student Exercises - comp.hkbu.edu.hk

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 the last name used to control the result. The LASTNAME column is defined as VARCHAR. There is a function which provides the length of the last name.

Problem 2

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

Problem 3

The salaries of the employees in department E11 will be increased by 3.75 percent. What will be the increase in dollars? Display the last name, actual yearly salary, and the salary increase rounded to the nearest dollar. Do not show any cents.

Problem 4

Repeat Problem 3 but this time express the amount of salary increase as an integer, that is, a number with no decimal places and no decimal point. (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, her job 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 for all employees for whom the hiring date is more than 30 years later than the date of birth. Display employee number and calculated difference. The difference should be shown in years, months, and days - each of which should be shown in a separate column. Make sure that the rows are in employee number sequence.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-2 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 75: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 7

Display project number, project name, project start date, and project end 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. Display employee number, last name, and first name. Also, show the activity number 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. List their last names and their hiring dates.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 6. Scalar Functions 6-3

Page 76: Student Exercises - comp.hkbu.edu.hk

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 the last name used to control the result. The LASTNAME column is defined as VARCHAR. There is a function which provides the length of the last name.

Result

EMPNO LASTNAME LASTCHAR ------ --------- -------- 000020 THOMPSON N 000030 KWAN N 000060 STERN N 000090 HENDERSON N 000150 ADAMSON N 000180 SCOUTTEN N 000200 BROWN N 000230 JEFFERSON N 000260 JOHNSON N

Problem 2

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

Result

PROJNO PROJNAME DEPTNO MAJPROJ ------ -------------------- ------ ---------------- AD3100 ADMIN SERVICES D01 NO MAJOR PROJECT <----note MA2100 WELD LINE AUTOMATION D01 NO MAJOR PROJECT MA2110 W L PROGRAMMING D11 MA2100 MA2111 W L PROGRAM DESIGN D11 MA2110 MA2112 W L ROBOT DESIGN D11 MA2110 MA2113 W L PROD CONT PROGS D11 MA2110

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-4 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 77: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 3

The salaries of the employees in department E11 will be increased by 3.75 percent. What will be the increase in dollars? Display the last name, actual yearly salary, and the salary increase rounded to the nearest 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 as an integer, that is, a number with no decimal places and no decimal point. (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 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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 6. Scalar Functions 6-5

Page 78: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 5

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

Result

WORKDEPT LISTING -------- --------------------------- A00 PRES: HAAS C01 MANAGER: KWAN D21 MANAGER: PULASKI E11 MANAGER: HENDERSON C01 ANALYST: QUINTANA C01 ANALYST: NICHOLLS D11 DESIGNER: PIANKA D11 DESIGNER: SCOUTTEN D11 DESIGNER: LUTZ D21 CLERK: JOHNSON D21 CLERK: PEREZ E11 OPERATOR: SCHNEIDER E11 OPERATOR: SETRIGHT

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-6 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 79: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 6

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

Result

EMPNO YEARS MONTHS DAYS ------ ----- ------ ---- 000010 31 4 8 000030 33 10 25 000130 45 10 13 000230 31 5 22 000260 38 11 6 000290 33 10 21 000300 35 7 23 000310 33 4 21 000320 32 10 27 000330 34 7 5

Problem 7

Display project number, project name, project start date, and project end 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 289 PL2100 WELD LINE PLANNING 1982-01-01 1982-09-15 257

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 6. Scalar Functions 6-7

Page 80: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 8

List the employees in department D11 who had activities. Display employee number, last name, and first name. Also, show the activity number 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 201 000160 PIANKA ELIZABETH 60 1982-07-15 201 000170 YOSHIMURA MASATOSHI 70 1982-06-01 245 000180 SCOUTTEN MARILYN 70 1982-04-01 75 000190 WALKER JAMES 80 1982-10-01 365 000200 BROWN DAVID 60 1982-06-15 231 000210 JONES WILLIAM 80 1982-10-01 123 000210 JONES WILLIAM 180 1982-10-01 123 000220 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. List their last names and their hiring dates.

Result

HIREDATE LASTNAME ---------- --------------- 1975-04-05 KWAN 1970-08-15 HENDERSON 1972-02-12 ADAMSON 1973-07-07 SCOUTTEN 1964-09-12 SETRIGHT

END OF LAB (with hints)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-8 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 81: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Solution

Problem 1

SELECT EMPNO,LASTNAME, SUBSTR(LASTNAME,LENGTH(LASTNAME),1) AS LASTCHAR FROM EMPLOYEE WHERE LASTNAME LIKE '%N'

An alternate solution is:

SELECT EMPNO,LASTNAME, SUBSTR(LASTNAME,LENGTH(LASTNAME),1) AS LASTCHAR FROM EMPLOYEE WHERE SUBSTR(LASTNAME,LENGTH(LASTNAME),1) = 'N'

If the column LASTNAME had been defined as CHAR(x) one way to code this 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 PROJECT WHERE 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 EMPLOYEE WHERE WORKDEPT = 'E11' or by using ROUND(): SELECT EMPNO, LASTNAME, WORKDEPT, SALARY, INTEGER(ROUND(SALARY * 0.0375 ,0)) AS AMOUNT FROM EMPLOYEE WHERE WORKDEPT = 'E11'

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 6. Scalar Functions 6-9

Page 82: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 4

SELECT EMPNO, LASTNAME, WORKDEPT, SALARY, INTEGER(SALARY * 0.0375 + 0.5) AS AMOUNT FROM EMPLOYEE WHERE WORKDEPT = 'E11'

Problem 5

SELECT WORKDEPT, CAST(RTRIM(JOB) AS VARCHAR(10)) !! ': '!! LASTNAME AS LISTING FROM EMPLOYEE WHERE SEX='F'

Problem 6

SELECT EMPNO, YEAR(HIREDATE - BIRTHDATE) AS YEARS, MONTH(HIREDATE - BIRTHDATE) AS MONTHS, DAY(HIREDATE - BIRTHDATE) AS DAYS FROM EMPLOYEE WHERE YEAR(HIREDATE - BIRTHDATE) > 30 ORDER BY EMPNO

Problem 7

SELECT PROJNO, PROJNAME, PRSTDATE, PRENDATE, DAYS(PRENDATE) - DAYS(PRSTDATE) AS DAYS_DURATION FROM PROJECT WHERE 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 EA ON E.EMPNO = EA.EMPNO WHERE EMSTDATE = (SELECT MAX(EMSTDATE) FROM EMP_ACT WHERE EMPNO = E.EMPNO) AND E.WORKDEPT = 'D11'

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-10 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 83: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 9

SELECT (DAYS('2000-01-01') - DAYS('1969-07-20')) / 7 AS WEEKS FROM EMPLOYEE WHERE EMPNO = '000010'

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

Problem 10

SELECT HIREDATE,LASTNAME FROM EMPLOYEE WHERE DAYOFWEEK(HIREDATE) IN (1,7)

END OF SOLUTION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 6. Scalar Functions 6-11

Page 84: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

6-12 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 85: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Exercise 7. Table Expressions and Recursive SQL

What This Exercise Is About

This exercise gives you the opportunity to work with table expressions 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 of recursion

Introduction

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

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

Required Materials

• Student handout • SQL Reference

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 7. Table Expressions and Recursive SQL 7-1

Page 86: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions

Problem 1

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

Problem 2

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

Problem 3

For each employee, display employee number, salary, and average salary and department number. The list should be sorted by department 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 specific model of a Honda Accord. You created the CARS table when you executed the CRTABS member at the beginning of the labs. Determine all the major parts necessary to construct the Passenger Compartment of the car. In other words, do not take the recursion to the maximum possible depth:, control the recursion so that it does not iterate more than once after the initialization.

You can determine the contents of the CARS table with the following SELECT statement.

SELECT * FROM CARS ORDER BY 1, 2, 3, 4

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-2 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 87: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

The CARS table should contain the following data:

LEVEL ASSEMBLY COMPONENT QUANTITY ------ ------------------------- ------------------------- -------- 1 HONDA ACCORD ENGINE COMPARTMENT 1 1 HONDA ACCORD PASSENGER COMPARTMENT 1 2 ENGINE COMPARTMENT ENGINE 1 2 ENGINE COMPARTMENT IGNITION SYSTEM 1 2 PASSENGER COMPARTMENT SEAT GROUP 3 2 PASSENGER COMPARTMENT DASHBOARD 1 2 PASSENGER COMPARTMENT TRUNK 1 3 ENGINE CAMSHAFT 1 3 ENGINE CRANKSHAFT 1 3 ENGINE PISTON 4 3 ENGINE CONNECTING ROD 4 3 SEAT GROUP FRONT SEAT ASSEMBLY 2 3 SEAT GROUP REAR SEAT ASSEMBLY 1 3 DASHBOARD VENT 4 3 DASHBOARD STEREO SYSTEM 1 3 DASHBOARD GAUGE CLUSTER 1 3 DASHBOARD CONTROL CLUSTER 1 3 TRUNK TOOL KIT 1 4 STEREO SYSTEM RADIO 1 4 STEREO SYSTEM CD PLAYER 1 4 GAUGE CLUSTER SPEEDOMETER 1 4 GAUGE CLUSTER ODOMETER 1 4 CONTROL CLUSTER FOG LAMP CONTROL 1 4 CONTROL CLUSTER FOUR WAY FLASHER CONTROL 1 4 CONTROL CLUSTER TURN SIGNAL CONTROL 1 4 FRONT SEAT ASSEMBLY FRONT SEAT 1 4 FRONT SEAT ASSEMBLY LAP/SHOULDER BELT 1 4 REAR SEAT ASSEMBLY REAR SEAT 1 4 REAR SEAT ASSEMBLY LAP/SHOULDER BELT 3 4 REAR SEAT ASSEMBLY SHOULDER BELT 3 30 record(s) selected.

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 7. Table Expressions and Recursive SQL 7-3

Page 88: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions With Hints

Problem 1

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

Result

HIREYEAR AVG_TOTAL_EARNINGS----------- ------------------ 1970 32730.000000 1971 26204.000000 1972 23686.000000 1973 34742.333333 1974 22486.000000 1975 30520.000000 1976 29597.000000 1977 24430.000000 1978 27154.000000 1979 25896.500000 1980 28860.500000

Problem 2

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

Result

HIGHEST_AVERAGE ----------------- 34742.333333

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

HIREYEAR AVG_TOTAL_EARNINGS----------- ------------------ 1973 34742.333333

Note: If a copy of the DSN8xxx.EMP is beeing usewd, the result may differ slightly.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-4 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 89: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 3

For each employee, display employee number, salary, and average salary and department number. The list should be sorted by department number and employee number.

Result

EMPNO SALARY AVG_SAL WORKDEPT ------ -------- -------------- -------- 000010 52750.00 42833.33333333 A00 000110 46500.00 42833.33333333 A00 000120 29250.00 42833.33333333 A00 000020 41250.00 41250.00000000 B01 000030 38250.00 30156.66666666 C01 000130 23800.00 30156.66666666 C01 000140 28420.00 30156.66666666 C01 000060 32250.00 24677.77777777 D11 000150 25280.00 24677.77777777 D11 000160 22250.00 24677.77777777 D11 000170 24680.00 24677.77777777 D11 000180 21340.00 24677.77777777 D11 000190 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 specific model of a Honda Accord. You created the CARS table when you executed the CRTABS member at the beginning of the labs. Determine all the major parts necessary to construct the Passenger Compartment of the car. In other words, do not take the recursion to the maximum possible depth:, control the recursion so that it does not iterate more than once after the initialization.

You can determine the contents of the CARS table with the following SELECT statement.

SELECT * FROM CARS ORDER BY 1, 2, 3, 4

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 7. Table Expressions and Recursive SQL 7-5

Page 90: Student Exercises - comp.hkbu.edu.hk

Student Exercises

The CARS table should contain the following data:

LEVEL ASSEMBLY COMPONENT QUANTITY ------ ------------------------- ------------------------- -------- 1 HONDA ACCORD ENGINE COMPARTMENT 1 1 HONDA ACCORD PASSENGER COMPARTMENT 1 2 ENGINE COMPARTMENT ENGINE 1 2 ENGINE COMPARTMENT IGNITION SYSTEM 1 2 PASSENGER COMPARTMENT SEAT GROUP 3 2 PASSENGER COMPARTMENT DASHBOARD 1 2 PASSENGER COMPARTMENT TRUNK 1 3 ENGINE CAMSHAFT 1 3 ENGINE CRANKSHAFT 1 3 ENGINE PISTON 4 3 ENGINE CONNECTING ROD 4 3 SEAT GROUP FRONT SEAT ASSEMBLY 2 3 SEAT GROUP REAR SEAT ASSEMBLY 1 3 DASHBOARD VENT 4 3 DASHBOARD STEREO SYSTEM 1 3 DASHBOARD GAUGE CLUSTER 1 3 DASHBOARD CONTROL CLUSTER 1 3 TRUNK TOOL KIT 1 4 STEREO SYSTEM RADIO 1 4 STEREO SYSTEM CD PLAYER 1 4 GAUGE CLUSTER SPEEDOMETER 1 4 GAUGE CLUSTER ODOMETER 1 4 CONTROL CLUSTER FOG LAMP CONTROL 1 4 CONTROL CLUSTER FOUR WAY FLASHER CONTROL 1 4 CONTROL CLUSTER TURN SIGNAL CONTROL 1 4 FRONT SEAT ASSEMBLY FRONT SEAT 1 4 FRONT SEAT ASSEMBLY LAP/SHOULDER BELT 1 4 REAR SEAT ASSEMBLY REAR SEAT 1 4 REAR SEAT ASSEMBLY LAP/SHOULDER BELT 3 4 REAR SEAT ASSEMBLY SHOULDER BELT 3 30 record(s) selected.

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-6 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 91: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Result

LEVEL ASSEMBLY COMPONENT QUANTITY ----- --------------------- ------------------ -------- 0 PASSENGER COMPARTMENT DASHBOARD 1 0 PASSENGER COMPARTMENT SEAT GROUP 3 0 PASSENGER COMPARTMENT TRUNK 1 1 DASHBOARD CONTROL CLUSTER 1 1 DASHBOARD GAUGE CLUSTER 1 1 DASHBOARD STEREO SYSTEM 1 1 DASHBOARD VENT 4 1 SEAT GROUP FRONT SEAT ASSEMBLY 2 1 SEAT GROUP REAR SEAT ASSEMBLY 1 1 TRUNK TOOL KIT 1

END OF LAB (with hints)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 7. Table Expressions and Recursive SQL 7-7

Page 92: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Solution

Problem 1

SELECT TEMP.HIREYEAR, AVG(TEMP.TOTAL_EARNINGS) AS AVG_TOTAL_EARNINGS FROM (SELECT YEAR(HIREDATE) AS HIREYEAR, SALARY + BONUS + COMM AS TOTAL_EARNINGS FROM EMPLOYEE WHERE 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_AVERAGE FROM (SELECT TEMP.HIREYEAR AS HIRED, AVG(TEMP.TOTAL_EARNINGS) AS AVG_TOTAL_EARNINGS FROM (SELECT YEAR(HIREDATE) AS HIREYEAR, SALARY + BONUS + COMM AS TOTAL_EARNINGS FROM EMPLOYEE WHERE 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 the average total earnings. To list their hiring year you can use the following query:

SELECT TEMP.HIREYEAR, AVG(TEMP.TOTAL_EARNINGS) AS AVG_TOTAL_EARNINGS FROM (SELECT YEAR(HIREDATE) AS HIREYEAR, SALARY + BONUS + COMM AS TOTAL_EARNINGS FROM EMPLOYEE WHERE HIREDATE BETWEEN '1970-01-01' AND '1980-12-31' )AS TEMP GROUP BY TEMP.HIREYEAR HAVING AVG(TEMP.TOTAL_EARNINGS) >= ALL (SELECT AVG(TEMP1.TOTAL_EARNINGS) FROM (SELECT YEAR(HIREDATE) AS HIREYEAR, SALARY + BONUS + COMM AS TOTAL_EARNINGS FROM EMPLOYEE WHERE HIREDATE BETWEEN '1970-01-01' AND '1980-12-31' ) AS TEMP1 GROUP BY TEMP1.HIREYEAR)

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-8 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 93: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 3

SELECT EMPNO, SALARY, AVG_TAB.AVG_SAL, E.WORKDEPT FROM EMPLOYEE E INNER JOIN (SELECT WORKDEPT ,AVG(SALARY) AS AVG_SAL FROM EMPLOYEE GROUP BY WORKDEPT) AS AVG_TAB ON E.WORKDEPT = AVG_TAB.WORKDEPT ORDER BY E.WORKDEPT, EMPNO

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

SELECT EMPNO, SALARY, AVG_TAB.AVG_SAL, E.WORKDEPT FROM EMPLOYEE E , (SELECT WORKDEPT ,AVG(SALARY) AS AVG_SAL FROM EMPLOYEE GROUP BY WORKDEPT) AS AVG_TAB WHERE E.WORKDEPT = AVG_TAB.WORKDEPT ORDER BY E.WORKDEPT, EMPNO

Problem 4

WITH CAR_PARTS (LEVEL, ASSEMBLY, COMPONENT, QUANTITY) AS (SELECT 0, ROOT.ASSEMBLY, ROOT.COMPONENT, ROOT.QUANTITY FROM CARS ROOT WHERE ROOT.LEVEL = 2 AND ASSEMBLY = 'PASSENGER COMPARTMENT' UNION ALL SELECT PARENT.LEVEL + 1, CHILD.ASSEMBLY, CHILD.COMPONENT, CHILD.QUANTITY FROM CAR_PARTS PARENT, CARS CHILD WHERE PARENT.COMPONENT = CHILD.ASSEMBLY AND PARENT.LEVEL < 1) SELECT LEVEL, ASSEMBLY, COMPONENT, QUANTITY FROM CAR_PARTS ORDER BY LEVEL, ASSEMBLY, COMPONENT

END OF SOLUTION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 7. Table Expressions and Recursive SQL 7-9

Page 94: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

7-10 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 95: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Exercise 8. Performance and UDT/UDF

What This Exercise Is About

This exercise will help you predict whether or not specific SQL statements 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 many factors

• Have some experience with UDT and sourced UDF

Introduction

Note: The first part is a paper exercise. You do not have to write or 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 and FIRSTNME, in that order.

• A non-unique index on column WORKDEPT.

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

Required Materials

• You can use the student handout

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 8. Performance and UDT/UDF 8-1

Page 96: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Exercise Instructions

Problem 1

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

SELECT FIRSTNME, LASTNAME FROM EMPLOYEE WHERE PHONENO = '1793'

____________________________________________________________

____________________________________________________________

Problem 2

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

SELECT EMPNO, FIRSTNME, LASTNAME, WORKDEPT FROM EMPLOYEE

____________________________________________________________

____________________________________________________________

Problem 3

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

SELECT EMPNO, FIRSTNME, LASTNAME, PHONENO, HIREDATE FROM EMPLOYEE WHERE LASTNAME LIKE 'J%'

____________________________________________________________

____________________________________________________________

Problem 4

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

SELECT FIRSTNME, LASTNAME FROM EMPLOYEE WHERE SUBSTR(LASTNAME,1,1) = 'J'

____________________________________________________________

____________________________________________________________

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

8-2 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 97: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 5

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

SELECT FIRSTNME FROM EMPLOYEE WHERE 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 EMPLOYEE WHERE WORKDEPT BETWEEN 'C01' AND 'D11'

____________________________________________________________

____________________________________________________________

Problem 8

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

Problem 9

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 8. Performance and UDT/UDF 8-3

Page 98: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 10

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

UPDATE the new columns in EMPLOYEE with following values:

EMPNO GER_SAL UK_SAL 000010 100000 40000 000020 80000 31000 000030 72000 29000

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

END OF LAB

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

8-4 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 99: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Solution

Problem 1

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

Problem 2

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

Problem 3

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

Problem 4

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

Problem 5

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

Problem 6

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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 8. Performance and UDT/UDF 8-5

Page 100: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Problem 7

DB2 might use the index on the WORKDEPT column if its analysis shows that there are relatively few departments in the range from 'C01' to 'D11'. Otherwise, it is unlikely to use an index. DB2 keeps statistics on the most frequently occurring values in a given index. These statistics are used in cases like this one to determine whether or not there is any significant benefit in using the index on the WORKDEPT column. The actual statistics kept vary somewhat from platform to platform and version 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

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

8-6 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 101: Student Exercises - comp.hkbu.edu.hk

Student ExercisesV1.2.2 BKM2MIF

Uempty

Problem 10

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

CREATE FUNCTION AVG(UK_POUND) RETURNS UK_POUND SOURCE AVG(DECIMAL(9,2)) CREATE FUNCTION MIN(UK_POUND) RETURNS UK_POUND SOURCE MIN(DECIMAL(9,2)) CREATE FUNCTION MAX(UK_POUND) RETURNS UK_POUND SOURCE MAX(DECIMAL(9,2)) CREATE FUNCTION AVG(GER_MARK) RETURNS GER_MARK SOURCE AVG(DECIMAL(9,2)) CREATE FUNCTION MIN(GER_MARK) RETURNS GER_MARK SOURCE AVG(DECIMAL(9,2)) CREATE FUNCTION MAX(GER_MARK) RETURNS GER_MARK SOURCE AVG(DECIMAL(9,2))

UPDATE the new columns in EMPLOYEE with following values:

EMPNO GER_SAL UK_SAL 000010 100000 40000 000020 80000 31000 000030 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 in German Marks and British Pounds for these three employees.

SELECT AVG(GER_SAL) AS MARKS,AVG(UK_SAL) AS POUNDS FROM EMPLOYEE WHERE EMPNO IN ('000010','000020','000030')

END OF SOLUTION

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

© Copyright IBM Corp. 1998, 2002 Exercise 8. Performance and UDT/UDF 8-7

Page 102: Student Exercises - comp.hkbu.edu.hk

Student Exercises

Course materials may not be reproduced in whole or in part without the prior written permission of IBM.

8-8 DB2 SQL for Experienced Users © Copyright IBM Corp. 1998, 2002

Page 103: Student Exercises - comp.hkbu.edu.hk

V1.2.2

backpg

Page 104: Student Exercises - comp.hkbu.edu.hk