StudentManual_cf124stud
Short Description
Download StudentManual_cf124stud...
Description
V3.1.0.1
cover
Front cover
DB2 SQL Workshop (Course Code CF12)
Student Notebook ERC 4.1
IBM Certified Course Material
Student Notebook
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: AIX OS/390 WebSphere
DB2 POWER z/OS
iSeries QMF 400
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Windows is a trademark 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. Linux® is a registered trademark of Linus Torvalds in the United States, other countries, or both. Other company, product, or service names may be trademarks or service marks of others.
February 2007 Edition The information contained in this document has not been submitted to any formal IBM test and is distributed on an “as is” basis without any warranty either express or implied. The use of this information or the implementation of any of these techniques is a customer responsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment. While each item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results will result elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk. © Copyright International Business Machines Corporation 1999, 2007. 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 restrictions set forth in GSA ADP Schedule Contract with IBM Corp.
V3.1.0.1 Student Notebook
TOC
Contents Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii Course Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix Agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi Unit 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1 Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2 1.1 Introduction to Relational Data Management Systems . . . . . . . . . . . . . . . . . . . 1-3 Computerless Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4 Relational Database Management System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5 Computerless Data Retrieval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6 Asking for Information - RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7 SQL Structured Query Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8 Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9 Table Name Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10 Sample Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11 Sample Alphanumeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12 Date Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13 Time Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14 CREATE TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15 NULL Characteristic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16 Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17 VIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18 Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19 Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20 Unit 2. Simple SQL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1 Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2 2.1 Simple SQL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3 EMPLOYEE Table - Part 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4 EMPLOYEE Table - Part 1 (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5 DEPARTMENT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7 PROJECT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8 Structure of an SQL Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9 Retrieving All Columns, All Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10 Retrieving All Columns, Limited Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11 Selecting Specific Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12 Select with Ordered Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13 Select with Ordered Output (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14 Alternate ORDER BY Specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15 Suppressing Duplicate Output Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16 Suppressing Duplicate Output Rows (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17 Retrieving Rows by Character Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18 © Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Contents
iii
Student Notebook
Retrieving Rows by Numerical Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-19 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-20 AND and OR - Principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-21 Multiple Conditions - AND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-22 Multiple Conditions - OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-23 Multiple Conditions - AND/OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-24 Multiple Conditions - Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-25 SELECT with IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-26 SELECT with BETWEEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-27 Retrieving Rows - Null Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-28 Partial String Search - LIKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-29 Partial String Search - Examples with '%' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-30 Partial String Search - Example with '_' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-31 Negation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-32 Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-33 Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-34 Unit 3. Retrieving Data from Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1 Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-2 3.1 Accessing Data Stored in Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3 Retrieving Data from Multiple Tables (Principle) . . . . . . . . . . . . . . . . . . . . . . . . . . .3-4 Retrieving Data from Multiple Tables (JOIN) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-5 Correlation Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-6 JOIN Syntax 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-7 JOIN Syntax 2 (JOIN Keyword) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-8 Another JOIN Example (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-9 Another JOIN Example (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-10 JOIN with Three Tables (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-11 JOIN with Three Tables (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-12 Joining a Table with Itself (1 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-13 Joining a Table with Itself (2 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-14 Joining a Table with Itself (3 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-15 Joining a Table with Itself – Other Example (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . .3-16 Joining a Table with Itself – Other Example (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . .3-17 Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-18 Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-19 Unit 4. Scalar Functions and Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1 Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-2 4.1 Scalar Functions and Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3 Selecting Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-4 Naming Result Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-5 Substitution of NULL Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-6 Arithmetic with NULL Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-7 Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-8 Decimal Representation of a Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-9 Decimal Values - Truncation and Rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-10 iv
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
TOC
Condition on Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Date and Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . CHAR Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Comparison with Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DATE / TIME Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Subtraction of Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Date / Time Scalar Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Date Scalar Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DATE Arithmetic (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . DATE Arithmetic (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Substring of Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Substring of Strings (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Concatenation of Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-11 4-12 4-13 4-14 4-15 4-16 4-17 4-18 4-19 4-20 4-21 4-22 4-23 4-24 4-25
Unit 5. Column Functions and Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1 Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2 5.1 Column Functions and Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3 SQL Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4 Column Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5 Sample Column Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7 Beware of Nulls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8 Column Functions Based on Subset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9 GROUP BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10 GROUP BY More than One Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11 The Hardest to Remember Rule in All of SQL! . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12 GROUP BY, ORDER BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13 GROUP BY, HAVING (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14 GROUP BY, HAVING (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15 Examples with HAVING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16 Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17 SELECT Statement - Six Clauses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18 Conceptual Execution of a SELECT (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-19 Conceptual Execution of a SELECT (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20 Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21 Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22 Unit 6. UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1 Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2 6.1 UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3 Multiple Queries - Multiple Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4 UNIONing Queries Together - Single Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5 Union Rule Number 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6 Union Rule Number 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7 Union Rule Number 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8 UNION ALL - Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Contents
v
Student Notebook
UNION ALL - Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-10 UNION ALL - Example 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-11 UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-12 UNION - Generation of Fitting Result Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-13 EXCEPT and INTERSECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-15 Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-16 Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-17 Unit 7. Using Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1 Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-2 7.1 Using Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3 Result Using Separate Selects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-4 Same Result Using a Subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-5 Subquery with Basic Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-6 Subquery Using IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-7 Variations on Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-8 Subquery Using IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-9 Subquery Using NOT IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-10 Subquery within HAVING Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-11 Restrictions/Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-12 Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-13 Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-14 Unit 8. Maintaining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1 Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-2 8.1 Maintaining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3 TESTEMP Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-4 Create Table TESTEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-5 Create View PERSINFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-7 Inserting Rows into the Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-9 Insert Multiple Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-11 Update Columns (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-12 Update Columns (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-13 Delete Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-14 Drop Table TESTEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-15 Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-16 Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-17 Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-18 Appendix A. Checkpoint Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1 Appendix B. Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-1
vi
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
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: AIX® OS/390® WebSphere®
DB2® POWER™ z/OS®
iSeries™ QMF™ 400®
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. Windows is a trademark 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. Linux® is a registered trademark of Linus Torvalds in the United States, other countries, or both. Other company, product, or service names may be trademarks or service marks of others.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Trademarks
vii
Student Notebook
viii
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Course Description DB2 SQL Workshop Duration: 2 days Purpose This course provides an introduction to the SQL language and applies to the entire DB2 Family. This course is appropriate for customers working in all DB2 environments, that is, z/OS, VM/VSE, iSeries, Linux, UNIX, and Windows.
Audience Everyone needing to write, support, or understand SQL queries. This includes but is not limited to end-users, programmers, application designers, database administrators, and system administrators who do not yet have knowledge of the SQL Data Manipulation Language (DML).
Prerequisites • Basic computer literacy • Basic editing skills • Database skills are not required
Objectives On completion of this course, you should be able to: • Code SQL statements to retrieve data from a DB2 table, including the SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER BY clauses • Code inner Joins, including joining a table to itself • Use SQL arithmetic operations • Use scalar and column functions • Use UNION and UNION ALL • INSERT, UPDATE and DELETE rows • Code simple CREATE TABLE and CREATE VIEW statements © Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Course Description
ix
Student Notebook
Contents • • • • • • • •
x
DB2 SQL Workshop
Introduction Simple SQL Queries Retrieving data from multiple tables Scalar functions and arithmetic Column functions and grouping UNION Using Subqueries Maintaining data
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Agenda Day 1 Welcome Introduction Simple SQL Queries Exercise 1 Exercise Review Retrieving Data from Multiple Tables Exercise 2 Exercise Review Scalar Functions and Arithmetic Exercise 3
Day 2 Exercise review Column Functions and Grouping Exercise 4 Exercise Review Union Exercise 5 Exercise Review Using Subqueries Exercise 6 Exercise Review Maintaining Data Exercise 7 Exercise Review
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Agenda
vii
Student Notebook
xii
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Unit 1. Introduction What This Unit Is About Database concepts, data types, tables, and views.
What You Should Be Able to Do After completing this unit, you should be able to: • Define the terms: - Database, table, row, column, view • State the more common DB2 UDB data types • List the most commonly used SQL statements in the: - Data Definition Language (DDL) - Data Manipulation Language (DML) - Data Control Language (DCL) • State three null characteristics, and their meaning
How You Will Check Your Progress • Checkpoint questions
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-1
Student Notebook
Unit Objectives After completing this unit, you should be able to: Define the terms – Database, table, row, column, view
State the more common DB2 data types List the most commonly used SQL statements in the – Data definition language (DDL) – Data manipulation language (DML) – Data control language (DCL)
State three null characteristics and their meaning
© Copyright IBM Corporation 2006
Figure 1-1. Unit Objectives
CF124.1
Notes:
1-2
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
1.1 Introduction to Relational Data Management Systems
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-3
Student Notebook
Computerless Data Storage
Departments
Projects
Employees
© Copyright IBM Corporation 2006
Figure 1-2. Computerless Data Storage
CF124.1
Notes: In a traditional office, • Employee data was filed in an 'EMPLOYEES' folder. • Department data was filed in a 'DEPARTMENTS' folder. • Project data was filed in a 'PROJECTS' folder. People manually managed the data, updated the data, search through it, and retrieved it on demand.
1-4
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Relational Database Management System DEPARTMENT
EMPLOYEE
.. .
EMPNO FIRSTNME
MID LASTNAME INIT
WORK DEPT
000010
CHRISTINE
I
HAAS
A00
A00
SPIFFY COMPUTER SERVICE DIV.
000020
MICHAEL
L
THOMPSON B01
B01
PLANNING
000030
SALLY
A
KWAN
C01
C01
INFORMATION CENTER
000050
JOHN
B
GEYER
E01
D01
DEVELOPMENT CENTER
000060
IRVING
F
STERN
D11
D11
MANUFACTURING SYSTEMS
000070
EVA
D
PULASKI
D21
D21
ADMINISTRATION SYSTEMS
DEPT DEPTNAME NO
...
PROJECT Database A collection of tables
PROJNO
PROJNAME
DEPT NO
AD3100
ADMIN SERVICES
D01
AD3110
GENERAL ADMIN SYSTEMS
D21
AD3111
PAYROLL PROGRAMMING
D21
AD3112
PERSONNEL PROGRAMMING D21
AD3113
ACCOUNT PROGRAMMING
D21
IF1000
QUERY SERVICES
C01
.. .
© Copyright IBM Corporation 2006
Figure 1-3. Relational Database Management System
CF124.1
Notes: A relational database is a collection of tables. A table is a set of columns and rows. All data is stored in tables. Every table has a name. In a well-designed database, each table contains data about a specific subject (entity); for instance, one table contains employee data, another table department data, and a third one data about projects. The data base management system manages the data. If someone requires information about an employee, he/she must talk to the data management system in a language which the system understands: SQL - Structured Query Language.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-5
Student Notebook
Computerless Data Retrieval
Please give me a list of all employees in department D11 sorted by name.
000010 HAAS I CHRISTINA A00 000340GOUNOT R JASON E21 000050GEYER B JOHN E01 000200 BROWN DAVID D11 000150 ADAMSON BRUCE D11
© Copyright IBM Corporation 2006
Figure 1-4. Computerless Data Retrieval
CF124.1
Notes: A query requires: 1. Someone who requests data (data requestor) 2. Someone who returns the data 3. A language understood by both sides 4. A medium for communication 5. A pool with the desired information
1-6
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Asking for Information - RDBMS RDBMS
Return a list of employees in department D11 sorted by last name
EMPLOYEE EMPNO LASTNAME
MID FIRSTNME INIT
WORKDEPT
PHONENO
000150 ADAMSON
BRUCE
D11
4510
000200 BROWN
DAVID
D11
4501
000050 GEYER
B
JOHN
E01
6789
000340 GOUNOT
R
JASON
E21
5698
000010 HAAS
T
CHRISTINE
A00
3978
SELECT * FROM EMPLOYEE WHERE WORKDEPT = 'D11' ORDER BY LASTNAME
SE L E
CT S
tatem
ent
© Copyright IBM Corporation 2006
Figure 1-5. Asking for Information - RDBMS
CF124.1
Notes Human communication RDBMS Data requestor End-user, programmer, designer Human language Structured Query Language (SQL) A medium for communication - phone, notes, The medium depends on the environment. etc. The medium could be a program, a query tool, etc. Pool (folders) with the desired information Tables Someone who fetches the information Integrated search and retrieval functions
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-7
Student Notebook
SQL Structured Query Language
© Copyright IBM Corporation 2006
Figure 1-6. SQL Structured Query Language
CF124.1
Notes: SQL has similarities with the human language. By means of SQL, we communicate with the RDBMS. We tell DB2 UDB what we want, not how DB2 UDB should access the data. SQL can be used either interactively or embedded in an application program, for example, COBOL, PL/1, C or Java. The object of a DML query is a set of tables. The result of the DML query is a set of qualifying rows from these tables. • DDL is mostly used by data base administrators to define DB2 UDB objects such as tables, views and indices • DML is used by all data base users to retrieve information or to maintain data • DCL is also used by data base administrators to allow or disallow activities in DB2 UDB by granting or revoking privileges Most Relational Database Managers understand SQL.
1-8
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Table USERA.EMPLOYEE EMPNO
row
FIRSTNME
MIDINIT LASTNAME
. . . BIRTHDATE
COMM
000010
CHRISTINE
I
HAAS
. . . 1933-08-24
9220
000020
MICHAEL
L
THOMSON
. . . 1948-02-02
0
000030
SALLY
A
KWAN
. . . 1941-05-11
-- - - -
000050
JOHN
B
GEYER
. . . 1925-09-15
3214
.....
.....
.....
.....
...
LEE
. . . 1941-07-18
000330
WING
column
text column
.....
.....
date column
2030
numeric column
© Copyright IBM Corporation 2006
Figure 1-7. Table
CF124.1
Notes: • Every table has a name. • Every column has a name. • Column names must be unique within a table. • A table consists of a set of rows and columns. • Rows are normally stored unordered. • For each row, a column has one entry (field). • All values of a column have the same data type.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-9
Student Notebook
Table Name Construction Qualified Table Name USERA.EMPLOYEE
Table owner / Schema
Simple Name
USERA
EMPLOYEE
© Copyright IBM Corporation 2006
Figure 1-8. Table Name Construction
CF124.1
Notes: • Every table must have a unique name. • Every table name consists of at least two parts referred to as simple table name and its qualifier (tables used in a distributed processing environment may have three part names). • The qualifier precedes the simple table name and is separated from it by a period. • The simple table name must be unique within a qualifier.
1-10 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Sample Numeric Data Types Data Type
Comment
SMALLINT
Whole numbers from -32768 to +32767
INTEGER
Whole numbers from -2,147,483,648 to +2,147,483,647
DECIMAL(m,n)
Decimal numbers with max. 31 digits m = total number of digits n = number of decimal digits
© Copyright IBM Corporation 2006
Figure 1-9. Sample Numeric Data Types
CF124.1
Notes: The visual shows a few of the DB2 UDB supported numeric data types. For complete list of supported data types in your environment, see the appropriate reference manual.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-11
Student Notebook
Sample Alphanumeric Data Types
Data Type
Comment
CHAR(n) or
STRING (fixed length)
CHARACTER(n) VARCHAR(n)
STRING (variable length)
© Copyright IBM Corporation 2006
Figure 1-10. Sample Alphanumeric Data Types
CF124.1
Notes: The visual shows a few of the alphanumeric data types available for the various platforms. For completeness, see the reference manual for your environment. Alphanumeric data may contain any character or printable special character. In queries, alphanumeric values must be enclosed in single quotes.
1-12 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Date Data Type Data Type
Comment
DATE YYYYMMDD
Display / Input Format USA mm/dd/yyyy EUR dd.mm.yyyy ISO yyyy-mm-dd JIS yyyy-mm-dd
DATE / TIME / TIMESTAMP data type - input verification allows arithmetic sorting component extraction © Copyright IBM Corporation 2006
Figure 1-11. Date Data Type
CF124.1
Notes: USA = US Standard EUR = European Standard ISO = International Standards Organization JIS = Japanese Industrial Standard Within an SQL statement, enclose dates in apostrophes. Examples: '2005-01-15' '01/15/2005' '15.01.2005' Within an SQL statement, all date formats (USA, JIS, EUR, ISO) are accepted.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-13
Student Notebook
Time Data Type
Data Type
Comment
TIME
Display / Input Formats
HHMMSS
USA
hh:mm AM or PM
EUR
hh.mm.ss
ISO
hh.mm.ss
JIS
hh:mm:ss
© Copyright IBM Corporation 2006
Figure 1-12. Time Data Type
CF124.1
Notes USA = US Standard EUR = European Standard ISO = International Standards Organization JIS = Japanese Industrial Standard Within an SQL statement, enclose times in apostrophes. Examples: '21.45.00' '9:45 PM' '21:45:00'
1-14 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Create Table CREATE TABLE EMPLOYEE ( EMPNO
CHAR(6)
NOT NULL,
FIRSTNME
VARCHAR(12)
NOT NULL,
MIDINIT
CHAR(1)
NOT NULL,
LASTNAME
VARCHAR(15)
NOT NULL,
WORKDEPT
CHAR(3)
,
.
.
.
.
.
.
BIRTHDATE
DATE
,
SALARY
DECIMAL(9,2)
,
BONUS
DECIMAL(9,2)
,
COMM
DECIMAL(9,2)
)
© Copyright IBM Corporation 2006
Figure 1-13. CREATE TABLE
CF124.1
Notes: If a table name qualifier is not explicitly supplied in the CREATE TABLE statement, the DB2 UDB environment determines the qualifier to be assigned (e.g. userid.tablename). For each column, at a minimum, the following must be defined: Column name Data type (and length) NULL characteristic
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-15
Student Notebook
NULL Characteristic
"nullable"
Column can be marked as having an 'unknown value'
NOT NULL
Column must always have a value
NOT NULL WITH Column must always have a value DEFAULT if we do not supply one, a system [(value)] or user defined default value will be supplied
© Copyright IBM Corporation 2006
Figure 1-14. NULL Characteristic
CF124.1
Notes: When a table is created, if a null characteristic is not provided the column is marked as "nullable". A column that is specified as NOT NULL must always contain a value for every row in the table. NOT NULL WITH DEFAULT columns are automatically supplied a value when the inserting user or application does not supply its value.
1-16 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Authorization GRANT SELECT ON PROJECT TO SALLY
DEPARTMENT
PROJECT
EMPLOYEE
REVOKE SELECT ON PROJECT FROM SALLY © Copyright IBM Corporation 2006
Figure 1-15. Authorization
CF124.1
Notes: A table owner or DB2 UDB administrator can grant privileges to other users. Example 1: Table owner USERX issues the following SQL GRANT and REVOKE statement: GRANT SELECT ON PROJECT TO SALLY This statement gives SALLY permission to retrieve data (SELECT) from the table named USERX.PROJECT. REVOKE SELECT ON PROJECT FROM SALLY This statement revokes SALLY's permission to retrieve data (SELECT) from the table named USERX.PROJECT. Example 2: USERX issues the following SQL GRANT: GRANT SELECT, INSERT, UPDATE ON EMPLOYEE TO SECR1 This statement authorizes user SECR1 to retrieve data from (SELECT), add rows to (INSERT), or change values of (UPDATE) table USERX.EMPLOYEE.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-17
Student Notebook
VIEW You only see what you should EMPNO
FIRSTNME
MIDINIT
LASTNAME
000150
BRUCE
ADAMSON
D11
4510
000200
DAVID
BROWN
D11
4501
000050
JOHN
B
GEYER
E01
6789
000340
JASON
R
GOUNOT
E21
5698
000010
CHRISTINE
T
A00
3978
HAAS
z Data security
WORKDEPT
PHONENO
z Simplification
© Copyright IBM Corporation 2006
Figure 1-16. VIEW
CF124.1
Notes: Views provide alternative ways of looking at the data of one or more tables. A view can be thought of as containing the data of selected columns and rows of the base table. For retrieval, all views can be used as base tables. Purpose: • Improved data security. • Improved data independence. • Simplification for the end user (less data, more user-friendly column names) Properties: • • • • •
No additional data is stored. A view encompasses a subset of columns and rows. A view may encompass data from several tables and/or other views. A view may encompass derived data, for example, averages. Data manipulation via some views is limited.
1-18 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Checkpoint 1. True or False? A database is a collection of tables. 2. What are some of the advantages of using date data types? 3. Name the alphanumeric and numeric data types covered in this unit. 4. Name the types of SQL statements in the Data Manipulation Language (DML).
© Copyright IBM Corporation 2006
Figure 1-17. Checkpoint
CF124.1
Notes: Please write down your answers below: 1. 2. 3. 4.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 1. Introduction
1-19
Student Notebook
Unit Summary Having completed this unit, you should be able to: Define the terms – Database, table, row, column, view
State the more common DB2 data types List the most commonly used SQL statements in the – Data definition language (DDL) – Data manipulation language (DML) – Data control language (DCL)
State three null characteristics and their meaning
© Copyright IBM Corporation 2006
Figure 1-18. Unit Summary
CF124.1
Notes:
1-20 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Unit 2. Simple SQL Queries What This Unit Is About The SELECT statement is used to retrieve data from a table. In this unit, we will discuss some of the SELECT statement's clauses and their syntax. In subsequent units, we will be looking at more complex SELECT statements.
What You Should Be Able to Do After completing this unit, you should be able to • Describe four SELECT statement clauses (SELECT, FROM, WHERE, ORDER BY) and their purpose. • Retrieve all rows of a table • Retrieve specific columns • Retrieve rows based on comparisons to numeric or alphanumeric column values • Use the keywords BETWEEN, IN, LIKE, DISTINCT • Order the resulting rows in a desired sequence
How You Will Check Your Progress • Checkpoint questions • Machine labs
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-1
Student Notebook
Unit Objectives After completing this unit, you should be able to: Describe four clauses of an SQL SELECT statement Use a SELECT statement to: – Retrieve all rows of a table – Retrieve specific columns – Retrieve rows based on comparisons to numeric or alphanumeric data – Retrieve rows based on specific columns containing NULL values
Use the keywords BETWEEN, IN, LIKE, DISTINCT Order the resulting rows in a desired sequence
© Copyright IBM Corporation 2007
Figure 2-1. Unit Objectives
CF124.1
Notes:
2-2
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
2.1 Simple SQL Queries
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-3
Student Notebook
EMPLOYEE Table - Part 1 (1 of 2) MID
WORK
PHONE NO
EMPNO
FIRSTNME
INIT
LASTNAME
DEPT
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
LUCCHESSI
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
© Copyright IBM Corporation 2007
Figure 2-2. EMPLOYEE Table - Part 1
CF124.1
Notes: EMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO HIREDATE
2-4
Employee number First name Middle initial Last name Department number Phone number Hire date
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
EMPLOYEE Table - Part 1 (2 of 2) ED EMPNO
JOB
LEVEL
SEX
BIRTHDATE
SALARY
BONUS
COMM
------
--------
-----
---
000010
PRES
18
F
----------
---------
---------
---------
1933-08-24
52750.00
1000.00
4220.00
000020
MANAGER
18
M
1948-02-02
41250.00
800.00
3300.00
000030
MANAGER
20
F
1941-05-11
38250.00
800.00
3060.00
000050 000060
MANAGER
16
M
1925-09-15
40175.00
800.00
3214.00
MANAGER
16
M
1945-07-07
32250.00
500.00
2580.00
000070
MANAGER
16
F
1953-05-26
36170.00
700.00
2893.00
000090
MANAGER
16
F
1941-05-15
29750.00
600.00
2380.00
000100
MANAGER
14
M
1956-12-18
26150.00
500.00
2092.00
000110
SALESREP
19
M
1929-11-05
46500.00
900.00
3720.00
000120
CLERK
14
M
1942-10-18
29250.00
600.00
2340.00
000130
ANALYST
16
F
1925-09-15
23800.00
500.00
1904.00
000140
ANALYST
18
F
1946-01-19
28420.00
600.00
2274.00
000150
DESIGNER
16
M
1947-05-17
25280.00
500.00
2022.00
000160
DESIGNER
17
F
1955-04-12
22250.00
400.00
1780.00
000170
DESIGNER
16
M
1951-01-05
24680.00
500.00
1974.00
© Copyright IBM Corporation 2007
Figure 2-3. EMPLOYEE Table - Part 1 (Cont)
CF124.1
Notes: EMPNO JOB EDLEVEL SEX BIRTHDATE SALARY BONUS COMM
Employee number (repeated for readability purpose) Job Education level (Ed-level) Sex Date of birth Salary (yearly) Bonus (yearly) Commission (yearly)
EMPNO is repeated on this page to facilitate row location. It is found only once within the Employee table.
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-5
2-6
DB2 SQL Workshop
EMPNO 000010 000020 000030 000050 000060 000070 000090 000100 000110 000120 000130 000140 000150 000160 000170 000180 000190 000200 000210 000220 000230 000240 000250 000260 000270 000280 000290 000300 000310 000320 000330 000340
FIRSTNME CHRISTINE MICHAEL SALLY JOHN IRVING EVA EILEEN THEODORE VINCENZO SEAN DOLORES HEATHER BRUCE ELIZABETH MASATOSHI MARILYN JAMES DAVID WILLIAM JENNIFER JAMES SALVATORE DANIEL SYBIL MARIA ETHEL JOHN PHILIP MAUDE RAMLAL WING JASON
Course materials may not be reproduced in whole or in part without the prior written permission of IBM. R
T K J M S P L R R X F V
R J S H
M A
M I D I N I T I L A B F D W Q G LASTNAME HAAS THOMPSON KWAN GEYER STERN PULASKI HENDERSON SPENSER LUCCHESSI O'CONNELL QUINTANA NICHOLLS ADAMSON PIANKA YOSHIMURA SCOUTTEN WALKER BROWN JONES LUTZ JEFFERSON MARINO SMITH JOHNSON PEREZ SCHNEIDER PARKER SMITH SETRIGHT MEHTA LEE GOUNOT
Employee Table Data
WORKDEPT A00 B01 C01 E01 D11 D21 E11 E21 A00 A00 C01 C01 D11 D11 D11 D11 D11 D11 D11 D11 D21 D21 D21 D21 D21 E11 E11 E11 E11 E21 E21 E21
PHONENO 3978 3476 4738 6789 6423 7831 5498 0972 3490 2167 4578 1793 4510 3782 2890 1682 2986 4501 0942 0672 4265 3780 0961 8953 9001 8997 4502 2095 3332 9990 2103 5698
HIREDATE 1965-01-01 1973-10-10 1975-04-05 1949-08-17 1973-09-14 1980-09-30 1970-08-15 1980-06-19 1958-05-16 1963-12-05 1971-07-28 1976-12-15 1972-02-12 1977-10-11 1978-09-15 1973-07-07 1974-07-26 1966-03-03 1979-04-11 1968-08-29 1966-11-21 1979-12-05 1969-10-30 1975-09-11 1980-09-30 1967-03-24 1980-05-30 1972-06-19 1964-09-12 1965-07-07 1976-02-23 1947-05-05
JOB EDLEVEL PRES 18 MANAGER 18 MANAGER 20 MANAGER 16 MANAGER 16 MANAGER 16 MANAGER 16 MANAGER 14 SALESREP 19 CLERK 14 ANALYST 16 ANALYST 18 DESIGNER 16 DESIGNER 17 DESIGNER 16 DESIGNER 17 DESIGNER 16 DESIGNER 16 DESIGNER 17 DESIGNER 18 CLERK 14 CLERK 17 CLERK 15 CLERK 16 CLERK 15 OPERATOR 17 OPERATOR 12 OPERATOR 14 OPERATOR 12 FIELDREP 16 FIELDREP 14 FIELDREP 16
S E X F M F M M F F M M M F F M F M F M M M F M M M F F F M M F M M M BIRTHDATE 1933-08-14 1948-02-02 1941-05-11 1925-09-15 1945-07-07 1953-05-26 1941-05-15 1956-12-18 1929-11-05 1942-10-18 1925-09-15 1946-01-19 1947-05-17 1955-04-12 1951-01-05 1949-02-21 1952-06-25 1941-05-29 1953-02-23 1948-03-19 1935-05-30 1954-03-31 1939-11-12 1936-10-05 1953-05-26 1936-03-28 1946-07-09 1936-10-27 1931-04-21 1932-08-11 1941-07-18 1926-05-17
SALARY BONUS 52750.00 1000.00 41250.00 800.00 38250.00 800.00 40175.00 800.00 32250.00 500.00 36170.00 700.00 29750.00 600.00 26150.00 500.00 46500.00 900.00 29250.00 600.00 23800.00 500.00 28420.00 600.00 25280.00 500.00 22250.00 400.00 24680.00 500.00 21340.00 500.00 20450.00 400.00 27740.00 600.00 18270.00 400.00 29840.00 600.00 22180.00 400.00 28760.00 600.00 19180.00 400.00 17250.00 300.00 27380.00 500.00 26250.00 500.00 15340.00 300.00 17750.00 400.00 15900.00 300.00 19950.00 400.00 25370.00 500.00 23840.00 500.00
COMM 4220.00 3300.00 3060.00 3214.00 2580.00 2893.00 2380.00 2092.00 3720.00 2340.00 1904.00 2274.00 2022.00 1780.00 1974.00 1707.00 1636.00 2217.00 1462.00 2387.00 1774.00 2301.00 1534.00 1380.00 2190.00 2100.00 1227.00 1420.00 1272.00 1596.00 2030.00 1907.00
Student Notebook
© Copyright IBM Corp. 1999, 2007
V3.1.0.1 Student Notebook
Uempty
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
-
© Copyright IBM Corporation 2007
Figure 2-4. DEPARTMENT Table
CF124.1
Notes: DEPTNO DEPTNAME MGRNO ADMRDEPT LOCATION
Department number Department name Employee serial number of the responsible manager Department number of the department to which this department reports Location
The dashes in the MGRNO and LOCATION columns indicate unknown values. The dashes are not physically stored in the table, they are displayed by the report writer to represent unknown values.
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-7
Student Notebook
PROJECT Table DEPT
RESP
NO
EMP
STAFF
----
------
-----
D01
000010
6.50
GENERAL ADMIN SYSTEMS
D21
000070
6.00
AD3111
PAYROLL PROGRAMMING
D21
000230
AD3112
PERSONNEL PROGRAMMING
D21
000250
AD3113
ACCOUNT PROGRAMMING
D21
IF1000
QUERY SERVICES
IF2000
PROJNO
PROJNAME
------
---------------------
AD3100
ADMIN SERVICES
AD3110
PR
MAJ PRSTDATE
PRENDATE
PROJ
----------
----------
------
1982-01-01
1983-02-01
-
1982-01-01
1983-02-01
AD3100
2.00
1982-01-01
1983-02-01
AD3110
1.00
1982-01-01
1983-02-01
AD3110
000270
2.00
1982-01-01
1983-02-01
AD3110
C01
000030
2.00
1982-01-01
1983-02-01
-
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
© Copyright IBM Corporation 2007
Figure 2-5. PROJECT Table
CF124.1
Notes: PROJNO PROJNAME DEPTNO RESPEMP PRSTAFF PRSTDATE PRENDATE MAJPROJ
2-8
Project number Project name Responsible department Employee number of the responsible employee Estimated mean staffing Estimated starting date Estimated ending date Major project for a subproject
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Structure of an SQL Query
SELECT
- Defines result columns Column names Arithmetic expressions Literals (text or numeric) Scalar functions Column functions Concatenation
FROM
- Table or view names
WHERE
- Conditions (qualifies rows)
ORDER BY
- Sorts result rows © Copyright IBM Corporation 2007
Figure 2-6. Structure of an SQL Query
CF124.1
Notes: Clauses must be coded in the sequence indicated in the visual. Each SELECT statement must have a SELECT and a FROM clause. The other clauses are optional. The individual clauses will be discussed in detail later on in this course.
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-9
Student Notebook
Retrieving All Columns, All Rows I need a listing of all department data
SELECT * FROM DEPARTMENT
DEPTNO DEPTNAME
MGRNO ADMRDEPT LOCATION
A00 B01 C01 D01 D11 D21 E01 E11 E21
000010 000020 000030 000060 000070 000050 000090 000100
SPIFFY COMPUTER SERVICE DIV. PLANNING INFORMATION CENTER DEVELOPMENT CENTER MANUFACTURING SYSTEMS ADMINISTRATION SYSTEMS SUPPORT SERVICES OPERATIONS SOFTWARE SUPPORT
A00 A00 A00 A00 D01 D01 A00 E01 E01
-
© Copyright IBM Corporation 2007
Figure 2-7. Retrieving All Columns, All Rows
CF124.1
Notes: The above statement displays all columns and all rows of the DEPARTMENT table. The output of every SELECT statement is called the result table. This is a simple statement useful for displaying all of the data in small tables. In practice, we rarely need to see all of the data in a production table. In a query, retrieve only the needed columns and rows.
2-10 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Retrieving All Columns, Limited Rows What does the data look like in the Department table?
SELECT * FROM DEPARTMENT FETCH FIRST 5 ROWS ONLY
DEPTNO A00 B01 C01 D01 D11
DEPTNAME SPIFFY COMPUTER SERVICE DIV. PLANNING INFORMATION CENTER DEVELOPMENT CENTER MANUFACTURING SYSTEMS
MGRNO 000010 000020 000030 000060
ADMRDEPT A00 A00 A00 A00 D01
LOCATION -
© Copyright IBM Corporation 2007
Figure 2-8. Retrieving All Columns, Limited Rows
CF124.1
Notes: The above statement displays all columns of the DEPARTMENT table but limits the result table to the first x rows specified in the FETCH FIRST clause. The FETCH FIRST clause, when used with an ORDER BY clause is useful in producing 'top 10' type reports. More on ORDER BY coming up.
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-11
Student Notebook
Selecting Specific Columns For each department, I need its number, its name and the department to which it reports.
SELECT DEPTNO, DEPTNAME, ADMRDEPT FROM DEPARTMENT
DEPTNO A00 B01 C01 D01 D11 D21 E01 E11 E21
DEPTNAME SPIFFY COMPUTER SERVICE DIV. PLANNING INFORMATION CENTER DEVELOPMENT CENTER MANUFACTURING SYSTEMS ADMINISTRATION SYSTEMS SUPPORT SERVICES OPERATIONS SOFTWARE SUPPORT
ADMRDEPT A00 A00 A00 A00 D01 D01 A00 E01 E01
© Copyright IBM Corporation 2007
Figure 2-9. Selecting Specific Columns
CF124.1
Notes: Items in the select list must be separated by commas. Spaces before and after commas are optional.
2-12 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Select with Ordered Output (1 of 2) By the way, the listing should be sorted by the department reported to SELECT DEPTNO, DEPTNAME, ADMRDEPT FROM DEPARTMENT ORDER BY ADMRDEPT ASC
DEPTNO A00 C01 B01 E01 D01 D11 D21 E21 E11
DEPTNAME ADMRDEPT SPIFFY COMPUTER SERVICE DIV.A00 A00 INFORMATION CENTER A00 PLANNING A00 SUPPORT SERVICES A00 DEVELOPMENT CENTER D01 MANUFACTURING SYSTEMS D01 ADMINISTRATION SYSTEMS E01 SOFTWARE SUPPORT E01 OPERATIONS © Copyright IBM Corporation 2007
Figure 2-10. Select with Ordered Output
CF124.1
Notes: • Resulting rows are sequenced according to columns listed in the ORDER BY clause. • The keyword ASC means sort in ascending sequence. This is the default sort sequence and the keyword ASC may be omitted. • DESC means sort in descending sequence. • Depending on the environment, columns used in the ORDER BY clause must be a part of the result table.
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-13
Student Notebook
Select with Ordered Output (2 of 2) I need the previous listing ordered first according to the number to which the department reports and within that sequence sorted by descending department numbers.
SELECT DEPTNO, DEPTNAME, ADMRDEPT FROM DEPARTMENT ORDER BY ADMRDEPT ASC, DEPTNO DESC
DEPTNO E01 D01 C01 B01 A00 D21 D11 E21 E11
DEPTNAME SUPPORT SERVICES DEVELOPMENT CENTER INFORMATION CENTER PLANNING SPIFFY COMPUTER SERVICE DIV. ADMINISTRATION SYSTEMS MANUFACTURING SYSTEMS SOFTWARE SUPPORT OPERATIONS
ADMRDEPT A00 A00 A00 A00 A00 D01 D01 E01 E01
© Copyright IBM Corporation 2007
Figure 2-11. Select with Ordered Output (Cont)
CF124.1
Notes: • If multiple columns are specified in the ORDER BY clause, their left to right sequence within the ORDER BY determines their sorting priority. The first ORDER BY column defines the primary order of the rows. Subsequent columns of the ORDER BY clause refine the order of rows. The rows with the same first-column values are further ordered by the values of the second column specified. The rows with identical first- and second-column values are further ordered by the values of the third column, and so on. • ASC or DESC may be specified for each column. • Date AND time columns may also be sorted in ascending or descending order. Assume you execute following statement: SELECT EMPNO, BIRTHDATE FROM EMPLOYEE ORDER BY BIRTHDATE DESC Then, the youngest employee (the one with the latest birth date) will be listed first. • A selected column can be identified by the column name or by an integer, referencing the columns position within the selection list.
2-14 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Alternate ORDER BY Specifications SELECT LASTNAME, FIRSTNME, WORKDEPT, JOB, SEX FROM
EMPLOYEE
ORDER BY WORKDEPT DESC, JOB, LASTNAME, SEX DESC
Equivalent ORDER BY clauses: ORDER BY WORKDEPT DESC, JOB ASC, LASTNAME ASC, SEX DESC ORDER BY 3 DESC, 4, 1, 5 DESC ORDER BY 3 DESC, 4 ASC, 1 ASC, 5 DESC ORDER BY 3 DESC, JOB, LASTNAME, 5 DESC ORDER BY WORKDEPT DESC, 4 ASC, 1 ASC, SEX DESC © Copyright IBM Corporation 2007
Figure 2-12. Alternate ORDER BY Specifications
CF124.1
Notes. Only one ORDER BY clause is allowed per query. In queries with a SELECT, FROM, WHERE and ORDER BY clause the ORDER BY must be coded as the last clause in the SELECT statement.
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-15
Student Notebook
Suppressing Duplicate Output Rows (1 of 2) Now, I want to know the different jobs performed by the employees. SELECT JOB FROM EMPLOYEE ORDER BY JOB
SELECT DISTINCT JOB FROM EMPLOYEE JOB ANALYST CLERK DESIGNER FIELDREP MANAGER OPERATOR PRES SALESREP
JOB ANALYST ANALYST CLERK CLERK CLERK CLERK
. . © Copyright IBM Corporation 2007
Figure 2-13. Suppressing Duplicate Output Rows
CF124.1
Notes: • DISTINCT ensures that the result contains unique rows. DISTINCT removes duplicate rows. • The keyword DISTINCT must immediately follow the word SELECT. It is effective at the row level.
2-16 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Suppressing Duplicate Output Rows (2 of 2) Also, I need a listing of the job distribution by department
SELECT WORKDEPT, JOB FROM EMPLOYEE ORDER BY WORKDEPT, JOB
SELECT DISTINCT WORKDEPT, JOB FROM EMPLOYEE ORDER BY WORKDEPT, JOB
WORKDEPT A00 A00 A00 B01 C01 C01 C01 D11 D11 D11 D11 D11 D11
WORKDEPT A00 A00 A00 B01 C01 C01 D11 D11 D21 D21 E01 E11 E11 E21 E21
. .
JOB CLERK PRES SALESREP MANAGER ANALYST ANALYST MANAGER DESIGNER DESIGNER DESIGNER DESIGNER DESIGNER DESIGNER
. .
JOB CLERK PRES SALESREP MANAGER ANALYST MANAGER DESIGNER MANAGER CLERK MANAGER MANAGER MANAGER OPERATOR FIELDREP MANAGER
© Copyright IBM Corporation 2007
Figure 2-14. Suppressing Duplicate Output Rows (Cont)
CF124.1
Notes: • DISTINCT eliminates all rows that contain duplicate data in the set of columns specified in the SELECT clause. • DISTINCT refers to the result row. • DISTINCT must not be used more than once within the scope of the SELECT statement.
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-17
Student Notebook
Retrieving Rows by Character Comparison I need a list of the departments reporting to department A00
SELECT FROM WHERE
DEPTNO A00 B01 C01 D01 E01
DEPTNO, ADMRDEPT DEPARTMENT ADMRDEPT = 'A00'
ADMRDEPT A00 A00 A00 A00 A00
© Copyright IBM Corporation 2007
Figure 2-15. Retrieving Rows by Character Comparison
CF124.1
Notes: To qualify specific table rows for further processing use the WHERE clause to specify the conditions rows must meet to be part of the result table. A WHERE clause can have one or more predicates, tests, or conditions. A predicate in the WHERE clause specifies a condition that is true, false, or unknown for a given row or group of rows. The values specified in a predicate must be compatible with the data type of the column or expression to which it is compared. For example, if you compare a column which is defined as alphanumeric, the value to which it is to be compared must be enclosed in single quotes. The comparison of alphanumeric columns is case sensitive. The SELECT list need not include the columns used in the WHERE clause.
2-18 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Retrieving Rows by Numerical Comparison I want the last name and education level of all employees with an education level greater than or equal to 19
SELECT FROM WHERE
LASTNAME KWAN LUCCHESSI
LASTNAME, EDLEVEL EMPLOYEE EDLEVEL >= 19
EDLEVEL 20 19
© Copyright IBM Corporation 2007
Figure 2-16. Retrieving Rows by Numerical Comparison
CF124.1
Notes: For numeric columns, for example, INTEGER, SMALLINT or DECIMAL, the values to be compared must not be enclosed in single quotes.
© Copyright IBM Corp. 1999, 2007
Unit 2. Simple SQL Queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-19
Student Notebook
Comparison Operators
SELECT
*
FROM
EMPLOYEE
WHERE
SALARY = 20000 -- equal to OR
SALARY 20000 -- not equal to
OR
SALARY >
OR
SALARY >= 20000 -- greater than or equal to
OR
SALARY <
OR
SALARY 50000 ORDER BY WORKDEPT
SUM 128500.00 41250.00 90470.00
WORKDEPT A00 C01
SUM 128500.00 90470.00
© Copyright IBM Corporation 2007
Figure 5-11. GROUP BY, HAVING (1 of 2)
CF124.1
Notes: So far we built groups. With HAVING, we now can select groups satisfying certain conditions. Conditions for groups must be specified in the having clause. HAVING may specify any column function on any column in a table being queried. This column need not be in the SELECT list. HAVING is used to qualify or disqualify a group from further processing.
5-14 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
GROUP BY, HAVING (2 of 2) By department, I need a listing of jobs, excluding managers, designer, and field representative, with an average salary higher than $25,000.
SELECT FROM WHERE GROUP BY HAVING ORDER BY
WORKDEPT, JOB, AVG(SALARY) AS AVG EMPLOYEE JOB NOT IN ('MANAGER', 'DESIGNER', 'FIELDREP') WORKDEPT, JOB AVG(SALARY) > 25000 WORKDEPT, JOB
WORKDEPT JOB A00 A00 A00 C01
CLERK PRES SALESREP ANALYST
AVG 29250.00000000 52750.00000000 46500.00000000 26110.00000000
© Copyright IBM Corporation 2007
Figure 5-12. GROUP BY, HAVING (2 of 2)
CF124.1
Notes: In the above example, we see another example of a GROUP BY clause with two columns, and another example of HAVING. The first three rows in the result have the same value ('A00') in the WORKDEPT column, but different values in the JOB column. The results of a GROUP BY clause is one result row for each unique set of values across the columns being grouped.
© Copyright IBM Corp. 1999, 2007
Unit 5. Column Functions and Grouping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-15
Student Notebook
Examples with HAVING Display the departments with more than one employee
SELECT FROM GROUP BY ORDER BY
WORKDEPT, COUNT(* ) AS NUMB EMPLOYEE WORKDEPT NUMB, WORKDEPT
WORKDEPT B01 E01 A00 C01 E21 E11 D21 D11
NUMB 1 1 3 3 4 5 6 9
SELECT FROM GROUP BY HAVING ORDER BY
WORKDEPT, COUNT(* ) AS NUMB EMPLOYEE WORKDEPT COUNT(*) > 1 NUMB, WORKDEPT
WORKDEPT A00 C01 E21 E11 D21 D11
NUMB 3 3 4 5 6 9
© Copyright IBM Corporation 2007
Figure 5-13. Examples with HAVING
CF124.1
Notes: The left SELECT is displayed to show the result without a HAVING clause. The right SELECT determines the result table consisting of groups for which the search condition of the HAVING clause is true. The condition COUNT(*) > 1 applies to the result table of the left SELECT
5-16 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Restrictions Column functions may be specified only in – SELECT – HAVING
SELECT may specify only – Column functions – Columns specified in 'GROUP BY'
HAVING may specify – Any column function on any column in a table being queried. This column need not be in the SELECT.
Column functions may not be nested
© Copyright IBM Corporation 2007
Figure 5-14. Restrictions
CF124.1
Notes:
© Copyright IBM Corp. 1999, 2007
Unit 5. Column Functions and Grouping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-17
Student Notebook
SELECT Statement - Six Clauses SELECT DEP, JOB, AVG(SAL) FROM EMPL WHERE JOB 'M' GROUP BY DEP, JOB HAVING AVG(SAL) > 28000 ORDER BY 3 DESC © Copyright IBM Corporation 2007
Figure 5-15. SELECT Statement - Six Clauses
CF124.1
Notes: The SELECT clause tells DB2 UDB which column(s) of information we want on our report. The SELECT list contains a column function (also known as a summary function) AVG. Column functions tell DB2 UDB to produce a single summary row for a set of detail rows. The FROM clause tells DB2 UDB which table(s) contain the requested data. The WHERE clause specifies which row(s) of information are to be used based upon some qualification criteria. The GROUP BY clause tells DB2 UDB which row(s) of information are to be grouped together (that is, summarized) based upon values in a column(s). The HAVING clause tells DB2 UDB which group(s) of information are to be processed based upon a group qualification criteria. The ORDER BY clause specifies sequence of the result rows in the final result table.
5-18 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Conceptual Execution of a SELECT (1 of 2) BASE TABLE JOB SAL S 31000 M 32000 S 30000 C 27000 S 33000 M 31000 S 32000 C 28000 S 30000 M 33000 S 31000 S 35000 C 27000 S 29000 S 29000
DEP BLU RED BLU GRE GRE BLU RED GRE RED GRE RED GRE BLU RED BLU
WHERE
GROUP BY
JOB SAL DEP S 31000 BLU
JOB SAL DEP C 27000 BLU
S C S
30000 BLU 27000 GRE 33000 GRE
S S S
31000 BLU 29000 BLU 30000 BLU
S C S
32000 RED 28000 GRE 30000 RED
C C
27000 GRE 28000 GRE
S S C S S
31000 35000 27000 29000 29000
S S
33000 GRE 35000 GRE
S S S S
32000 30000 31000 29000
RED GRE BLU RED BLU
RED RED RED RED
© Copyright IBM Corporation 2007
Figure 5-16. Conceptual Execution of a SELECT (1 of 2)
CF124.1
Notes: The clauses are executed in this sequence: • FROM • WHERE • GROUP BY Through the FROM clause DB2 UDB locates the table. The WHERE clause extracts into the conceptual intermediate table rows that will be processed further. The GROUP BY clause sorts the rows in the intermediate table into subsets.
© Copyright IBM Corp. 1999, 2007
Unit 5. Column Functions and Grouping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-19
Student Notebook
Conceptual Execution of a SELECT (2 of 2) HAVING
SELECT
ORDER BY
JOB
SAL
DEP
DEP
JOB
AVG(SAL)
DEP
JOB
AVG(SAL)
S S S
31000 BLU 29000 BLU 30000 BLU
BLU
S
30000
GRE RED BLU
S S S
34000 30500 30000
S S
33000 GRE 35000 GRE
GRE
S
34000
S S S S
32000 30000 31000 29000
RED
S
30500
RED RED RED RED
© Copyright IBM Corporation 2007
Figure 5-17. Conceptual Execution of a SELECT (2 of 2)
CF124.1
Notes: Only those groups passing the HAVING clause test are processed further.
5-20 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Checkpoint 1. True or False? A scalar function produces a summary row for a set of rows. 2. A SELECT statement whose SELECT list includes a column function (SUM, AVG, MIN, MAX, COUNT, and so forth) and three columns not in column functions does not require a GROUP BY clause. 3. Which clause qualifies groups for further processing? a. b. c. d. e. f.
SELECT FROM WHERE GROUP BY HAVING ORDER BY
4. True or False? The following query is syntactically correct. SELECT WORKDEPT, AVG(SALARY) FROM EMPLOYEE WHERE AVG(SALARY) > 20000 GROUP BY WORKDEPT HAVING COUNT(*) > 3 ORDER BY 2 DESC © Copyright IBM Corporation 2007
Figure 5-18. Checkpoint
CF124.1
Notes: Please write down your answers below: 1. 2. 3. 4.
© Copyright IBM Corp. 1999, 2007
Unit 5. Column Functions and Grouping
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-21
Student Notebook
Unit Summary Having completed this unit, you should be able to: Describe the difference between scalar and column functions List the more common DB2 column functions Group rows into sets based on one or more columns
© Copyright IBM Corporation 2007
Figure 5-19. Unit Summary
CF124.1
Notes:
5-22 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Unit 6. UNION What This Unit Is About This unit describes the syntax of an SQL statement that will produce a result table containing the results of two or more SELECT statements.
What You Should Be Able to Do After completing this unit, you should be able to: • Produce a single result table containing data from more than one query • State the UNION rules • State the difference between UNION and UNION ALL
How You Will Check Your Progress Accountability: • Checkpoint • Machine labs
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-1
Student Notebook
Unit Objectives After completing this unit, you should be able to: Produce a single result table containing data from more than one query State the UNION rules State the difference between UNION and UNION ALL
© Copyright IBM Corporation 2007
Figure 6-1. Unit Objectives
CF124.1
Notes:
6-2
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
6.1 UNION
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-3
Student Notebook
Multiple Queries - Multiple Reports QUERY 1 SELECT some_columns FROM some_table(s) WHERE some_conditions
DATA FROM QUERY 1
QUERY 2 SELECT some_columns FROM some_table(s) WHERE some_conditions
DATA FROM QUERY 2
© Copyright IBM Corporation 2007
Figure 6-2. Multiple Queries - Multiple Reports
CF124.1
Notes: Each time a query is executed a single report is produced. Sometimes we have a requirement for data returned by one query to appear in a report with data from additional queries.
6-4
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
UNIONing Queries Together - Single Report -- QUERY 1 SELECT some_columns FROM some_table(s) WHERE some_conditions
DATA FROM QUERY 1
UNION ALL DATA FROM QUERY 2 -- QUERY 2 SELECT some_columns FROM some_table(s) WHERE some_conditions
© Copyright IBM Corporation 2007
Figure 6-3. UNIONing Queries Together - Single Report
CF124.1
Notes: By following the UNION RULES, and adding a UNION ALL clause between the queries the data from both queries appears in a single report.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-5
Student Notebook
Union Rule Number 1 SELECT COL_6, COL_3, COL_8, COL_14 FROM TEST_TAB_A WHERE COL_7 = 'Y' UNION ALL SELECT COL_D, COL_Y, COL_A, COL_P FROM TEST_TAB_B WHERE COL_R < 7 Every query in the stack must return the same number of columns © Copyright IBM Corporation 2007
Figure 6-4. Union Rule Number 1
CF124.1
Notes: If the first query in the stack returns x number of columns every query in the stack must return x number of columns.
6-6
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Union Rule Number 2 SELECT COL_6, COL_3, COL_8, COL_14 FROM TEST_TAB_A WHERE COL_7 = 'Y' UNION ALL SELECT COL_D, COL_Y, COL_A, COL_P FROM TEST_TAB_B WHERE COL_R < 7 The data types of the nth column of each query in the stack must be compatible © Copyright IBM Corporation 2007
Figure 6-5. Union Rule Number 2
CF124.1
Notes: If the nth column in the first query returns character data then the corresponding nth column in every query of the stack must return character data. Column lengths do not have to match. Numeric precision and scale do not have to match (integer and DEC(7,2) data can appear in the same column). The report column will carry the largest precision and scale of all numbers in the column.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-7
Student Notebook
Union Rule Number 3 SELECT COL_6, COL_3, COL_8 AS C3 FROM TEST_TAB_A WHERE COL_7 = 'Y' UNION ALL SELECT COL_D, COL_Y, COL_A AS C3 FROM TEST_TAB_B WHERE COL_R < 7 ORDER BY C3 DESC, 2 The ORDER BY clause must be the last clause on the last query in the stack © Copyright IBM Corporation 2007
Figure 6-6. Union Rule Number 3
CF124.1
Notes: Only one ORDER BY clause allowed on a UNIONed query.
6-8
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
UNION ALL - Example 1 For workdepts C01 and A00 display workdept, last name concatenated to first name and in a GENDER column print MALE or FEMALE where appropriate
SELECT WORKDEPT, LASTNAME || ', ' || FIRSTNME AS NAME, 'MALE' AS GENDER FROM EMPLOYEE WHERE SEX = 'M' AND WORKDEPT IN ('A00', 'C01') UNION ALL SELECT WORKDEPT, LASTNAME || ', ' || FIRSTNME AS NAME, 'FEMALE' AS GENDER FROM EMPLOYEE WHERE SEX = 'F' AND WORKDEPT IN ('A00', 'C01') ORDER BY WORKDEPT
WORKDEPT A00 A00 A00 C01 C01 C01
NAME HAAS, CHRISTINE LUCCHESSI, VINCENZO O'CONNELL, SEAN KWAN, SALLY QUINTANA, DOLORES NICHOLLS, HEATHER
GENDER FEMALE MALE MALE FEMALE FEMALE FEMALE
© Copyright IBM Corporation 2007
Figure 6-7. UNION ALL - Example 1
CF124.1
Notes: The above example is one of several ways of translating coded data into more human terms (the value of M replaced with the word MALE, the value of F replaced with the word FEMALE.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-9
Student Notebook
UNION ALL - Example 2 SELECT As sketched out below, use two lines per department. On line one print manager's information, on line two print department information.
MGRNO 000010 000010 000020 000020 000030 000030 000050 000050
Mgr.: Dept.: Mgr.: Dept.: Mgr.: Dept.: Mgr.: Dept.:
MGRNO , 'Dept.:', DEPTNAME AS NAME FROM DEPARTMENT WHERE MGRNO IS NOT NULL UNION ALL SELECT MGRNO, 'Mgr.:', LASTNAME AS NAME FROM DEPARTMENT D, EMPLOYEE E WHERE D.MGRNO = E.EMPNO ORDER BY 1,2 DESC
NAME HAAS SPIFFY COMPUTER SERVICE DIV. THOMPSON PLANNING KWAN INFORMATION CENTER GEYER SUPPORT SERVICES
© Copyright IBM Corporation 2007
Figure 6-8. UNION ALL - Example 2
CF124.1
Notes: The first SELECT establishes the column headings of the result. If a column you wish to sort by has the same name in each query in the stack, then the column name can be used in the ORDER BY clause. Otherwise, the column's position number must be used.
6-10 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
UNION ALL - Example 3 SELECT FROM WHERE
LASTNAME, EDLEVEL EMPLOYEE JOB = 'ANALYST'
LASTNAME QUINTANA NICHOLLS
EDLEVEL 16 18
SELECT FROM WHERE
LASTNAME, EDLEVEL EMPLOYEE EDLEVEL = 18
LASTNAME HAAS THOMPSON NICHOLLS LUTZ
EDLEVEL 18 18 18 18
SELECT FROM WHERE UNION ALL SELECT FROM WHERE
LASTNAME, EDLEVEL EMPLOYEE JOB = 'ANALYST'
LASTNAME QUINTANA NICHOLLS HAAS THOMPSON NICHOLLS LUTZ
EDLEVEL 16 18 18 18 18 18
LASTNAME, EDLEVEL EMPLOYEE EDLEVEL = 18 © Copyright IBM Corporation 2007
Figure 6-9. UNION ALL - Example 3
CF124.1
Notes: UNION ALL does not eliminate duplicates. Use UNION ALL if the queries cannot return duplicate rows.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-11
Student Notebook
UNION SELECT FROM WHERE
LASTNAME, EDLEVEL EMPLOYEE JOB = 'ANALYST'
LASTNAME NICHOLLS QUINTANA
EDLEVEL 18 16
SELECT FROM WHERE
LASTNAME, EDLEVEL EMPLOYEE EDLEVEL = 18
LASTNAME HAAS LUTZ NICHOLLS THOMPSON
EDLEVEL 18 18 18 18
SELECT FROM WHERE UNION SELECT FROM WHERE
LASTNAME, EDLEVEL EMPLOYEE JOB = 'ANALYST'
LASTNAME HAAS LUTZ NICHOLLS QUINTANA THOMPSON
EDLEVEL 18 18 18 16 18
LASTNAME, EDLEVEL EMPLOYEE EDLEVEL = 18 © Copyright IBM Corporation 2007
Figure 6-10. UNION
CF124.1
Notes: UNION combines two sets of rows and removes duplicates. Therefore, UNION ALL often performs better than UNION. The problem to list last name and education level of employees who are analysts or have an education level of 18 can be solved by means of a UNION performing the following three steps: 1. Each SELECT is evaluated separately 2. The results are merged and ordered 3. Duplicates are removed
6-12 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
UNION - Generation of Fitting Result Rows SELECT FROM UNION SELECT FROM UNION SELECT FROM UNION SELECT
FROM ORDER BY
EMPNO, SUBSTR(FIRSTNME, 1, 1) || '.' || MIDINIT, LASTNAME, SALARY AS INCOME, 1 AS SORT EMPLOYEE ALL EMPNO, ' ', ' ', BONUS, 2 AS SORT EMPLOYEE ALL EMPNO, ' ', ' ', COMM, 3 AS SORT EMPLOYEE ALL EMPNO, ' ', 'SUM: ', SALARY + BONUS + COMM, 4 AS SORT EMPLOYEE EMPNO, SORT
EMPNO 000010 000010 000010 000010 000020 000020 000020 000020 .
LASTNAME C.I
HAAS
M.L
SUM: THOMPSON
.
SUM:.
INCOME 52750.00 1000.00 4220.00 57970.00 41250.00 800.00 3300.00 45350.00 .
SORT 1 2 3 4 1 2 3 4.
© Copyright IBM Corporation 2007
Figure 6-11. UNION - Generation of Fitting Result Rows
CF124.1
Notes: Any type of SELECT statement can be used as long as the rules for UNION are adhered to. All column and scalar functions can be used. In the above example, a substring of first name concatenated with the MIDINIT and the last name are selected in the first SELECT. To get the equivalent number of columns in the other SELECT statements, blanks (compatible to the data types of the concatenated value and the last name value) are specified as corresponding column values. Numeric literals, current date or current time can be 'place holders' at the appropriate spots in UNIONed queries. EMPNO must be selected to order the result table. To get a four row result for each employee in the desired order (1st salary, 2nd bonus, 3rd commission, 4th sum), we need an additional sort column. The double exclamation points (!!), and double bars (||) (in environments where they are supported), are equivalent to the CONCAT operator (which is supported in all
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-13
Student Notebook
environments). Check the manuals for your environment to determine its supported operator concatenation operators.
6-14 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
EXCEPT and INTERSECT SELECT FROM WHERE EXCEPT SELECT FROM WHERE
LASTNAME, EDLEVEL EMPLOYEE JOB = 'ANALYST'
LASTNAME
EDLEVEL
QUINTANA
16
LASTNAME
EDLEVEL
NICHOLLS
18
LASTNAME, EDLEVEL EMPLOYEE EDLEVEL = 18
LASTNAME, EDLEVEL SELECT EMPLOYEE FROM JOB = 'ANALYST' WHERE INTERSECT LASTNAME, EDLEVEL SELECT FROM EMPLOYEE WHERE EDLEVEL = 18
© Copyright IBM Corporation 2007
Figure 6-12. EXCEPT and INTERSECT
CF124.1
Notes: Here are two other sets of words that can be used in place of UNION ALL and UNION. They are also used for merging data, but work differently. EXCEPT displays what is in the first result set but not in the second result set. In this case, it displays ANALYSTS who are not edlevel 18. This would show duplicates if there were any; EXCEPT ALL would not. INTERSECT displays only what is in both the first result set and in the second result set. In this case, it displays ONLY ANALYSTS who are ALSO edlevel 18. This would show duplicates if there were any; INTERSECT ALL would not.
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-15
Student Notebook
Checkpoint 1. True or False? The results of arbitrary SELECTs can be combined by means of UNION and ordered to get a new result. 2. Why or when should you use UNION? a. When all duplicate rows have to be eliminated. b. When SELECTs with an arbitrary number of columns should be combined.
3. Which rules do you have to consider when using UNION?
© Copyright IBM Corporation 2007
Figure 6-13. Checkpoint
CF124.1
Notes: Please write down your answers below: 1. 2. 3.
6-16 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Unit Summary Having completed this unit, you should be able to: Produce a single result table containing data from more than one query State the UNION rules State the difference between UNION and UNION ALL
© Copyright IBM Corporation 2007
Figure 6-14. Unit Summary
CF124.1
Notes:
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
Unit 6. UNION
6-17
Student Notebook
6-18 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Unit 7. Using Subqueries What This Unit Is About This unit provides information on how to use subqueries.
What You Should Be Able to Do After completing this unit, you should be able to: • Use subqueries in WHERE and HAVING clauses • Code subqueries using basic predicates • Code subqueries using the IN keyword
How You Will Check Your Progress Accountability: • Checkpoint • Machine labs
© Copyright IBM Corp. 1999, 2007
Unit 7. Using Subqueries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-1
Student Notebook
Unit Objectives After completing this unit, you should be able to: Use subqueries in WHERE and HAVING clauses Code subqueries using basic predicates Code subqueries using IN
© Copyright IBM Corporation 2007
Figure 7-15. Unit Objectives
CF124.1
Notes: It is often useful to imbed a query within another. This enables the inner query to provide an answer to a question for use in the outer query. The inner query is referred to as a subquery.
7-2
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
7.1 Using Subqueries
© Copyright IBM Corp. 1999, 2007
Unit 7. Using Subqueries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-3
Student Notebook
Result Using Separate Selects Whose salary is higher than the average salary?
First Select:
SELECT FROM
AVG(SALARY) EMPLOYEE
27303 Second Select:
SELECT FROM WHERE
EMPNO, LASTNAME EMPLOYEE SALARY > 27303
© Copyright IBM Corporation 2007
Figure 7-16. Result Using Separate Selects
CF124.1
Notes: Assume that you want to identify all employees whose salary is higher than the average salary of all employees. Without subqueries, you would have to do the following: • Evaluate the average salary of all employees (first select) • Code a second query using the result (27303) in the WHERE clause. • Run the second query to find the employees whose salary is higher than the average salary (27303).
7-4
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Same Result Using a Subquery
SELECT
EMPNO, LASTNAME
FROM
EMPLOYEE
WHERE
SALARY > (SELECT AVG(SALARY) FROM
EMPLOYEE)
© Copyright IBM Corporation 2007
Figure 7-17. Same Result Using a Subquery
CF124.1
Notes: The problem, described on the previous visual can be solved by means of a single execution of a query containing a subquery. We can code the first SELECT of the previous visual in the WHERE condition of the second SELECT of the previous visual at the place where the average is needed. As a consequence, the second SELECT is executed by the outer(main) query. The inner SELECT is referred to as the subquery. The subquery runs first, and the result is used to evaluate the WHERE condition of the main query. A subquery cannot contain an ORDER BY. The results of the subquery are passed to the outer query and are not visible to the user.
© Copyright IBM Corp. 1999, 2007
Unit 7. Using Subqueries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-5
Student Notebook
Subquery with Basic Predicates Who earned the lowest bonus?
EMPNO
LASTNAME
000010 000070 000290
HAAS PULASKI PARKER
BONUS 1000 700 300
SELECT EMPNO, LASTNAME, BONUS FROM
EMPLOYEE
WHERE BONUS = (SELECT MIN (BONUS) FROM EMPLOYEE)
EMPNO
LASTNAME
000290
PARKER
BONUS 300
© Copyright IBM Corporation 2007
Figure 7-18. Subquery with Basic Predicates
CF124.1
Notes: In this example, we look for the employee(s) who earned the lowest bonus. The subquery will determine the lowest bonus and it will be compared with the bonuses of all employees. If the bonus of an employee matches the value provided by the subquery, the result of the predicate is true and the row is returned. A basic predicate is one that uses single value comparison operator (=, , or any combination thereof). A subquery in a basic predicate must not return more than one value.
7-6
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Subquery Using IN List the names and employee numbers of employees who are managers of a department
SELECT FIRSTNME, LASTNAME, EMPNO FROM EMPLOYEE WHERE EMPNO IN (SELECT MGRNO FROM DEPARTMENT) Final result
Result of subquery
FIRSTNME
LASTNAME
EMPNO
CHRISTINE
HAAS
000010
000010
MICHAEL
THOMPSON
000020
000020
SALLY
KWAN
000030
000030
JOHN
GEYER
000050
000050
IRVING
STERN
000060
000060
EVA
PULASKI
000070
000070
EILEEN
HENDERSE N
000090
000090
SPENSER
000100
THEODORE
000100 -
© Copyright IBM Corporation 2007
Figure 7-19. Subquery Using IN
CF124.1
Notes: IN and NOT IN can be used to compare with a list of values. IN means that for the condition to evaluate TRUE, the value in the first operand (EMPNO in the example) must be equal to at least one of the values in the list returned by the subquery.
© Copyright IBM Corp. 1999, 2007
Unit 7. Using Subqueries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-7
Student Notebook
Variations on Predicates SELECT EMPNO, LASTNAME, WORKDEPT, JOB FROM EMPLOYEE WHERE (WORKDEPT, JOB) = ('D21', 'CLERK')
EMPNO 000230 000240 000250 000260 000270
LASTNAME JEFFERSON MARINO SMITH JOHNSON PEREZ
WORKDEPT D21 D21 D21 D21 D21
JOB CLERK CLERK CLERK CLERK CLERK
© Copyright IBM Corporation 2007
Figure 7-20. Variations on Predicates
CF124.1
Notes: In later releases of DB2 UDB it is possible to use the syntax illustrated in this WHERE clause. A list of items enclosed in parenthesis can be compared with a list of values, also enclosed in parenthesis, on the right hand side of the comparison operator. Both lists must contain the same number of items and the items must be data type compatible. The comparison operator must be equal (=) or not equal (). DB2 UDB will rewrite the WHERE clause to the equivalent of: WHERE WORKDEPT = 'D21' AND JOB = 'CLERK' Check the reference manuals for your environment to determine if the syntax is supported.
7-8
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Subquery Using IN List the people in Smith's department that have the same job as Smith
FIRSTNME JAMES SALVATORE DANIEL SYBIL MARIA ETHEL JOHN PHILIP MAUDE
SELECT FIRSTNME, LASTNAME, WORKDEPT, JOB FROM EMPLOYEE WHERE (WORKDEPT, JOB) IN (SELECT WORKDEPT, JOB FROM EMPLOYEE WHERE LASTNAME = 'SMITH') LASTNAME JEFFERSON MARINO SMITH JOHNSON PEREZ SCHNEIDER PARKER SMITH SETRIGHT
WORKDEPT D21 D21 D21 D21 D21 E11 E11 E11 E11
JOB CLERK CLERK CLERK CLERK CLERK OPERATOR OPERATOR OPERATOR OPERATOR
© Copyright IBM Corporation 2007
Figure 7-21. Subquery Using IN
CF124.1
Notes: Later releases of DB2 UDB support the above syntax with a list of items enclosed in parenthesis compared with a multiple value comparison operator to a subquery returning zero, one or more rows with the same number of items as in the list on the left. The comparison operator must be IN or NOT IN, even if the subquery returns only one row.
© Copyright IBM Corp. 1999, 2007
Unit 7. Using Subqueries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-9
Student Notebook
Subquery Using NOT IN DEPARTMENT Table
Which departments do not have projects assigned to them?
DEPTNO
DEPTNAME
A00 B01 C01
SPIFFY COMPUTER SERVICE PLANNING INFORMATION CENTER
...
SELECT FROM WHERE
...
DEPTNO, DEPTNAME DEPARTMENT DEPTNO NOT IN (SELECT DEPTNO FROM PROJECT WHERE DEPTNO IS NOT NULL)
Result of Subquery Final Result
B01 C01 D01 D11 D21 E01 E11 E21
DEPTNO DEPTNAME A00
SPIFFY COMPUTER SERVICE
© Copyright IBM Corporation 2007
Figure 7-22. Subquery Using NOT IN
CF124.1
Notes: The subquery in the example builds a list of the DEPTNO values for every department of the PROJECT table. The outer query determines the department number and department name of any department whose department number is NOT in the list returned by the subquery. In other words, the query is reporting on departments which do not have projects. The IN predicate, when used with a subquery, enables the outer query to compare the values in a column of the outer table with a list of values provided by the subquery. For an IN predicate, if any of the non-null values returned by the subquery match any of the non-null values of the column being searched in the outer query, the rows in the outer query that contain the matching value will appear in the final result set. Nulls in the subquery result will never match nulls in the outer query result. When the IN is prefaced with a NOT, as in the example, the subquery should be written to return only non-null values. Then, all of the rows of the outer query that do not match any of the values returned by the subquery will appear in the result set. If the NOT IN subquery returns a null, the outer query will always produce an empty result set! 7-10 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Subquery within HAVING Clause I need a list of the departments whose average salary for non-managers is higher than the company-wide average for non-managers. The department with the highest average should be listed first. SELECT FROM WHERE GROUP BY HAVING
WORKDEPT, AVG(SALARY) AS AVG_WORKDEPT EMPLOYEE JOB 'MANAGER' WORKDEPT AVG(SALARY) > (SELECT AVG(SALARY) FROM EMPLOYEE WHERE JOB 'MANAGER') ORDER BY AVG_WORKDEPT DESC
Final Result WORKDEPT A00 C01
AVG_WORKDEPT 42833.33333333 26110.00000000
Result of Subquery 25188.80000000
© Copyright IBM Corporation 2007
Figure 7-23. Subquery within HAVING Clause
CF124.1
Notes: Subqueries can be also used in a HAVING condition for GROUP values.
© Copyright IBM Corp. 1999, 2007
Unit 7. Using Subqueries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-11
Student Notebook
Restrictions/Reminders Subqueries Must be on right side of search condition when used in WHERE clause or in HAVING clause Must be enclosed in parentheses Can return single or multiple values Number of values subquery can return must be compatible with operator in outer SELECT The subquery must return the same number of items as in the list to which it is compared
© Copyright IBM Corporation 2007
Figure 7-24. Restrictions/Reminders
CF124.1
Notes:
7-12 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Checkpoint 1. True or False? Subqueries can be used in WHERE or HAVING clauses of a SELECT. 2. If you want to list the employees whose salary is the highest, the outer query's WHERE clause may be coded: a. WHERE SALARY > (SELECT SALARY FROM EMPLOYEE..) b. WHERE SALARY = (SELECT MAX(SALARY) FROM EMPLOYEE..) c. WHERE SALARY > ALL (SELECT SALARY FROM EMPLOYEE..)
3. What is the keyword taught in this topic that compares a single value to a set of values returned by a subquery, looking for a match?
© Copyright IBM Corporation 2007
Figure 7-25. Checkpoint
CF124.1
Notes: Please write down your answers below: 1. 2. 3.
© Copyright IBM Corp. 1999, 2007
Unit 7. Using Subqueries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-13
Student Notebook
Unit Summary Having completed this unit, you should be able to: Use subqueries in WHERE and HAVING clauses Code subqueries using basic predicates Code subqueries using IN
© Copyright IBM Corporation 2007
Figure 7-26. Unit Summary
CF124.1
Notes:
7-14 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Unit 8. Maintaining Data What This Unit Is About Along with the SELECT statement, the SQL Data Manipulation Language (DML) has three additional SQL statements. These are used to add rows to a table (INSERT), modify data within existing rows (UPDATE), and remove rows (DELETE).
What You Should Be Able to Do After completing this unit, you should be able to: • Create a simple table for testing DML statements • Create a simple view • Insert rows into a table • Update data in a table • Delete rows from a table • Drop a table
How You Will Check Your Progress Accountability: • Checkpoint • Machine labs
© Copyright IBM Corp. 1999, 2007
Unit 8. Maintaining Data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-1
Student Notebook
Unit Objectives After completing this unit, you should be able to: Create a simple table to test DML statements Create a view Insert rows into a table Update data in a table Delete rows from a table Drop a table
© Copyright IBM Corporation 2007
Figure 8-27. Unit Objectives
CF124.1
Notes: Creating tables is normally done by database administrators. For test purposes, it could be helpful to create a simple test table by yourself. After the test table has been created, INSERT, UPDATE, and DELETE statements can be used to add rows, change rows, and remove rows.
8-2
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
8.1 Maintaining Data
© Copyright IBM Corp. 1999, 2007
Unit 8. Maintaining Data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-3
Student Notebook
TESTEMP Table
EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS 000010 000020 000030 000050 000111
HAAS THOMPSON KWAN GEYER SMITH
A00 B01 C01 E01 C01
1965-01-01 1973-10-10 1975-04-04 1949-08-17 1998-06-25
52750.00 41250.00 38250.00 40175.00 25000.00
1000.00 800.00 800.00 800.00 -
© Copyright IBM Corporation 2007
Figure 8-28. TESTEMP Table
CF124.1
Notes: The visual shows the contents of the TESTEMP table. This table will be the basis for the exercises of this unit.
8-4
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Create Table TESTEMP CREATE TABLE TESTEMP (EMPNO
CHAR(6)
NOT NULL,
LASTNAME
VARCHAR(15)
NOT NULL,
WORKDEPT
CHAR(3)
,
HIREDATE
DATE
,
SALARY
DECIMAL(9,2)
,
BONUS
DECIMAL(9,2)
)
-- IN DB_NAME.TS_NAME -- or -- IN DATABASE DB_NAME -- or -- IN TS_NAME © Copyright IBM Corporation 2007
Figure 8-29. Create Table TESTEMP
CF124.1
Notes: This CREATE TABLE statement creates the TESTEMP table. In addition to the column definitions, an IN clause may be required. The format of the IN clause depends on the environment. z/OS: IN DB_NAME.TS_NAME - Table must be created in the named table space IN DATABASE DB_NAME - If a database DB_NAME has been provided, and the table is to be created in a table space which will be created by the system in this database. No IN clause if the table is to be created in the default database. This is almost never allowed by administrators in a z/OS environment. Linux, UNIX, and Windows: IN TS_NAME - If a table space TS_NAME has been provided and the table should be created in this table space.
© Copyright IBM Corp. 1999, 2007
Unit 8. Maintaining Data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-5
Student Notebook
No IN clause if a default table space has been provided and the table should be created in the default table space. iSeries: the IN clause is not used. Databases or table spaces are generally provided by a database administrator.
8-6
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Create View PERSINFO CREATE VIEW PERSINFO AS SELECT EMPNO, LASTNAME, SALARY AS YEAR_SAL FROM TESTEMP WHERE WORKDEPT = 'C01'
SELECT * FROM PERSINFO EMPNO LASTNAME YEAR_SAL 000030 000111
KWAN SMITH
38250.00 25000.00
© Copyright IBM Corporation 2007
Figure 8-30. Create View PERSINFO
CF124.1
Notes: This CREATE VIEW statement describes a part of the base table, consisting of employee number, last name, and yearly salary of all employees in department C01. The AS clause in the subselect enables you to specify column names in the view different from the column names in the referenced table. In the above example, "SALARY AS YEAR_SAL" is used to rename the SALARY column in the base table TESTEMP to YEAR_SAL in view PERSINFO. Users referencing the view PERSINFO must use the new column name. Another possibility for renaming columns in a view is: CREATE VIEW PERSINFO (EMPNO, LASTNAME, YEAR_SAL) AS SELECT EMPNO, LASTNAME, SALARY FROM EMPLOYEE WHERE WORKDEPT = 'C01' When using this syntax, the number of column names listed in the parentheses must match the number of the selected columns.
© Copyright IBM Corp. 1999, 2007
Unit 8. Maintaining Data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-7
Student Notebook
Users who are authorized to use view PERSINFO will get the listed columns for employees whose department number is C01. Other data is not visible.
8-8
DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Inserting Rows into the Table INSERT INTO TESTEMP VALUES ('000111', 'SMITH', 'C01', '1998-06-25', 25000, NULL) OR INSERT INTO TESTEMP (EMPNO, LASTNAME, WORKDEPT, HIREDATE, SALARY) VALUES ('000111', 'SMITH', 'C01', '1998-06-25', 25000)
EMPNO 000111
LASTNAME SMITH
WORKDEPT C01
HIREDATE 1998-06-25
SALARY 25000.00
BONUS -
© Copyright IBM Corporation 2007
Figure 8-31. Inserting Rows into the Table
CF124.1
Notes: Use an INSERT statement to insert a row into a table. Inserting a row via a view inserts the row into the table on which the view is based. Therefore, inserts via a view are only possible if the view contains all columns that are defined with NOT NULL without a DEFAULT value in the base table. In the first example, the column list is omitted. In this case, a value for each column in the table or view must be provided in the VALUES clause, in the order they are defined for the table or the view. In the second example, a column list is specified. The number of values provided for a row via the VALUES clause must be equal to the number of column names in the column list. The first value is inserted in the first column of the list, the second value in the second column, and so on.
© Copyright IBM Corp. 1999, 2007
Unit 8. Maintaining Data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-9
Student Notebook
DB2 UDB for Linux, UNIX, and Windows allows inserting multiple rows in one INSERT statement; for example: INSERT INTO TESTEMP VALUES ('000111', 'SMITH', 'C01', '1998-06-25', 25000, NULL), ('000113', 'JONES', 'C01', '2001-06-25', 25000, NULL), ('000114', 'THOMPSON', 'C01', '2001-06-25', 25000, NULL)
8-10 DB2 SQL Workshop
© Copyright IBM Corp. 1999, 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
V3.1.0.1 Student Notebook
Uempty
Insert Multiple Rows INSERT INTO TESTEMP SELECT EMPNO,LASTNAME,WORKDEPT,HIREDATE,SALARY,BONUS FROM
EMPLOYEE
WHERE EMPNO
View more...
Comments