DB2 SQL Workshop (Course Code CF12) Student Notebook ERC 4.1 IBM Certified Course Material V3.1.0.1 cover
V3.1.0.1
cover
���
Front coverDB2 SQL Workshop (Course Code CF12)
Student NotebookERC 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:
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.
AIX DB2 iSeriesOS/390 POWER QMFWebSphere z/OS 400
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 withoutany warranty either express or implied. The use of this information or the implementation of any of these techniques is a customerresponsibility and depends on the customer’s ability to evaluate and integrate them into the customer’s operational environment. Whileeach item may have been reviewed by IBM for accuracy in a specific situation, there is no guarantee that the same or similar results willresult elsewhere. Customers attempting to adapt these techniques to their own environments do so at their own risk.
© 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 restrictionsset forth in GSA ADP Schedule Contract with IBM Corp.
Student NotebookV3.1.0.1
TOC
ContentsTrademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Course Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
Agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
Unit 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
1.1 Introduction to Relational Data Management Systems . . . . . . . . . . . . . . . . . . . 1-3Computerless Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4Relational Database Management System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5Computerless Data Retrieval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6Asking for Information - RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7SQL Structured Query Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9Table Name Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10Sample Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11Sample Alphanumeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12Date Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13Time Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14CREATE TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15NULL Characteristic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17VIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20
Unit 2. Simple SQL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
2.1 Simple SQL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3EMPLOYEE Table - Part 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4EMPLOYEE Table - Part 1 (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5DEPARTMENT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7PROJECT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8Structure of an SQL Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9Retrieving All Columns, All Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10Retrieving All Columns, Limited Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11Selecting Specific Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12Select with Ordered Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13Select with Ordered Output (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14Alternate ORDER BY Specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15Suppressing Duplicate Output Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16Suppressing Duplicate Output Rows (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17Retrieving Rows by Character Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Contents iii
Student Notebook
Retrieving Rows by Numerical Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-19Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-20AND and OR - Principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-21Multiple Conditions - AND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-22Multiple Conditions - OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-23Multiple Conditions - AND/OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-24Multiple Conditions - Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-25SELECT with IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-26SELECT with BETWEEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-27Retrieving Rows - Null Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-28Partial String Search - LIKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-29Partial String Search - Examples with '%' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-30Partial String Search - Example with '_' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-31Negation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-32Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-33Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-34
Unit 3. Retrieving Data from Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-2
3.1 Accessing Data Stored in Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3Retrieving Data from Multiple Tables (Principle) . . . . . . . . . . . . . . . . . . . . . . . . . . .3-4Retrieving Data from Multiple Tables (JOIN) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-5Correlation Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-6JOIN Syntax 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-7JOIN Syntax 2 (JOIN Keyword) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-8Another JOIN Example (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-9Another JOIN Example (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-10JOIN with Three Tables (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-11JOIN with Three Tables (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-12Joining a Table with Itself (1 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-13Joining a Table with Itself (2 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-14Joining a Table with Itself (3 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-15Joining a Table with Itself – Other Example (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . .3-16Joining a Table with Itself – Other Example (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . .3-17Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-18Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-19
Unit 4. Scalar Functions and Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-2
4.1 Scalar Functions and Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3Selecting Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-4Naming Result Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-5Substitution of NULL Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-6Arithmetic with NULL Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-7Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-8Decimal Representation of a Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-9Decimal Values - Truncation and Rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-10
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
iv DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
TOC
Condition on Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11Date and Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12CHAR Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13Comparison with Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14DATE / TIME Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15Subtraction of Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-16Date / Time Scalar Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17Date Scalar Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18DATE Arithmetic (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-19DATE Arithmetic (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20Substring of Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-21Substring of Strings (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-22Concatenation of Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-23Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-24Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-25Unit 5. Column Functions and Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
5.1 Column Functions and Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3SQL Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4Column Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5Sample Column Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7Beware of Nulls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8Column Functions Based on Subset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9GROUP BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10GROUP BY More than One Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11The Hardest to Remember Rule in All of SQL! . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12GROUP BY, ORDER BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13GROUP BY, HAVING (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14GROUP BY, HAVING (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15Examples with HAVING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17SELECT Statement - Six Clauses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18Conceptual Execution of a SELECT (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-19Conceptual Execution of a SELECT (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22
Unit 6. UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
6.1 UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3Multiple Queries - Multiple Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4UNIONing Queries Together - Single Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5Union Rule Number 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6Union Rule Number 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7Union Rule Number 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8UNION ALL - Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Contents v
Student Notebook
UNION ALL - Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-10UNION ALL - Example 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-11UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-12UNION - Generation of Fitting Result Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-13EXCEPT and INTERSECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-15Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-16Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-17
Unit 7. Using Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-2
7.1 Using Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3Result Using Separate Selects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-4Same Result Using a Subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-5Subquery with Basic Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-6Subquery Using IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-7Variations on Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-8Subquery Using IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-9Subquery Using NOT IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-10Subquery within HAVING Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-11Restrictions/Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-12Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-13Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-14
Unit 8. Maintaining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-2
8.1 Maintaining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3TESTEMP Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-4Create Table TESTEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-5Create View PERSINFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-7Inserting Rows into the Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-9Insert Multiple Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-11Update Columns (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-12Update Columns (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-13Delete Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-14Drop Table TESTEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-15Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-16Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-17Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-18
Appendix A. Checkpoint Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1
Appendix B. Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-1
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
vi DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
TMK
TrademarksThe 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:
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.
AIX® DB2® iSeries™OS/390® POWER™ QMF™WebSphere® z/OS® 400®
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Trademarks vii
Student Notebook
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
viii DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Course DescriptionDB2 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Course Description ix
Student Notebook
Contents
• Introduction • Simple SQL Queries • Retrieving data from multiple tables • Scalar functions and arithmetic • Column functions and grouping • UNION • Using Subqueries • Maintaining data
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
x DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
AgendaDay 1
WelcomeIntroductionSimple SQL QueriesExercise 1Exercise Review Retrieving Data from Multiple TablesExercise 2Exercise Review Scalar Functions and ArithmeticExercise 3
Day 2
Exercise review Column Functions and GroupingExercise 4Exercise Review UnionExercise 5Exercise Review Using SubqueriesExercise 6Exercise Review Maintaining DataExercise 7 Exercise Review
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Agenda vii
Student Notebook
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
xii DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Unit 1. IntroductionWhat 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-1
Student Notebook
Figure 1-1. Unit Objectives CF124.1
Notes:
© Copyright IBM Corporation 2006
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
1.1 Introduction to Relational Data Management SystemsCourse materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-3
Student Notebook
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.
© Copyright IBM Corporation 2006
Departments
Employees
Projects
Computerless Data Storage
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2006
FIRSTNME DEPTNAMEMIDINIT
WORKDEPTLASTNAME ...
..
.EMPNO
EMPLOYEE DEPARTMENTDEPTNO
000010
000020
000030
000050
000060
000070
CHRISTINE
MICHAEL
SALLY
JOHN
IRVING
EVA
I
L
A
B
F
D
HAAS
THOMPSON
KWAN
GEYER
STERN
PULASKI
A00
B01
C01
E01
D11
D21
A00
B01
C01
D01
D11
D21
SPIFFY COMPUTER SERVICE DIV.
PLANNING
INFORMATION CENTER
DEVELOPMENT CENTER
MANUFACTURING SYSTEMS
ADMINISTRATION SYSTEMS
PROJNAMEDEPTNO
..
.
PROJECTPROJNO
AD3100
AD3110
AD3111
AD3112
AD3113
IF1000
ADMIN SERVICES
GENERAL ADMIN SYSTEMS
PAYROLL PROGRAMMING
PERSONNEL PROGRAMMING
ACCOUNT PROGRAMMING
QUERY SERVICES
D01
D21
D21
D21
D21
C01
DatabaseA collection of
tables
Relational Database Management System
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-5
Student Notebook
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
© Copyright IBM Corporation 2006
Please give me a list of all employees in
department D11 sorted by name.
000150 ADAMSON BRUCE D11000200BROWN DAVID D11
000050GEYER B JOHN E01000340GOUNOT R JASON E21
000010HAAS I CHRISTINAA00
Computerless Data Retrieval
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 1-5. Asking for Information - RDBMS CF124.1
NotesHuman communication RDBMS Data requestor End-user, programmer, designer Human language Structured Query Language (SQL) A medium for communication - phone, notes, etc.
The medium depends on the environment. 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 Corporation 2006
RDBMSEMPLOYEE
ADAMSON
BROWN
GEYER
GOUNOT
HAAS
000150
000200
000050
000340
000010
BRUCE
DAVID
JOHN
JASON
CHRISTINE
B
R
T
D11
D11
E01
E21
A00
4510
4501
6789
5698
3978
SELECT * FROM
EMPLOYEE WHERE
WORKDEPT = 'D11'
ORDER BY LASTNAME SELECT Statement
EMPNO LASTNAMEMIDINIT FIRSTNME WORKDEPT PHONENO
Return a list ofemployees indepartment D11sorted by last name
Asking for Information - RDBMS
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-7
Student Notebook
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.
© Copyright IBM Corporation 2006
SQL Structured Query Language
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2006
numericcolumn
date columntext columncolumn
row
EMPNO FIRSTNME LASTNAME BIRTHDATE COMM
000010 CHRISTINE I HAAS 1933-08-24 9220
000330 WING LEE 1941-07-18 2030
. . .
. . .
. . .
. . .
. . .
. . .
. . .
000020 MICHAEL L THOMSON 1948-02-02 0
000030 SALLY A KWAN 1941-05-11 - - - - -
000050 JOHN B GEYER 1925-09-15 3214
MIDINIT
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
USERA.EMPLOYEE
Table
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-9
Student Notebook
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.
© Copyright IBM Corporation 2006
Qualified Table NameUSERA.EMPLOYEE
Table owner / Schema Simple Name
USERA EMPLOYEE
Table Name Construction
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2006
Data Type Comment
SMALLINT
INTEGER
DECIMAL(m,n)
Whole numbers from -32768 to +32767
Whole numbers from -2,147,483,648 to+2,147,483,647
Decimal numbers with max. 31 digitsm = total number of digitsn = number of decimal digits
Sample Numeric Data Types
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-11
Student Notebook
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.
© Copyright IBM Corporation 2006
Data Type Comment
CHAR(n) orCHARACTER(n)
VARCHAR(n)
STRING (fixed length)
STRING (variable length)
Sample Alphanumeric Data Types
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2006
Data Type Comment
DATE Display / Input FormatYYYYMMDD USA mm/dd/yyyy
EUR dd.mm.yyyyISO yyyy-mm-ddJIS yyyy-mm-dd
DATE / TIME / TIMESTAMP data type - input verificationallows arithmeticsortingcomponent extraction
Date Data Type
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-13
Student Notebook
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'
© Copyright IBM Corporation 2006
Data Type Comment
TIMEHHMMSS
Display / Input FormatsUSA hh:mm AM or PMEUR hh.mm.ssISO hh.mm.ssJIS hh:mm:ss
Time Data Type
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2006
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) )
Create Table
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-15
Student Notebook
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.
© Copyright IBM Corporation 2006
"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
NULL Characteristic
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2006
DEPARTMENT
EMPLOYEEPROJECT
REVOKE SELECT ON PROJECT FROM SALLY
GRANT SELECT ON PROJECT TO SALLY
Authorization
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-17
Student Notebook
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.
© Copyright IBM Corporation 2006
EMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO
000150 4510
000200 4501
000050 6789
000340 5698
000010 CHRISTINE T HAAS A00 3978
You only see what you should
Data security Simplification
BRUCE
JASON
DAVID
JOHN B
R
ADAMSON
BROWN
GEYER
GOUNOT
D11
D11
E01
E21
VIEW
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 1-17. Checkpoint CF124.1
Notes:
Please write down your answers below:
1.
2.
3.
4.
© Copyright IBM Corporation 2006
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).
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-19
Student Notebook
Figure 1-18. Unit Summary CF124.1
Notes:
© Copyright IBM Corporation 2006
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
1-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Unit 2. Simple SQL QueriesWhat 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-1
Student Notebook
Figure 2-1. Unit Objectives CF124.1
Notes:
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
2.1 Simple SQL QueriesCourse materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-3
Student Notebook
Figure 2-2. EMPLOYEE Table - Part 1 CF124.1
Notes:
EMPNO Employee number FIRSTNME First name MIDINIT Middle initial LASTNAME Last name WORKDEPT Department number PHONENO Phone number HIREDATE Hire date
© Copyright IBM Corporation 2007
MID WORK PHONE
EMPNO FIRSTNME INIT LASTNAME DEPT NO 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
EMPLOYEE Table - Part 1 (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-3. EMPLOYEE Table - Part 1 (Cont) CF124.1
Notes:
EMPNO Employee number (repeated for readability purpose) JOB Job EDLEVEL Education level (Ed-level) SEX Sex BIRTHDATE Date of birth SALARY Salary (yearly) BONUS Bonus (yearly) COMM Commission (yearly)
EMPNO is repeated on this page to facilitate row location. It is found only once within the Employee table.
© Copyright IBM Corporation 2007
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 MANAGER 16 M 1925-09-15 40175.00 800.00 3214.00
000060 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
EMPLOYEE Table - Part 1 (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-5
Student Notebook
Em
plo
yee
Tab
le D
ata
M
I
D
I
N S
I E
EMPNO FIRSTNME T LASTNAME WORKDEPT PHONENO HIREDATE JOB EDLEVEL X BIRTHDATE SALARY BONUS COMM
000010 CHRISTINE I HAAS A00 3978 1965-01-01 PRES 18 F 1933-08-14 52750.00 1000.00 4220.00
000020 MICHAEL L THOMPSON B01 3476 1973-10-10 MANAGER 18 M 1948-02-02 41250.00 800.00 3300.00
000030 SALLY A KWAN C01 4738 1975-04-05 MANAGER 20 F 1941-05-11 38250.00 800.00 3060.00
000050 JOHN B GEYER E01 6789 1949-08-17 MANAGER 16 M 1925-09-15 40175.00 800.00 3214.00
000060 IRVING F STERN D11 6423 1973-09-14 MANAGER 16 M 1945-07-07 32250.00 500.00 2580.00
000070 EVA D PULASKI D21 7831 1980-09-30 MANAGER 16 F 1953-05-26 36170.00 700.00 2893.00
000090 EILEEN W HENDERSON E11 5498 1970-08-15 MANAGER 16 F 1941-05-15 29750.00 600.00 2380.00
000100 THEODORE Q SPENSER E21 0972 1980-06-19 MANAGER 14 M 1956-12-18 26150.00 500.00 2092.00
000110 VINCENZO G LUCCHESSI A00 3490 1958-05-16 SALESREP 19 M 1929-11-05 46500.00 900.00 3720.00
000120 SEAN O'CONNELL A00 2167 1963-12-05 CLERK 14 M 1942-10-18 29250.00 600.00 2340.00
000130 DOLORES M QUINTANA C01 4578 1971-07-28 ANALYST 16 F 1925-09-15 23800.00 500.00 1904.00
000140 HEATHER A NICHOLLS C01 1793 1976-12-15 ANALYST 18 F 1946-01-19 28420.00 600.00 2274.00
000150 BRUCE ADAMSON D11 4510 1972-02-12 DESIGNER 16 M 1947-05-17 25280.00 500.00 2022.00
000160 ELIZABETH R PIANKA D11 3782 1977-10-11 DESIGNER 17 F 1955-04-12 22250.00 400.00 1780.00
000170 MASATOSHI J YOSHIMURA D11 2890 1978-09-15 DESIGNER 16 M 1951-01-05 24680.00 500.00 1974.00
000180 MARILYN S SCOUTTEN D11 1682 1973-07-07 DESIGNER 17 F 1949-02-21 21340.00 500.00 1707.00
000190 JAMES H WALKER D11 2986 1974-07-26 DESIGNER 16 M 1952-06-25 20450.00 400.00 1636.00
000200 DAVID BROWN D11 4501 1966-03-03 DESIGNER 16 M 1941-05-29 27740.00 600.00 2217.00
000210 WILLIAM T JONES D11 0942 1979-04-11 DESIGNER 17 M 1953-02-23 18270.00 400.00 1462.00
000220 JENNIFER K LUTZ D11 0672 1968-08-29 DESIGNER 18 F 1948-03-19 29840.00 600.00 2387.00
000230 JAMES J JEFFERSON D21 4265 1966-11-21 CLERK 14 M 1935-05-30 22180.00 400.00 1774.00
000240 SALVATORE M MARINO D21 3780 1979-12-05 CLERK 17 M 1954-03-31 28760.00 600.00 2301.00
000250 DANIEL S SMITH D21 0961 1969-10-30 CLERK 15 M 1939-11-12 19180.00 400.00 1534.00
000260 SYBIL P JOHNSON D21 8953 1975-09-11 CLERK 16 F 1936-10-05 17250.00 300.00 1380.00
000270 MARIA L PEREZ D21 9001 1980-09-30 CLERK 15 F 1953-05-26 27380.00 500.00 2190.00
000280 ETHEL R SCHNEIDER E11 8997 1967-03-24 OPERATOR 17 F 1936-03-28 26250.00 500.00 2100.00
000290 JOHN R PARKER E11 4502 1980-05-30 OPERATOR 12 M 1946-07-09 15340.00 300.00 1227.00
000300 PHILIP X SMITH E11 2095 1972-06-19 OPERATOR 14 M 1936-10-27 17750.00 400.00 1420.00
000310 MAUDE F SETRIGHT E11 3332 1964-09-12 OPERATOR 12 F 1931-04-21 15900.00 300.00 1272.00
000320 RAMLAL V MEHTA E21 9990 1965-07-07 FIELDREP 16 M 1932-08-11 19950.00 400.00 1596.00
000330 WING LEE E21 2103 1976-02-23 FIELDREP 14 M 1941-07-18 25370.00 500.00 2030.00
000340 JASON R GOUNOT E21 5698 1947-05-05 FIELDREP 16 M 1926-05-17 23840.00 500.00 1907.00
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-4. DEPARTMENT Table CF124.1
Notes:
DEPTNO Department numberDEPTNAME Department nameMGRNO Employee serial number of the responsible managerADMRDEPT Department number of the department to which this department reportsLOCATION 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 Corporation 2007
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 -
DEPARTMENT Table
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-7
Student Notebook
Figure 2-5. PROJECT Table CF124.1
Notes:
PROJNO Project number PROJNAME Project name DEPTNO Responsible department RESPEMP Employee number of the responsible employee PRSTAFF Estimated mean staffing PRSTDATE Estimated starting date PRENDATE Estimated ending date MAJPROJ Major project for a subproject
© Copyright IBM Corporation 2007
DEPT RESP PR MAJ
PROJNO PROJNAME NO EMP STAFF PRSTDATE PRENDATE PROJ
------ --------------------- ---- ------ ----- ---------- ---------- ------
AD3100 ADMIN SERVICES D01 000010 6.50 1982-01-01 1983-02-01 -
AD3110 GENERAL ADMIN SYSTEMS D21 000070 6.00 1982-01-01 1983-02-01 AD3100
AD3111 PAYROLL PROGRAMMING D21 000230 2.00 1982-01-01 1983-02-01 AD3110
AD3112 PERSONNEL PROGRAMMING D21 000250 1.00 1982-01-01 1983-02-01 AD3110
AD3113 ACCOUNT PROGRAMMING D21 000270 2.00 1982-01-01 1983-02-01 AD3110
IF1000 QUERY SERVICES C01 000030 2.00 1982-01-01 1983-02-01 -
IF2000 USER EDUCATION C01 000030 1.00 1982-01-01 1983-02-01 -
MA2100 WELD LINE AUTOMATION D01 000010 12.00 1982-01-01 1983-02-01 -
MA2110 W L PROGRAMMING D11 000060 9.00 1982-01-01 1983-02-01 MA2100
MA2111 W L PROGRAM DESIGN D11 000220 2.00 1982-01-01 1982-12-01 MA2110
MA2112 W L ROBOT DESIGN D11 000150 3.00 1982-01-01 1982-12-01 MA2110
MA2113 W L PROD CONT PROGS D11 000160 3.00 1982-02-15 1982-12-01 MA2110
OP1000 OPERATION SUPPORT E01 000050 6.00 1982-01-01 1983-02-01 -
OP1010 OPERATION E11 000090 5.00 1982-01-01 1983-02-01 OP1000
OP2000 GEN SYSTEMS SERVICES E01 000050 5.00 1982-01-01 1983-02-01 -
OP2010 SYSTEMS SUPPORT E21 000100 4.00 1982-01-01 1983-02-01 OP2000
OP2011 SCP SYSTEMS SUPPORT E21 000320 1.00 1982-01-01 1983-02-01 OP2010
OP2012 APPLICATIONS SUPPORT E21 000330 1.00 1982-01-01 1983-02-01 OP2010
OP2013 DB/DC SUPPORT E21 000340 1.00 1982-01-01 1983-02-01 OP2010
PL2100 WELD LINE PLANNING B01 000020 1.00 1982-01-01 1982-09-15 MA2100
PROJECT Table
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
SELECT - Defines result columnsColumn namesArithmetic expressionsLiterals (text or numeric)Scalar functionsColumn functionsConcatenation
FROM - Table or view namesWHERE - Conditions (qualifies rows)ORDER BY - Sorts result rows
Structure of an SQL Query
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-9
Student Notebook
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.
© Copyright IBM Corporation 2007
SPIFFY COMPUTER SERVICE DIV.PLANNINGINFORMATION CENTERDEVELOPMENT CENTERMANUFACTURING SYSTEMS ADMINISTRATION SYSTEMSSUPPORT SERVICESOPERATIONSSOFTWARE SUPPORT
DEPTNAME ADMRDEPT LOCATIONMGRNODEPTNOA00 -A00 -A00 -A00 -D01 -D01 -A00 -E01 -E01 -
000010000020000030
-000060000070000050000090000100
A00B01C01D01D11D21E01E11E21
SELECT *FROM DEPARTMENT
I need a listing of alldepartment data
Retrieving All Columns, All Rows
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
What does the datalook like in the
Department table?
SELECT * FROM DEPARTMENTFETCH FIRST 5 ROWS ONLY
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 -
Retrieving All Columns, Limited Rows
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-11
Student Notebook
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.
© Copyright IBM Corporation 2007
For each department, I needits number, its name and the
department to which it reports.
SELECT DEPTNO, DEPTNAME, ADMRDEPT
FROM DEPARTMENT
DEPTNO DEPTNAME ADMRDEPTA00 SPIFFY COMPUTER SERVICE DIV. A00B01 PLANNING A00C01 INFORMATION CENTER A00D01 DEVELOPMENT CENTER A00D11 MANUFACTURING SYSTEMS D01D21 ADMINISTRATION SYSTEMS D01E01 SUPPORT SERVICES A00E11 OPERATIONS E01E21 SOFTWARE SUPPORT E01
Selecting Specific Columns
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
SPIFFY COMPUTER SERVICE DIV.INFORMATION CENTERPLANNINGSUPPORT SERVICESDEVELOPMENT CENTERMANUFACTURING SYSTEMSADMINISTRATION SYSTEMSSOFTWARE SUPPORTOPERATIONS
DEPTNAME ADMRDEPTDEPTNOA00A00A00A00A00D01D01E01E01
A00C01B01E01D01D11D21E21E11
By the way, the listingshould be sorted by the department reported to
SELECT DEPTNO, DEPTNAME, ADMRDEPTFROM DEPARTMENTORDER BY ADMRDEPT ASC
Select with Ordered Output (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-13
Student Notebook
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.
© Copyright IBM Corporation 2007
SELECT DEPTNO, DEPTNAME, ADMRDEPTFROM DEPARTMENTORDER BY ADMRDEPT ASC, DEPTNO DESC
DEPTNO DEPTNAME ADMRDEPTE01 SUPPORT SERVICES A00D01 DEVELOPMENT CENTER A00C01 INFORMATION CENTER A00B01 PLANNING A00A00 SPIFFY COMPUTER SERVICE DIV. A00D21 ADMINISTRATION SYSTEMS D01D11 MANUFACTURING SYSTEMS D01E21 SOFTWARE SUPPORT E01E11 OPERATIONS E01
Select with Ordered Output (2 of 2)
I need the previous listingordered first according to the number
to which the department reportsand within that sequence sorted bydescending department numbers.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
SELECT LASTNAME, FIRSTNME, WORKDEPT, JOB, SEXFROM EMPLOYEEORDER 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 DESCORDER BY 3 DESC, 4 ASC, 1 ASC, 5 DESCORDER BY 3 DESC, JOB, LASTNAME, 5 DESCORDER BY WORKDEPT DESC, 4 ASC, 1 ASC, SEX DESC
Alternate ORDER BY Specifications
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-15
Student Notebook
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.
© Copyright IBM Corporation 2007
Now, I want to know the different jobs
performedby the employees.
SELECT DISTINCT JOBFROM EMPLOYEE
JOBANALYSTCLERKDESIGNERFIELDREPMANAGEROPERATORPRESSALESREP
SELECT JOBFROM EMPLOYEEORDER BY JOB
JOBANALYST ANALYST CLERK CLERK CLERK CLERK
.
.
Suppressing Duplicate Output Rows (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
Also, I need a listing of thejob distribution by department
SELECT DISTINCT WORKDEPT, JOBFROM EMPLOYEEORDER BY WORKDEPT, JOB
WORKDEPT JOBA00 CLERK A00 PRES A00 SALESREPB01 MANAGER C01 ANALYST C01 MANAGER D11 DESIGNERD11 MANAGER D21 CLERK D21 MANAGER E01 MANAGER E11 MANAGER E11 OPERATORE21 FIELDREPE21 MANAGER
SELECT WORKDEPT, JOBFROM EMPLOYEEORDER BY WORKDEPT, JOB
WORKDEPT JOBA00 CLERK A00 PRES A00 SALESREPB01 MANAGER C01 ANALYST C01 ANALYST C01 MANAGER D11 DESIGNERD11 DESIGNERD11 DESIGNERD11 DESIGNERD11 DESIGNERD11 DESIGNER
. .
. .
Suppressing Duplicate Output Rows (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-17
Student Notebook
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.
© Copyright IBM Corporation 2007
DEPTNO ADMRDEPTA00 A00B01 A00C01 A00D01 A00E01 A00
I need a list of thedepartments reporting to
department A00
SELECT DEPTNO, ADMRDEPTFROM DEPARTMENTWHERE ADMRDEPT = 'A00'
Retrieving Rows by Character Comparison
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
LASTNAME EDLEVELKWAN 20LUCCHESSI 19
I want the last name and education level of all employees
with an education levelgreater than or equal to 19
SELECT LASTNAME, EDLEVEL FROM EMPLOYEEWHERE EDLEVEL >= 19
Retrieving Rows by Numerical Comparison
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-19
Student Notebook
Figure 2-17. Comparison Operators CF124.1
Notes:
The symbols between the column named SALARY and the value 20000 are interpreted to mean the words to the right of the predicate.
Within many query editors, two hyphens side by side (no space between them) represents a comment marker. Text to the right of the comment marker is ignored.
© Copyright IBM Corporation 2007
SELECT *FROM EMPLOYEEWHERE SALARY = 20000 -- equal to
OR SALARY <> 20000 -- not equal toOR SALARY > 20000 -- greater thanOR SALARY >= 20000 -- greater than or equal toOR SALARY < 20000 -- less thanOR SALARY <= 20000 -- less than or equal to
Comparison Operators
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-18. AND and OR - Principle CF124.1
Notes:
When predicates are combined via AND, for a row to qualify, both predicates must be true. For predicates combined via OR, rows qualify if at least one predicate is true.
© Copyright IBM Corporation 2007
Yellow OR Oval
Y
Y Y
R
R
Y Y Y
Y
Y Y
R
RY
R
Y Y
YYellow AND Oval
AND and OR - Principle
R
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-21
Student Notebook
Figure 2-19. Multiple Conditions - AND CF124.1
Notes:
When AND is used between predicates, for a row to qualify, both conditions must be met.
In the above example, only rows for analysts with an education level of 16 are displayed.
© Copyright IBM Corporation 2007
List employee number, job, andeducation level for analysts with
an education level of 16
SELECT EMPNO, JOB, EDLEVELFROM EMPLOYEEWHERE JOB = 'ANALYST'
AND EDLEVEL = 16
EMPNO JOB EDLEVEL000130 ANALYST 16
Multiple Conditions - AND
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-22 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-20. Multiple Conditions - OR CF124.1
Notes:
Rows qualify for further processing if at least one condition is met.
In the above example, employees who are analysts, and employees with an education level of 20 (independent of their job) are displayed.
© Copyright IBM Corporation 2007
List the columns below forall analysts and all employees
with an education level of 20. Sortthe list by job and employee number.
SELECT EMPNO, JOB, EDLEVELFROM EMPLOYEEWHERE JOB = 'ANALYST'
OR EDLEVEL = 20ORDER BY JOB, EMPNO
EMPNO JOB EDLEVEL000130 ANALYST 16000140 ANALYST 18000030 MANAGER 20
Multiple Conditions - OR
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-23
Student Notebook
Figure 2-21. Multiple Conditions - AND/OR CF124.1
Notes:
If you combine multiple conditions by AND and OR, AND takes precedence over OR.
© Copyright IBM Corporation 2007
SELECT EMPNO, JOB, EDLEVELFROM EMPLOYEEWHERE JOB = 'ANALYST'
AND EDLEVEL = 16OR EDLEVEL = 18
ORDER BY JOB, EMPNO
List the columns below for allanalysts with an ed-level of 16. Includeemployees with an ed-level of 18. Sortthe list by job and employee number.
EMPNO JOB EDLEVEL000130 ANALYST 16000140 ANALYST 18000220 DESIGNER 18000020 MANAGER 18000010 PRES 18
Multiple Conditions - AND/OR
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-24 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-22. Multiple Conditions - Parentheses CF124.1
Notes:
Search conditions within parentheses are evaluated first. If the order of evaluation is not determined by parentheses, AND is applied before OR. The order in which operators at the same precedence level are evaluated is undefined to allow for the optimization of search conditions.
© Copyright IBM Corporation 2007
List the columns belowfor all analysts with an
ed-level of 16 or 18.
SELECT EMPNO, JOB, EDLEVELFROM EMPLOYEEWHERE JOB = 'ANALYST'
AND (EDLEVEL = 16OR EDLEVEL = 18)
EMPNO JOB EDLEVEL000130 ANALYST 16000140 ANALYST 18
Multiple Conditions - Parentheses
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-25
Student Notebook
Figure 2-23. SELECT with IN CF124.1
Notes:
The IN predicate compares a value with a set of values.
The values may be numeric, or alphanumeric, a date, or a time.
An alphanumeric value, a date, or a time must be enclosed within single quotes.
Example:
SELECT * FROM DEPARTMENT WHERE DEPTNO IN ('B01', 'C01', 'D01')
© Copyright IBM Corporation 2007
SELECT LASTNAME, EDLEVELFROM EMPLOYEEWHERE EDLEVEL IN (14,19,20)ORDER BY EDLEVEL, LASTNAME
List last name and ed-level forall employees with an ed-level of
14, 19 or 20. Sort the listingby ed-level and last name.
LASTNAME EDLEVELJEFFERSON 14LEE 14O'CONNELL 14SMITH 14SPENSER 14LUCCHESSI 19KWAN 20
SELECT with IN
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-26 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-24. SELECT with BETWEEN CF124.1
Notes:
The BETWEEN predicate determines if a given value lies between and including two values specified in ascending order (low value listed first, the higher or equal value must be listed after the AND).
The clause
WHERE EDLEVEL BETWEEN 12 AND 15
is equivalent to
WHERE EDLEVEL >= 12 AND EDLEVEL <= 15
Alphanumeric values could also be used within the between predicate. Example:
WHERE WORKDEPT BETWEEN 'A00' AND 'D00'
© Copyright IBM Corporation 2007
SELECT EMPNO, EDLEVELFROM EMPLOYEEWHERE EDLEVEL BETWEEN 12 AND 15 ORDER BY EDLEVEL
List employee number and ed-levelfor all employees with an ed-level
from 12 through 15. Sort by ed-level.
EMPNO EDLEVEL000290 12000310 12000100 14000120 14000230 14000300 14000330 14000250 15000270 15
SELECT with BETWEEN
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-27
Student Notebook
Figure 2-25. Retrieving Rows - Null Comparison CF124.1
Notes:
The NULL predicate tests for null values.
The result of "IS NULL" cannot be unknown. If the value of the expression is null, the result is true. If the value is not null, the result is false. If "IS NOT NULL" is specified, the result is reversed.
© Copyright IBM Corporation 2007
List number and name of all departments whose manager
is unknown
SELECT DEPTNO, DEPTNAME, MGRNOFROM DEPARTMENTWHERE MGRNO IS NULL
DEPTNO DEPTNAME MGRNOD01 DEVELOPMENT CENTER -
Retrieving Rows - Null Comparison
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-28 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-26. Partial String Search - LIKE CF124.1
Notes:
• The LIKE predicate searches for character strings that have a certain pattern.
• In the pattern the percent sign ('%') serves as place holder for a string of zero or more arbitrary characters.
The above SELECT searches for names beginning with the letter 'G'.
© Copyright IBM Corporation 2007
List the last name for allemployees whose last name
starts with the letter G
SELECT LASTNAMEFROM EMPLOYEEWHERE LASTNAME LIKE 'G%'
LASTNAMEGEYERGOUNOT
Partial String Search - LIKE
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-29
Student Notebook
Figure 2-27. Partial String Search - Examples with '%' CF124.1
Notes:
The first example displays all names ending with 'SON'. and will only work as illustrated if the data type of the LASTNAME column is VARCHAR.
The second example displays all names containing 'M' and 'N' in that sequence. Names beginning with 'M' and ending with 'N' would also be displayed.
© Copyright IBM Corporation 2007
SELECT LASTNAMEFROM EMPLOYEEWHERE LASTNAME LIKE '%SON'
SELECT LASTNAMEFROM EMPLOYEEWHERE LASTNAME LIKE '%M%N%'
LASTNAMETHOMPSONHENDERSONADAMSONJEFFERSONJOHNSON
LASTNAMETHOMPSONADAMSONMARINO
Partial String Search - Examples with '%'
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-30 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-28. Partial String Search - Example with '_' CF124.1
Notes:
The underscore symbol ('_') in the pattern causes the character in the corresponding position of the appropriate column to not be compared. Each underscore in the pattern represents a single character whose value is not compared.
The above SELECT returns names which start with any arbitrary character if the second character is the letter 'C'.
To search for last names whose third character is a 'C', the pattern would have to start with two underscores.
© Copyright IBM Corporation 2007
I need a listing of all employee last names whose
second character is the letter 'C'
SELECT LASTNAMEFROM EMPLOYEEWHERE LASTNAME LIKE '_C%'
LASTNAMESCOUTTENSCHNEIDER
Partial String Search - Example with '_'
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-31
Student Notebook
Figure 2-29. Negation CF124.1
Notes:
If there are composite conditions, NOT is applied before AND and AND is applied before OR.
All predicates can be negated by preceding the predicate with the word NOT.
WHERE NOT SALARY > 2000
© Copyright IBM Corporation 2007
I need a listing of all departmentsexcept those with a department
number starting with 'D'
SELECT DEPTNO, DEPTNAMEFROM DEPARTMENTWHERE DEPTNO NOT LIKE 'D%'
DEPTNO DEPTNAMEA00 SPIFFY COMPUTER SERVICE DIV.B01 PLANNINGC01 INFORMATION CENTERE01 SUPPORT SERVICESE11 OPERATIONSE21 SOFTWARE SUPPORT
Negation
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-32 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 2-30. Checkpoint CF124.1
Notes:
Please write down your answers below:
1.
2.
3.
4.
5.
6.
© Copyright IBM Corporation 2007
Checkpoint
1. True or False? The sequence in which clauses are coded in a SELECT statement is arbitrary.
2. BETWEEN causes the rows of the result table to be a. Sorted in ascending order b. Sorted in descending order c. Not sorted at all
3. Which clauses in a SELECT statement are required? 4. Within a WHERE clause, character data, dates, times and
timestamps must always be enclosed within what?5. When doing patterned character string searches, what gives
the underscore and the percent symbol their masking abilities?
6. True or False? WHERE clause predicates must be separated from each other by commas.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-33
Student Notebook
Figure 2-31. Unit Summary CF124.1
Notes:
© Copyright IBM Corporation 2007
Unit Summary
Having completed 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
2-34 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Unit 3. Retrieving Data from Multiple TablesWhat This Unit Is About
How to retrieve columns from more than one table or view.
What You Should Be Able to Do
After completing this unit, you should be able to:
• Retrieve data from more than one table or view.
• Specify JOIN predicates.
• Use correlation names in queries
How You Will Check Your Progress
Accountability:
• Checkpoint • Machine labs
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-1
Student Notebook
Figure 3-1. Unit Objectives CF124.1
Notes:
© Copyright IBM Corporation 2007
Unit Objectives
After completing this unit, you should be able to:
Retrieve data from more than one table or view
Specify JOIN predicates
Use correlation names in queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
3.1 Accessing Data Stored in Multiple TablesCourse materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-3
Student Notebook
Figure 3-2. Retrieving Data from Multiple Tables (Principle) CF124.1
Notes:
For each department number in table PROJECT, one row exists in table DEPARTMENT.
By looking at the data within the two tables we can see how a row in one table is related to a row in the other table. The rows are related by the values in the DEPTNO columns.
© Copyright IBM Corporation 2007
Retrieving Data from Multiple Tables (Principle)PROJECT
DEPTNAME
PROJNAME DEPTNO
. . .
. . .
DEPARTMENT
PROJNO
DEPTNO
A00C01D01D21
SPIFFY COMPUTER SERVICE DIV.INFORMATION CENTERDEVELOPMENT CENTERADMINISTRATION SYSTEMS
AD3100AD3110AD3111AD3112
D01D21D21D21
ADMIN SERVICESGENERAL ADMIN SYSTEMSPAYROLL PROGRAMMINGPERSONNEL PROGRAMMING
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 3-3. Retrieving Data from Multiple Tables (JOIN) CF124.1
Notes:
You can use the SELECT statement to produce reports that contain information from two or more tables. This is commonly referred as a JOIN.
To join two tables, specify the columns you want to be displayed in the SELECT clause, the table names in the FROM clause, and the join predicate in the WHERE clause.
Because DEPTNO is a column of tables DEPARTMENT and PROJECT, the column name must be qualified. Furthermore, it is a good practice that all column names in a SELECT referencing more than one table be fully qualified to avoid potential error.
When the join predicate is omitted each qualified row from the first table is combined with all qualifying rows in the second table. This is called a Cartesian Product and is usually an unwanted result.
© Copyright IBM Corporation 2007
SELECT PROJNO, PROJNAME, PROJECT.DEPTNO, DEPTNAMEFROM PROJECT, DEPARTMENTWHERE PROJECT.DEPTNO=DEPARTMENT.DEPTNO -- JOIN PREDICATEORDER BY PROJNO
PROJNO PROJNAME DEPTNO DEPTNAMEAD3100 ADMIN SERVICES D01 DEVELOPMENT CENTERAD3110 GENERAL ADMIN SYSTEMS D21 ADMINISTRATION SYSTEMSAD3111 PAYROLL PROGRAMMING D21 ADMINISTRATION SYSTEMSAD3112 PERSONNEL PROGRAMMING D21 ADMINISTRATION SYSTEMSAD3113 ACCOUNT PROGRAMMING D21 ADMINISTRATION SYSTEMS
... ... ... ...
Avoid a Cartesian Product!
Retrieving Data from Multiple Tables (JOIN)
For every project, list the project number, project name, and the number and name of the department responsible for the project.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-5
Student Notebook
Figure 3-4. Correlation Names CF124.1
Notes:
Correlation names are defined in the FROM clause of any query. They can be used as short-hand synonyms for the table names in that query.
Here we take advantage of the fact that we specify short correlation names and we follow the recommendation to qualify all column names in our query.
© Copyright IBM Corporation 2007
Correlation Names
SELECT P.PROJNO, P.PROJNAME, P.DEPTNO, D.DEPTNAME
FROM PROJECT P, DEPARTMENT D
WHERE P.DEPTNO = D.DEPTNO
ORDER BY P.PROJNO
PROJNO PROJNAME DEPTNO DEPTNAMEAD3100 ADMIN SERVICES D01 DEVELOPMENT CENTERAD3110 GENERAL ADMIN SYSTEMS D21 ADMINISTRATION SYSTEMSAD3111 PAYROLL PROGRAMMING D21 ADMINISTRATION SYSTEMSAD3112 PERSONNEL PROGRAMMING D21 ADMINISTRATION SYSTEMSAD3113 ACCOUNT PROGRAMMING D21 ADMINISTRATION SYSTEMS
... ... ... ...
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 3-5. JOIN Syntax 1 CF124.1
Notes:
The tables EMPLOYEE and DEPARTMENT have common values for columns WORKDEPT and DEPTNO. WORKDEPT contains the department number to which the employee belongs. The join predicate tells DB2 UDB to combine the row for an employee with the row for the department to which the employee belongs.
In most cases, when joining two tables we provide at least one JOIN condition. For three tables, we provide at least two JOIN conditions. The general rule of thumb is:
The number of tables minus one (n-1) is USUALLY the LEAST number of join predicates needed for the query, ensuring that there are no un-linked tables.
Further conditions are allowed and may be added by means of AND or OR.
© Copyright IBM Corporation 2007
SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAMEFROM EMPLOYEE, DEPARTMENTWHERE WORKDEPT = DEPTNO
AND LASTNAME = 'HAAS'
HAAS
WORKDEPT DEPTNAMELASTNAME
A00 SPIFFY COMPUTER SERVICE DIV.000010
EMPNO
JOIN Syntax 1
For employees with a last name of HAAS, display the employee number, last name, and the number and name of the department they are working in.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-7
Student Notebook
Figure 3-6. JOIN Syntax 2 (JOIN Keyword) CF124.1
Notes:
When the JOIN keyword is used in the FROM clause, the join predicates must be specified in an ON clause.
Row conditions (local predicates) must be written in a WHERE clause which must follow the ON clause.
© Copyright IBM Corporation 2007
HAAS A00 SPIFFY COMPUTER SERVICE DIV.000010
EMPNO
SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAMEFROM EMPLOYEE JOIN
DEPARTMENTON WORKDEPT = DEPTNOWHERE LASTNAME = 'HAAS'
LASTNAME WORKDEPT DEPTNAME
JOIN Syntax 2 (JOIN Keyword)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 3-7. Another JOIN Example (1 of 2) CF124.1
Notes:
The DEPARTMENT and EMPLOYEE tables can be joined another way: the MGRNO column in the DEPARTMENT table corresponds to the employee number (EMPNO in the EMPLOYEE table) of the manager of the department.
© Copyright IBM Corporation 2007
FIRSTNME LASTNAMEMIDINIT
DEPTNAME MGRNO . . .
EMPLOYEEEMPNO
DEPTNO
A00B01C01D01D11D21E01
000010000020000030- - - - - -000060000070000050
SPIFFY COMPUTER SERVICE DIV.PLANNINGINFORMATION CENTERDEVELOPMENT CENTERMANUFACTURING SYSTEMSADMINISTRATION SYSTEMSSUPPORT SERVICES
HAASTHOMPSONKWANGEYERSTERNPULASKIHENDERSONSPENSER
ILABFDWQ
CHRISTINEMICHAELSALLYJOHNIRVINGEVAEILEENTHEODORE
000010000020000030000050000060000070000090000100
. . .
. . .Display the department name, and the employee number and last
name of the manager, for department D21.
Another JOIN Example (1 of 2)
DEPARTMENT
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-9
Student Notebook
Figure 3-8. Another JOIN Example (2 of 2) CF124.1
Notes:
This shows the JOIN answering the question on the previous page. Note that we could also have used the second type of syntax:
SELECT DEPTNAME, MGRNO, LASTNAMEFROM DEPARTMENT JOIN EMPLOYEE
ON MGRNO = EMPNOWHERE DEPTNO = ‘D21'
© Copyright IBM Corporation 2007
SELECT DEPTNAME, MGRNO, LASTNAMEFROM DEPARTMENT, EMPLOYEEWHERE MGRNO = EMPNO
AND DEPTNO = ‘D21’
ADMINISTRATION SYSTEMS 000070 PULASKI
DEPTNAME MGRNO LASTNAME
Another JOIN Example (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 3-9. JOIN with Three Tables (1 of 2) CF124.1
Notes:
Here we want to find out the project number for projects belonging to department D21, as well as the department name, the employee number and last name of the department's manager. This requires joining together the PROJECT, DEPARTMENT and EMPLOYEE tables.
To find the name of the department that a project is assigned to, DB2 UDB can first read the PROJECT table to obtain the department number of the department.
Next, read the corresponding row of the DEPARTMENT table to obtain the department name and the employee number of the responsible manager.
Next, read the corresponding row of the EMPLOYEE table to obtain the manager's last name.
The DB2 UDB optimizer determines the sequence of the above steps.
© Copyright IBM Corporation 2007
FIRSTNME LASTNAMEMIDINIT
DEPTNAME MGRNO
PROJNAME DEPTNO
. . .DEPARTMENT
EMPLOYEEEMPNO
DEPTNO
PROJNO
AD3100AD3110AD3111AD3112AD3113IF1000
ADMIN SERVICESGENERAL AD SYSTEMSPAYROLL PROGRAMMINGPERSONNEL PROGRAMMINGACCOUNT. PROGRAMMINGQUERY SERVICES
D01D21D21D21D21C01
A00B01C01D01D11D21E01
000010000020000030- - - - - -000060000070000050
SPIFFY COMPUTER SERVICE DIV.PLANNINGINFORMATION CENTERDEVELOPMENT CENTERMANUFACTURING SYSTEMSADMINISTRATION SYSTEMSSUPPORT SERVICES
HAASTHOMPSONKWANGEYERSTERNPULASKIHENDERSONSPENSER
ILABFDWQ
CHRISTINEMICHAELSALLYJOHNIRVINGEVAEILEENTHEODORE
000010000020000030000050000060000070000090000100
PROJECT
. . .
. . .For department D21 list
PROJNO, DEPTNO, DEPTNAME, MGRNO, and
LASTNAME.
JOIN with Three Tables (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-11
Student Notebook
Figure 3-10. JOIN with Three Tables (2 of 2) CF124.1
Notes:
With three tables being joined together, and the join conditions being on one column, we need two join predicates (conditions)
If multiple tables are specified, but no JOIN predicate and no search condition is specified, the intermediate result table consists of all possible combinations of the rows of the specified tables (the Cartesian product); the number of rows in the result is the product of the number of rows of all specified tables.
© Copyright IBM Corporation 2007
DEPTNO DEPTNAME MGRNO LASTNAMEPROJNO
D21D21D21D21
ADMINISTRATION SYSTEMS ADMINISTRATION SYSTEMSADMINISTRATION SYSTEMSADMINISTRATION SYSTEMS
000070000070000070000070
PULASKIPULASKIPULASKIPULASKI
AD3110AD3111AD3112AD3113
SELECT PROJNO, P.DEPTNO, DEPTNAME, MGRNO, LASTNAMEFROM PROJECT P,
DEPARTMENT D,EMPLOYEE E
WHERE P.DEPTNO = D.DEPTNO -- join predicateAND D.MGRNO = E.EMPNO -- join predicateAND D.DEPTNO = 'D21‘ -- local predicate
ORDER BY PROJNO
JOIN with Three Tables (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 3-11. Joining a Table with Itself (1 of 3) CF124.1
Notes:
In the DEPARTMENT table, the column ADMRDEPT contains the number of the department (DEPTNO) that this department reports to; for example, department B01 reports to department A00 (the highest department, A00, reports to itself). ADMRDEPT and DEPTNO are columns in the same table; therefore, the DEPARTMENT table can be joined to itself.
© Copyright IBM Corporation 2007
Joining a Table with Itself (1 of 3)
DEPTNO DEPTNAME MGRNO ADMRDEPT
A00 SPIFFY COMPUTER SERVICE DIV. 000010 A00
B01 PLANNING 000020 A00
… … … …
DEPARTMENT
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-13
Student Notebook
Figure 3-12. Joining a Table with Itself (2 of 3) CF124.1
Notes:
To answer the question on the visual, we have to access the DEPARTMENT table twice: once for the department we are interested in (B01) and once for the department it reports to.
We will code this as if we had two copies of the table: one copy for the department we are interested in – we name this copy DEP in the visual, and one for the higher department (named SUP in the visual).
Of course, in reality, DB2 will NOT create a copy of the table; it will join each candidate row of the table with other rows of the same table.
© Copyright IBM Corporation 2007
DEPARTMENT (DEP)
. . .
. . .
Joining a Table with Itself (2 of 3)
DEPTNO DEPTNAME MGRNO ADMRDEPT
DEPTNO DEPTNAME MGRNO ADMRDEPT
DEPARTMENT (SUP)
A00 SPIFFY COMPUTING SERVICE DIV. 000010 A00
B01 PLANNING 000020 A00
A00 SPIFFY COMPUTING SERVICE DIV. 000010 A00
B01 PLANNING 000020 A00
Display the name of department B01 and the name of the department it reports to
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 3-13. Joining a Table with Itself (3 of 3) CF124.1
Notes:
Table qualifiers (correlation names) are required because a table is referenced twice within the FROM clause of the query.
© Copyright IBM Corporation 2007
SELECT DEP.DEPTNAME, SUP. DEPTNAMEFROM DEPARTMENT DEP, DEPARTMENT SUPWHERE DEP.ADMRDEPT = SUP.DEPTNO
AND DEP.DEPTNO = ‘B01’
DEPTNAME DEPTNAME
PLANNING SPIFFY COMPUTER SERVICE DIV.
Joining a Table with Itself (3 of 3)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-15
Student Notebook
Figure 3-14. Joining a Table with Itself – Other Example (1 of 2) CF124.1
Notes:
To get the required data, the EMPLOYEE table must be accessed twice.
Using the EMPLOYEE table, for each employee we read his/her department number. Then, from the department table we find his/her manager's employee number. Using the manager's employee number, we access the EMPLOYEE table again to retrieve the manager's date of birth.
Then, the dates of birth are compared and for each employee that is older than his/her manager information is put into the result table.
© Copyright IBM Corporation 2007
DEPTNAME ADMRDEPT
LASTNAME
LASTNAME
WORKDEPT
WORKDEPT
BIRTHDATE
BIRTHDATE
.
.
. . .
2. Obtain department number from DEPARTMENT (D)
3. Retrieve row for manager from EMPLOYEE (M)
DEPTNO
EMPNO
EMPNO
000100
000330
SPENSER
LEE
E21
E21
1956-12-18
1941-07-18
E21 E21
.
.000100
.
.SOFTWARE SUPPORT
.
.
000100
000330
SPENSER
LEE
E21
E21
1956-12-18
1941-07-18
MGRNO
. . . . . .
. . . . . . . . .
1. Retrieve employee's row from EMPLOYEE (E)Which
employeesare olderthan theirmanager?
Joining a Table with Itself – Another Example (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 3-15. Joining a Table with Itself – Other Example (2 of 2) CF124.1
Notes:
Once again, table qualifiers (correlation names) are required because a table is referenced twice within the FROM clause of the query.
© Copyright IBM Corporation 2007
EMPNO LASTNAME BIRTHDATE EMPNO
LUCCHESIQUINTANABROWNJEFFERSONSMITHJOHNSONSCHNEIDERSMITHSETRIGHTMEHTALEEGOUNOT
Which employees are older thantheir manager?
SELECT E.EMPNO, E.LASTNAME,E.BIRTHDATE, M.BIRTHDATE, M.EMPNO
FROM EMPLOYEE E,DEPARTMENT D,EMPLOYEE M
WHERE E.WORKDEPT = D.DEPTNOAND D.MGRNO = M.EMPNOAND E.BIRTHDATE < M.BIRTHDATE
000110000130000200000230000250000260000280000300000310000320000330000340
1929-11-051925-09-151941-05-291935-05-301939-11-121936-10-051936-03-281936-10-271931-04-211932-08-111941-07-181926-05-17
000010000030000060000070000070000070000090000090000090000100000100000100
1933-08-141941-05-111945-07-071953-05-261953-05-261953-05-261941-05-151941-05-151941-05-151956-12-181956-12-181956-12-18
BIRTHDATE
Joining a Table with Itself – Another Example (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-17
Student Notebook
Figure 3-16. Checkpoint CF124.1
Notes:
Please write down your answers below:
1.
2.
3.
© Copyright IBM Corporation 2007
Checkpoint
1. True or False? If you reference multiple tables in the FROM clause, you should use JOIN conditions to obtain the desired result.
2. Which of the following situations applies if you forget the JOIN conditions in a SELECT statement using multiple tables:
a. You receive an error and the statement is not executed. b. The statement is executed and the result is the Cartesian
product of the tables.
3. Why do we use correlation names in a SELECT?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 3-17. Unit Summary CF124.1
Notes:
© Copyright IBM Corporation 2007
Unit Summary
Having completed this unit, you should be able to:
Retrieve data from more than one table or view
Specify JOIN predicates
Use correlation names in queries
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-19
Student Notebook
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
3-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Unit 4. Scalar Functions and ArithmeticWhat This Unit Is About
Scalar functions can be used to manipulate column or expression values. This unit will discuss the format and syntax of basic scalar functions.
Arithmetic allows us to work with or present calculated values, such as salary + comm.
Date columns can also be used in arithmetic calculations.
What You Should Be Able to Do
After completing this unit, you should be able to:
• Use arithmetic in the SELECT and WHERE clauses
• Specify basic scalar functions such as COALESCE/VALUE, DECIMAL, SUBSTR
• Use date and time scalar functions
• Use the CONCAT operator
How You Will Check Your Progress
Accountability:
• Checkpoint • Machine labs
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-1
Student Notebook
Figure 4-1. Unit Objectives CF124.1
Notes:
© Copyright IBM Corporation 2007
Unit Objectives
After completing this unit, you should be able to:
Use arithmetic in the SELECT and WHERE clauses
Use basic scalar functions such as COALESCE/VALUE, DECIMAL, SUBSTR
Use date and time scalar functions
Use the CONCAT operator
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
4.1 Scalar Functions and ArithmeticCourse materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-3
Student Notebook
Figure 4-2. Selecting Calculated Values CF124.1
Notes:
• You can use the following arithmetic operators and parentheses() to calculate values:
addition + subtraction - multiplication * division /
• Precedence of operations:
Expressions within parentheses are evaluated first. When the order of elevation is not specified by parentheses, multiplication and division are applied before addition and subtraction. Operators at the same precedence level are applied from left to right.
• In the result table, derived columns, such as SALARY+COMM, do not have meaningful column names associated with them.
© Copyright IBM Corporation 2007
18270.0019180.0017250.0015340.0017750.0015900.0019950.00
1462.001534.001380.001227.001420.001272.001596.00
19732.0020714.0018630.0016567.0019170.0017172.0021546.00
SALARY COMMEMPNO000210000250000260000290000300000310000320
I need a list containingEMPNO, SALARY, COMM,
and SALARY + COMMfor employees whose salary
is less than $20000,ordered by employee number
SELECT EMPNO, SALARY, COMM,SALARY + COMM
FROM EMPLOYEEWHERE SALARY < 20000ORDER BY EMPNO
Selecting Calculated Values
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-3. Naming Result Columns CF124.1
Notes:
Derived columns ordinarily have no column names or have dummy column names specified by the SQL tool used (SPUFI, QMF, Command Editor, and so on). You can use the AS clause to rename the column headings for these derived column results.
Because the SELECT clause is executed after the WHERE clause the new column name may only be used in the ORDER BY clause.
© Copyright IBM Corporation 2007
SALARY COMM INCOMEEMPNO
18270.0019180.0017250.0015340.0017750.0015900.0019950.00
1462.001534.001380.001227.001420.001272.001596.00
19732.0020714.0018630.0016567.0019170.0017172.0021546.00
000210000250000260000290000300000310000320
SELECT EMPNO, SALARY, COMM, SALARY + COMM AS INCOMEFROM EMPLOYEEWHERE SALARY < 20000ORDER BY EMPNO
Naming Result Columns
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-5
Student Notebook
Figure 4-4. Substitution of NULL Values CF124.1
Notes:
The COALESCE scalar function is equivalent to the VALUE scalar function.
• COALESCE allows multiple parameters:
COALESCE(expression_1, expression_2, expression_n, 'constant')
• The COALESCE function takes a variable number of parameters and returns the value of the first parameter that is not null. The result is null if the values of all parameters are null.
• In the example, the value "UNKNOWN" is returned if a department does not have a manager, that is, MGRNO is NULL.
• Every expression must be of a compatible data type (if the first expression is numeric, every expression must be numeric, and so on).
© Copyright IBM Corporation 2007
DEPTNAME MANAGERADMINISTRATION SYSTEMS 000070DEVELOPMENT CENTER UNKNOWN INFORMATION CENTER 000030MANUFACTURING SYSTEMS 000060OPERATIONS 000090PLANNING 000020SOFTWARE SUPPORT 000100SPIFFY COMPUTER SERVICE DIV. 000010SUPPORT SERVICES 000050
I need a listing containingdepartment names and the
employee number of its manager,sorted by department name.
SELECT DEPTNAME, COALESCE (MGRNO, 'UNKNOWN')
AS MANAGERFROM DEPARTMENTORDER BY DEPTNAME
Substitution of NULL Values
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-5. Arithmetic with NULL Values CF124.1
Notes:
If one of the columns used in the expression contains a NULL value, the result of the expression is unknown.
In the left example, when commission is NULL, SALARY + COMM is null. In the right example, for SALARY + COMM, nulls are replaced with zeros.
© Copyright IBM Corporation 2007
SELECT EMPNO, SALARY, COMM,SALARY + COALESCE (COMM, 0)AS "TOTAL INCOME"
FROM EMPLOYEE
I need a list of the total income(salary and commission).
In the total, assume unknowncommissions to be zero.
EMPNO SALARY COMM TOTAL INCOME
000210 18270.00 1462.00 19732.00
000260 17250.00 - -
000290 15340.00 1227.00 16567.00
000300 17750.00 - -
... ... ... ...
SELECT EMPNO, SALARY, COMM,SALARY + COMM AS "TOTAL INCOME"
FROM EMPLOYEE
EMPNO SALARY COMM TOTAL INCOME
000210 18270.00 1462.00 19732.00
000260 17250.00 - 17250.00
000290 15340.00 1227.00 16567.00
000300 17750.00 - 17750.00
... ... ... ...
Arithmetic with NULL Values
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-7
Student Notebook
Figure 4-6. Calculated Values CF124.1
Notes:
The above example shows multiplication using a constant. You can also use calculations with multiple columns (for example, COL1 * COL2).
© Copyright IBM Corporation 2007
SALARYEMPNO18270.0019180.0017250.0015340.0017750.0015900.0019950.00
18955.12500019899.25000017896.87500015915.25000018415.62500016496.25000020698.125000
000210000250000260000290000300000310000320
SELECTFROMWHEREORDER BY
EMPNO, SALARY, SALARY * 1.0375EMPLOYEESALARY < 20000EMPNO
Calculated Values
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-7. Decimal Representation of a Value CF124.1
Notes:
The DECIMAL scalar function returns a decimal representation of a numeric value or a decimal representation of a numeric looking character value. In the example above, the DECIMAL scalar function is used to ensure that the result column has 2 decimal positions.
The result is truncated after the second decimal position. No rounding occurs with the DECIMAL scalar function.
© Copyright IBM Corporation 2007
SALARYEMPNO18270.0019180.0017250.0015340.0017750.0015900.0019950.00
18955.1219899.2517896.8715915.2518415.6216496.2520698.12
000210000250000260000290000300000310000320
SELECT
FROMWHEREORDER BY
EMPNO, SALARY,DECIMAL (SALARY * 1.0375, 8, 2) EMPLOYEESALARY < 20000EMPNO
Decimal Representation of a Value
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-9
Student Notebook
Figure 4-8. Decimal Values - Truncation and Rounding CF124.1
Notes:
If you need a rounded result, add 5 to the first decimal position to be truncated and apply the DECIMAL function to this expression.
Most environments support a ROUND scalar function as another method of rounding. See the SQL Reference manual for your environment for additional information.
© Copyright IBM Corporation 2007
SALARYEMPNO18270.0019180.0017250.0015340.0017750.0015900.0019950.00
18955.1319899.2517896.8815915.2518415.6316496.2520698.13
000210000250000260000290000300000310000320
SELECT
FROMWHEREORDER BY
EMPNO, SALARY,DECIMAL (SALARY * 1.0375 + 0.005, 8, 2) EMPLOYEESALARY < 20000EMPNO
Decimal Values - Truncation and Rounding
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-9. Condition on Calculated Values CF124.1
Notes:
Arithmetic expressions can be used in the SELECT list and in the WHERE clause.
The above SELECT returns rows for employees with a commission higher than 8 percent of their salary.
© Copyright IBM Corporation 2007
SELECTFROMWHEREORDER BY
EMPNO, COMM, SALARY, (COMM/SALARY) * 100EMPLOYEE(COMM/SALARY) * 100 > 8EMPNO
SALARYEMPNO COMM
2274.001462.002301.002030.00
28420.0018270.0028760.0025370.00
000140000210000240000330
8.0014008.0021008.0006008.001500
Condition on Calculated Values
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-11
Student Notebook
Figure 4-10. Date and Time CF124.1
Notes:
The visual shows the internal and external formats for DATE/TIME data.
A timestamp is a seven-part value (year, month, day, hour, minute, second, and microsecond) that represents a date and a time including microseconds.
© Copyright IBM Corporation 2007
Date Format
yyyy-mm-dd
mm/dd/yyyy
dd.mm.yyyy
yyyy-mm-dd
???
Length
8 bytes
8 bytes
8 bytes
8 bytes
???
Length
10 bytes
10 bytes
10 bytes
10 bytes
???
Format
ISO
USA
EUR
JIS
LOCAL
TIMESTAMP DATA:
Time Format
hh.mm.ss
hh:mm AM
hh:mm PM
hh.mm.ss
hh:mm:ss
???
yyyy-mm-dd-hh.mm.ss.nnnnnn 26 bytes
DataTypeDATETIMETIMESTAMP
Internal Formatyyyymmddhhmmssyyyymmddhhmmssnnnnnn
Internal Length4 bytes3 bytes10 bytes
Date and Time
DATE, TIME, TIMESTAMP data internally stored as packed decimal, without sign
Program uses an external format, that is,
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-11. CHAR Function CF124.1
Notes:
The visual shows the CHAR function to convert a DATE or TIME to a chosen external character format.
© Copyright IBM Corporation 2007
CHAR controls the external format of date / time data
SELECT CHAR (TIMECOL, USA), CHAR (TIMECOL, ISO)...
03:30 PM 15.30.00
CHAR Function
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-13
Student Notebook
Figure 4-12. Comparison with Dates CF124.1
Notes:
Columns defined with a DATE or TIME data type can be compared with other DATE or TIME columns or with a valid date or time.
Date or time constants (character string representations of a valid date or time) must be placed in single quotes. All legal formats can be used.
In the shown example, all employees are selected that were born '1955-01-01' or later.
© Copyright IBM Corporation 2007
SELECTFROMWHEREORDER BY
EMPNO, LASTNAME, BIRTHDATEEMPLOYEEBIRTHDATE >= '1955-01-01'BIRTHDATE
BIRTHDATEEMPNO LASTNAME
000160000100
PIANKASPENCER
1955-04-121956-12-18
Comparison with Dates
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-13. DATE / TIME Arithmetic CF124.1
Notes:
A date duration represents the period between two dates. The result is presented in format yyyymmdd.
A time duration represents the period between two times. The result is presented in format hhmmss.
A timestamp duration represents the period between two timestamps. The result is presented in format yyyymmddhhmmss.nnnnnn (the nnnnnn portion represents microseconds).
© Copyright IBM Corporation 2007
DATE / TIME Arithmetic
Subtraction onlytime - time time duration (decimal (6,0))date – date date duration (decimal (8,0))timestamp – timestamp timestamp duration
(decimal (20,6))
Labeled durations: YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, MICROSECONDS
time + labeled duration timedate + labeled duration datetimestamp + duration timestamp
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-15
Student Notebook
Figure 4-14. Subtraction of Dates CF124.1
Notes:
In above example, the values of two date columns are subtracted. The result of the subtraction is presented in the format yyyymmdd. Leading zeros are not displayed.
For example, in the first result line, the value 790727 means 79 years, 7 months, and 27 days. (The results are for CURRENT_DATE of 2005-05-12).
In the WHERE clause, the calculated durations are compared with 720000, that is, 72 years, 00 months, and 00 days (72 years old or more).
CURRENT_DATE, CURRENT_TIME, and CURRENT_TIMESTAMP (or CURRENT DATE, CURRENT TIME and CURRENT TIMESTAMP) are special registers provided by DB2 UDB, containing the system date, system time, or system timestamp respectively. The format with the underscore is more standard, but older versions of DB2 on some platforms do not support this format.
© Copyright IBM Corporation 2007
QUINTANAGEYERGOUNOTLUCCHESSISETRIGHTMEHTA
790727.790727.781126.750607.740021.720901.
LASTNAME DIFFEREMPNO
000130000050000340000110000310000320
I need a listing containing the ages of all employees 72 years old or
more, sorted by age in descending sequence.
SELECT EMPNO, LASTNAME, CURRENT_DATE -BIRTHDATE AS DIFFER
FROM EMPLOYEEWHERE CURRENT_DATE - BIRTHDATE >= 720000ORDER BY DIFFER DESC
Subtraction of Dates
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-15. Date / Time Scalar Functions CF124.1
Notes:
The visual shows some scalar functions for date and time values.
© Copyright IBM Corporation 2007
Date / Time Scalar Functions
DAY, MONTH, YEAR, HOUR, MINUTE, SECOND, MICROSECOND, DATE, TIME
Extract portions of a date, time, timestamp, or duration
DAYS - Converts a date to the number of days since 12/31/0000
DAYS(date_1) – DAYS(date_2) gives the number of days between date_1 and date_2
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-17
Student Notebook
Figure 4-16. Date Scalar Functions CF124.1
Notes:
In the above example, year, month, and day are displayed separately using appropriate scalar functions.
The resulting columns normally do not have column headings. The AS clause is used to name the columns.
© Copyright IBM Corporation 2007
JOHNDOLORESJASONVINCENZOMAUDERAMLAL
790727.790727.781126.750607.740021.720901.
797978757472
2727267
211
DAYS
GEYERQUINTANAGOUNOTLUCCHESSISETRIGHTMEHTA
LASTNAME FIRSTNME AGE YEARS
77
11609
MONTHS
LASTNAME, FIRSTNME,CURRENT_DATE - BIRTHDATE AS AGE,YEAR(CURRENT_DATE - BIRTHDATE) AS YEARS,MONTH(CURRENT_DATE - BIRTHDATE) AS MONTHS,DAY(CURRENT_DATE - BIRTHDATE) AS DAYSEMPLOYEEYEAR(CURRENT_DATE - BIRTHDATE) >= 72AGE DESC, LASTNAME
SELECT
FROMWHEREORDER BY
Date Scalar Functions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-17. DATE Arithmetic (1 of 2) CF124.1
Notes:
The example shows the duration of projects in days. To obtain a positive result, the project start date (PRSTDATE) must be subtracted from the project end date (PRENDATE) because the end date is higher.
© Copyright IBM Corporation 2007
PROJNO,DAYS(PRENDATE) - DAYS(PRSTDATE) AS DAYSPROJECTDAYS(PRENDATE) - DAYS(PRSTDATE) <= 300DAYS
SELECT
FROMWHEREORDER BY
DAYSPROJNO
PL2100MA2113
257289
DATE Arithmetic (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-19
Student Notebook
Figure 4-18. DATE Arithmetic (2 of 2) CF124.1
Notes:
The example shows the use of labeled durations and adds 2 months and 15 days to a date.
© Copyright IBM Corporation 2007
SELECT
FROMWHEREORDER BY
PROJNO, PRENDATE,PRENDATE + 2 MONTHS + 15 DAYSPROJECTPROJNO = 'AD3100'PROJNO
PRENDATEPROJNO
AD3100 1983-02-01 1983-04-16
DATE Arithmetic (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-19. Substring of Strings CF124.1
Notes:
If only a part of a character string is to be selected, use the SUBSTR scalar function to extract the part.
Assume that COURSINF is defined CHAR(20) and that both course code and course title are stored in that column, separated by a blank. To only display the course title, you can use the SUBSTR scalar function.
SUBSTR(COURSINF,6,15) returns a substring of length 15 beginning at position 6, that is, the course title in the above example.
© Copyright IBM Corporation 2007
COURSINF
CC
FF
11
23
SS
LL
BA
AD D
SV
IA
CN
SC E
S Q L B A S I C SS Q L A D DV A N C E
SELECT SUBSTR(COURSINF, 6, 15) ...
Substring of Strings (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-21
Student Notebook
Figure 4-20. Substring of Strings (Cont) CF124.1
Notes:
The first two characters of the project number represents the project class. To display only the project class, the SUBSTR function is used.
SUBSTR(PROJNO,1,2) extracts the first two characters. The function can be interpreted to read: Within the PROJNO column, start with the first character and return two characters.
© Copyright IBM Corporation 2007
SELECT SUBSTR(PROJNO,1, 2) AS PROJ_CLASS,PROJNAME
FROM PROJECTWHERE PROJNO LIKE 'IF%'
PROJNAMEPROJ_CLASSIFIF
QUERY SERVICESUSER EDUCATION
Substring of Strings (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-22 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-21. Concatenation of Values CF124.1
Notes:
The above example displays last name and first name as a single column, separated by a comma and a space.
CONCAT combines character strings into a single column. The word CONCAT works in all environments.
Double bars (||) can be used to represent concatenation, but you must make sure that the vertical bar symbol on your keyboard will actually result in a vertical bar on the host.
Example:
SELECT LASTNAME || ',' || FIRSTNME FROM EMPLOYEE
Check your environment's SQL documentation to see what additional concatenation symbols are supported.
© Copyright IBM Corporation 2007
NAMEHAAS, CHRISTINELUCCHESSI, VINCENZOO'CONNELL, SEAN
SELECT
FROMWHEREORDER BY
LASTNAME CONCAT ', 'CONCAT FIRSTNME AS NAMEEMPLOYEEWORKDEPT = 'A00'NAME
Concatenation of Values
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-23
Student Notebook
Figure 4-22. Checkpoint CF124.1
Notes:
Please write down your answers below:
1.
2.
3.
© Copyright IBM Corporation 2007
Checkpoint
1. True or False? If you use the DECIMAL scalar function to have two decimal positions instead of six, the result will be rounded.
2. If you subtract two dates, the format of the result will be: a. DD.MM.YYYYb. YYYY-MM-DDc. YYYYMMDD
3. Name several scalar functions.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-24 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 4-23. Unit Summary CF124.1
Notes:
© Copyright IBM Corporation 2007
Unit Summary
Having completed this unit, you should be able to:
Use arithmetic in the SELECT and WHERE clauses
Use basic scalar functions such as COALESCE/VALUE, DECIMAL, SUBSTR
Use date and time scalar functions
Use the CONCAT operator
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-25
Student Notebook
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4-26 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Unit 5. Column Functions and GroupingWhat This Unit Is About
This unit introduces column functions which can be used to obtain results derived from a set of one or more rows. In addition, the syntax for selecting group results will be taught.
What You Should Be Able to Do
After completing this unit, you should be able to:
• Describe the difference between scalar and column functions • List the more common DB2 UDB column functions. • Group rows into sets based on one or more columns.
How You Will Check Your Progress
• Checkpoint questions • Machine labs
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-1
Student Notebook
Figure 5-1. Unit Objectives CF124.1
Notes:
© Copyright IBM Corporation 2007
Unit Objectives
After completing 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
5.1 Column Functions and GroupingCourse materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-3
Student Notebook
Figure 5-2. SQL Functions CF124.1
Notes:
There are two types of SQL functions:
• Column functions (also known as summary functions)
• Scalar functions
The format for writing both types of functions is the same, the name of the function followed by parentheses. Inside the parentheses is the argument to which the function is applied.
Column functions produce a summary row for a set of rows.
Scalar functions produce a value for each row within the set.
© Copyright IBM Corporation 2007
Function_name(f_argument)
Column ScalarFunctions FunctionsAVG(SALARY) YEAR(HIREDATE)________ __________ _____________ __________ _____________ ______ __________ _____________ __________ _____________ __________ _____
}
SQL Functions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 5-3. Column Functions CF124.1
Notes:
For SUM, AVG, MIN, MAX, COUNT(*), COUNT_BIG(*), COUNT(DISTINCT...), COUNT_BIG(DISTINCT…), the following applies:
The basis for these column functions are values derived from one or more rows.
The data type of the input values for SUM and AVG must be numeric.
Example for COUNT(*):
SELECT COUNT(*) FROM EMPLOYEE WHERE WORKDEPT = 'A00'
returns the number of rows having the value 'A00' in the WORKDEPT column. In general, the argument for COUNT(*) or COUNT_BIG(*) is a set of rows. The result is the number of rows in the set.
COUNT returns an INTEGER value (up to 2,147,483,647); if a larger result is possible (there are tables with billions of rows), then we can use COUNT_BIG which returns a value in DECIMAL(31,0) format.
© Copyright IBM Corporation 2007
Column Functions
COUNT(DISTINCT col-name)COUNT_BIG(DISTINCT col-name)
Determine the number of unique non-null values in a column
COUNT(*)COUNT_BIG(*)
Determine the number of rows meeting the search condition
MAX(expression) Find Maximum Value
MIN(expression)Find Minimum Value
AVG(expression)Calculate Average
SUM(expression)Compute Total
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-5
Student Notebook
Example for COUNT(DISTINCT column-name):
SELECT COUNT(DISTINCT WORKDEPT) FROM EMPLOYEE
returns the number of unique non-null values in the WORKDEPT column.
The argument of this function can also be an expression.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 5-4. Sample Column Functions CF124.1
Notes:
The set of rows to which these column functions are applied contains all rows of the employee table.
The result does not display detailed information for individual rows.
Precision and scale of the resulting values are derived from the definition for the column to which the column function applies.
Except for COUNT(*) and COUNT_BIG(*), expressions (for example, SALARY + COMM) may be used as an argument for column functions.
© Copyright IBM Corporation 2007
AVG MIN MAX COUNT DEPTSUM
27303.59375000 15340.00 52750.00 32 8873715.00
SELECT SUM(SALARY) AS SUM,AVG(SALARY) AS AVG,MIN(SALARY ) AS MIN,MAX(SALARY) AS MAX,COUNT(*) AS COUNT,COUNT (DISTINCT WORKDEPT) AS DEPT
FROM EMPLOYEE
Sample Column Functions
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-7
Student Notebook
Figure 5-5. Beware of Nulls CF124.1
Notes:
If a null is part of row level arithmetic the result is null.
Nulls are ignored in column level arithmetic.
Consider using the COALESCE/VALUE scalar function to replace nulls with known values.
© Copyright IBM Corporation 2007
EMPNO SALARY BONUS COMM SALARY+BONUS+COMM
000010 1000 500 100 1600
000020 2000 NULL 300 NULL
000030 2500 400 NULL NULL
000040 1500 100 400 2000
------ ------ ----- ---- -----------------
Sum: 7000 1000 800 --> 8800 3600
===== ===== ==== ====
SUM(SALARY)+SUM(BONUS)+SUM(COMM)
VERSUS
SUM(SALARY+BONUS+COMM)
Beware of Nulls
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 5-6. Column Functions Based on Subset CF124.1
Notes:
The result is derived from the set of rows for which the WHERE clause predicate is true.
© Copyright IBM Corporation 2007
SUM
373020.00
SELECT SUM(SALARY) AS SUMFROM EMPLOYEEWHERE WORKDEPT LIKE 'D%'
I need the sumof all salaries
for workdepts beginningwith the letter D
Column Functions Based on Subset
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-9
Student Notebook
Figure 5-7. GROUP BY CF124.1
Notes:
With GROUP BY, a column function results in a single value for each group. A group is made up of all the candidate rows (rows satisfying the WHERE clause) having the same value for all the columns in the GROUP BY (in this example, having the same value for WORKDEPT).
A name defined by an AS clause cannot be used in GROUP BY.
GROUP BY does not guarantee a sorted result table. If an ordered result table is required an appropriate ORDER BY clause must be specified.
© Copyright IBM Corporation 2007
SUM
WORKDEPT
A00B01C01
I need a listing of the salaries for allemployees in the departments A00, B01,
and C01. In addition, for these departments,I want the totals spent for salaries.
SELECT WORKDEPT, SALARYFROM EMPLOYEEWHERE WORKDEPT IN ('A00', 'B01', 'C01')ORDER BY WORKDEPT
SELECT WORKDEPT, SUM(SALARY) AS SUMFROM EMPLOYEEWHERE WORKDEPT IN ('A00', 'B01', 'C01')GROUP BY WORKDEPTORDER BY WORKDEPT
128500.0041250.0090470.00
WORKDEPT
SALARYA00A00A00
52750.0046500.0029250.00
B01C01C01C01
41250.0038250.0023800.0028420.00
GROUP BY
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 5-8. GROUP BY More than One Column CF124.1
Notes:
Here we are grouping by the first character of the department number and education level.
© Copyright IBM Corporation 2007
DEPT_GROUP EDLEVEL AVGSAL
A 18 52750.00
A 19 46500.00
B 18 41250.00
C 18 28420.00
C 20 38250.00
D 18 29840.00
SELECT SUBSTR(WORKDEPT,1,1) AS DEPT_GROUP, EDLEVEL,
DECIMAL(AVG(SALARY),9,2) AS AVGSAL
FROM EMPLOYEE
WHERE EDLEVEL >= 18
GROUP BY SUBSTR(WORKDEPT,1,1), EDLEVEL
GROUP BY more than one Column
Find out the average salary per education level for each department group (given by the first character of the department number), for education levels 18 and higher
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-11
Student Notebook
Figure 5-9. The Hardest to Remember Rule in All of SQL! CF124.1
Notes:
Column functions are:
• MIN
• MAX
• SUM
• AVG
• COUNT(*)
• COUNT_BIG(*)
• COUNT(DISTINCT column_name)
• COUNT_BIG(DISTINCT column_name)
The reverse of the rule is not true, that is, columns listed in the GROUP BY clause don't have to have been selected.
© Copyright IBM Corporation 2007
Only applies to queries with COLUMN FUNCTIONSin the SELECT Clause
If a SELECT clause has COLUMN functionsAND
columns not in COLUMN functions
ALL
columns not in COLUMN functions must be included in the GROUP BY clause
The Hardest to Remember Rule in All of SQL!
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 5-10. GROUP BY, ORDER BY CF124.1
Notes:
The requirement is, from the PROJECT table, produce a list that includes MAJPROJ, DEPTNO, the average number of staff assigned and the number of projects that are part of the major project. Our hard to remember rule tells us that when we have a column function in the select list we must GROUP BY all columns in the select list that are not arguments of a column function.
Looking at the fourth line in the report, it can be interpreted to read: Department E21 has 3 subprojects to major project OP2010 and their average staffing is 1.
Note that nulls within the scope of the grouping are combined: the first report line can be interpreted to read: Department C01 has two projects that have an unknown major project.
Note also that nulls are sorted as high values (ORDER BY MAJPROJ DESC).
© Copyright IBM Corporation 2007
MAJPROJ DEPTNO AVG(PRSTAFF) COUNT(*)
- C01 1.5000000000000000000000000000 2
- D01 9.2500000000000000000000000000 2
- E01 5.5000000000000009000000000000 2
OP2010 E21 1.0000000000000000000000000000 3
OP2000 E21 4.0000000000000000000000000000 1
OP1000 E11 5.0000000000000000000000000000 1
MA2110 D11 2.6666666666666661000000000000 3
MA2100 B01 1.0000000000000000000000000000 1
MA2100 D11 8.9999999999999982000000000000 1
AD3110 D21 1.6666666666666663000000000000 3
AD3100 D21 6.0000000000000000000000000000 1
SELECT MAJPROJ, DEPTNO, AVG(PRSTAFF) AS "AVG(PRSTAFF)", COUNT(*) AS "COUNT(*)"
FROM PROJECTGROUP BY MAJPROJ, DEPTNOORDER BY MAJPROJ DESC
GROUP BY, ORDER BY
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-13
Student Notebook
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.
© Copyright IBM Corporation 2007
SUMA00C01
Now, I just want to see departments with total spentfor salaries higher than 50000
SELECT WORKDEPT, SUM(SALARY) AS SUMFROM EMPLOYEEWHERE WORKDEPT IN ('A00', 'B01', 'C01')GROUP BY WORKDEPTHAVING SUM(SALARY) > 50000ORDER BY WORKDEPT
128500.0090470.00
WORKDEPT
SELECT WORKDEPT, SUM(SALARY) AS SUMFROM EMPLOYEEWHERE WORKDEPT IN ('A00', 'B01', 'C01')GROUP BY WORKDEPTORDER BY WORKDEPT
SUMA00B01C01
128500.0041250.0090470.00
WORKDEPT
GROUP BY, HAVING (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
CLERKPRESSALESREPANALYST
29250.0000000052750.0000000046500.0000000026110.00000000
JOB AVGWORKDEPTA00A00A00C01
By department, I need a listing ofjobs, excluding managers, designer,and field representative, with an
average salary higher than $25,000.
SELECT WORKDEPT, JOB, AVG(SALARY) AS AVGFROM EMPLOYEEWHERE JOB NOT IN ('MANAGER', 'DESIGNER', 'FIELDREP')GROUP BY WORKDEPT, JOBHAVING AVG(SALARY) > 25000ORDER BY WORKDEPT, JOB
GROUP BY, HAVING (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-15
Student Notebook
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
© Copyright IBM Corporation 2007
WORKDEPT NUMBB01 1E01 1A00 3C01 3E21 4E11 5D21 6D11 9
WORKDEPT NUMBA00 3C01 3E21 4E11 5D21 6D11 9
Display the departmentswith more than one employee
SELECT WORKDEPT, COUNT(* ) AS NUMB
FROM EMPLOYEEGROUP BY WORKDEPTORDER BY NUMB, WORKDEPT
SELECT WORKDEPT, COUNT(* ) AS NUMB
FROM EMPLOYEEGROUP BY WORKDEPTHAVING COUNT(*) > 1ORDER BY NUMB, WORKDEPT
Examples with HAVING
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 5-14. Restrictions CF124.1
Notes:
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-17
Student Notebook
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.
© Copyright IBM Corporation 2007
SELECT DEP, JOB, AVG(SAL)
FROM EMPL
WHERE JOB <> 'M'
GROUP BY DEP, JOB
HAVING AVG(SAL) > 28000
ORDER BY 3 DESC
SELECT Statement - Six Clauses
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
JOB SAL DEPS 31000 BLUM 32000 REDS 30000 BLU C 27000 GRES 33000 GREM 31000 BLUS 32000 REDC 28000 GRES 30000 REDM 33000 GRES 31000 REDS 35000 GREC 27000 BLUS 29000 REDS 29000 BLU
JOB SAL DEPS 31000 BLU
S 30000 BLUC 27000 GRES 33000 GRE
S 32000 REDC 28000 GRES 30000 RED
S 31000 REDS 35000 GREC 27000 BLUS 29000 REDS 29000 BLU
JOB SAL DEPC 27000 BLU
S 31000 BLUS 29000 BLUS 30000 BLU
C 27000 GREC 28000 GRE
S 33000 GRES 35000 GRE
S 32000 REDS 30000 REDS 31000 REDS 29000 RED
BASE TABLE WHERE GROUP BY
Conceptual Execution of a SELECT (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-19
Student Notebook
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.
© Copyright IBM Corporation 2007
HAVING SELECTJOB SAL DEP
S 31000 BLUS 29000 BLUS 30000 BLU
S 33000 GRES 35000 GRE
S 32000 REDS 30000 REDS 31000 REDS 29000 RED
DEP JOB AVG(SAL)
BLU S 30000
GRE S 34000
RED S 30500
DEP JOB AVG(SAL)
GRE S 34000RED S 30500 BLU S 30000
ORDER BY
Conceptual Execution of a SELECT (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 5-18. Checkpoint CF124.1
Notes:
Please write down your answers below:
1.
2.
3.
4.
© Copyright IBM Corporation 2007
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. SELECTb. FROMc. WHEREd. GROUP BY e. HAVINGf. 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-21
Student Notebook
Figure 5-19. Unit Summary CF124.1
Notes:
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
5-22 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Unit 6. UNIONWhat 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-1
Student Notebook
Figure 6-1. Unit Objectives CF124.1
Notes:
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
6.1 UNIONCourse materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-3
Student Notebook
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.
© Copyright IBM Corporation 2007
QUERY 1SELECT some_columnsFROM some_table(s)WHERE some_conditions
DATA FROM QUERY 1
QUERY 2SELECT some_columnsFROM some_table(s)WHERE some_conditions
DATA FROM QUERY 2
Multiple Queries - Multiple Reports
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
-- QUERY 1SELECT some_columnsFROM some_table(s)WHERE some_conditions
UNION ALL
-- QUERY 2SELECT some_columnsFROM some_table(s)WHERE some_conditions
DATA FROM QUERY 1
DATA FROM QUERY 2
UNIONing Queries Together - Single Report
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-5
Student Notebook
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.
© Copyright IBM Corporation 2007
SELECT COL_6, COL_3, COL_8, COL_14FROM TEST_TAB_AWHERE COL_7 = 'Y'
UNION ALL
SELECT COL_D, COL_Y, COL_A, COL_PFROM TEST_TAB_BWHERE COL_R < 7
Every query in the stack must returnthe same number of columns
Union Rule Number 1
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
The data types of the nth column of eachquery in the stack must be compatible
SELECT COL_6, COL_3, COL_8, COL_14FROM TEST_TAB_AWHERE COL_7 = 'Y'
UNION ALL
SELECT COL_D, COL_Y, COL_A, COL_PFROM TEST_TAB_BWHERE COL_R < 7
Union Rule Number 2
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-7
Student Notebook
Figure 6-6. Union Rule Number 3 CF124.1
Notes:
Only one ORDER BY clause allowed on a UNIONed query.
© Copyright IBM Corporation 2007
The ORDER BY clause must be the lastclause on the last query in the stack
SELECT COL_6, COL_3, COL_8 AS C3FROM TEST_TAB_AWHERE COL_7 = 'Y'
UNION ALL
SELECT COL_D, COL_Y, COL_A AS C3FROM TEST_TAB_BWHERE COL_R < 7ORDER BY C3 DESC, 2
Union Rule Number 3
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
For workdepts C01 and A00 displayworkdept, last name concatenated tofirst name and in a GENDER column
print MALE or FEMALE whereappropriate
SELECT WORKDEPT, LASTNAME || ', ' || FIRSTNME AS NAME,'MALE' AS GENDER
FROM EMPLOYEEWHERE SEX = 'M'
AND WORKDEPT IN ('A00', 'C01')
UNION ALL
SELECT WORKDEPT, LASTNAME || ', ' || FIRSTNME AS NAME, 'FEMALE' AS GENDER
FROM EMPLOYEEWHERE SEX = 'F'AND WORKDEPT IN ('A00', 'C01')ORDER BY WORKDEPT
WORKDEPT NAME GENDER
A00 HAAS, CHRISTINE FEMALE
A00 LUCCHESSI, VINCENZO MALE
A00 O'CONNELL, SEAN MALE
C01 KWAN, SALLY FEMALE
C01 QUINTANA, DOLORES FEMALE
C01 NICHOLLS, HEATHER FEMALE
UNION ALL - Example 1
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-9
Student Notebook
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.
© Copyright IBM Corporation 2007
HAASSPIFFY COMPUTER SERVICE DIV.THOMPSONPLANNINGKWANINFORMATION CENTERGEYERSUPPORT SERVICES
Mgr.:Dept.:Mgr.:Dept.:Mgr.:Dept.:Mgr.:Dept.:
NAMEMGRNO000010000010000020000020000030000030000050000050
As sketched out below, use two linesper department. On line one printmanager's information, on line two
print department information.
SELECT MGRNO , 'Dept.:', DEPTNAME AS NAME
FROM DEPARTMENTWHERE MGRNO IS NOT NULLUNION ALLSELECT MGRNO, 'Mgr.:',
LASTNAME AS NAMEFROM DEPARTMENT D, EMPLOYEE EWHERE D.MGRNO = E.EMPNOORDER BY 1,2 DESC
UNION ALL - Example 2
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
EDLEVEL
EDLEVEL
EDLEVEL
LASTNAME
LASTNAME
LASTNAME
LASTNAME
HAASTHOMPSONNICHOLLSLUTZ
QUINTANANICHOLLSHAASTHOMPSONNICHOLLSLUTZ
QUINTANANICHOLLS
1618
18181818
161818181818
SELECTFROMWHEREUNION ALLSELECTFROMWHERE
LASTNAME, EDLEVELEMPLOYEEJOB = 'ANALYST'
LASTNAME, EDLEVELEMPLOYEEEDLEVEL = 18
SELECTFROMWHERE
LASTNAME, EDLEVELEMPLOYEEEDLEVEL = 18
SELECTFROMWHERE
LASTNAME, EDLEVELEMPLOYEEJOB = 'ANALYST'
UNION ALL - Example 3
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-11
Student Notebook
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
© Copyright IBM Corporation 2007
EDLEVEL
EDLEVEL
EDLEVEL
LASTNAME
LASTNAME
LASTNAME
LASTNAME
HAASLUTZNICHOLLSTHOMPSON
HAASLUTZNICHOLLSQUINTANATHOMPSON
NICHOLLSQUINTANA
1816
18181818
1818181618
SELECTFROMWHEREUNIONSELECTFROMWHERE
LASTNAME, EDLEVELEMPLOYEEJOB = 'ANALYST'
LASTNAME, EDLEVELEMPLOYEEEDLEVEL = 18
SELECTFROMWHERE
LASTNAME, EDLEVELEMPLOYEEEDLEVEL = 18
SELECTFROMWHERE
LASTNAME, EDLEVELEMPLOYEEJOB = 'ANALYST'
UNION
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
SELECT
FROMUNIONSELECT
FROMUNIONSELECT
FROMUNIONSELECT
FROMORDER BY
EMPNO, SUBSTR(FIRSTNME, 1, 1) || '.' || MIDINIT,LASTNAME, SALARY AS INCOME, 1 AS SORTEMPLOYEEALLEMPNO, ' ',' ', BONUS, 2 AS SORTEMPLOYEEALLEMPNO, ' ',' ', COMM, 3 AS SORTEMPLOYEEALLEMPNO, ' ','SUM: ', SALARY + BONUS + COMM,4 AS SORTEMPLOYEEEMPNO, SORT
EMPNO LASTNAME INCOME SORTHAAS
SUM:THOMPSON
SUM:
C.I
M.L
12341234
000010000010000010000010000020000020000020000020
52750.001000.004220.00
57970.0041250.00
800.003300.00
45350.00. .. . .
UNION - Generation of Fitting Result Rows
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-13
Student Notebook
environments). Check the manuals for your environment to determine its supported operator concatenation operators.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
EXCEPT and INTERSECT
EDLEVELLASTNAME
NICHOLLS 18
SELECTFROMWHEREINTERSECTSELECTFROMWHERE
LASTNAME, EDLEVELEMPLOYEEJOB = 'ANALYST'
LASTNAME, EDLEVELEMPLOYEEEDLEVEL = 18
EDLEVELLASTNAME
QUINTANA 16
SELECTFROMWHEREEXCEPTSELECTFROMWHERE
LASTNAME, EDLEVELEMPLOYEEJOB = 'ANALYST'
LASTNAME, EDLEVELEMPLOYEEEDLEVEL = 18
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-15
Student Notebook
Figure 6-13. Checkpoint CF124.1
Notes:
Please write down your answers below:
1.
2.
3.
© Copyright IBM Corporation 2007
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?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 6-14. Unit Summary CF124.1
Notes:
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-17
Student Notebook
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
6-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Unit 7. Using SubqueriesWhat 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-1
Student Notebook
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.
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
7.1 Using SubqueriesCourse materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-3
Student Notebook
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).
© Copyright IBM Corporation 2007
Whose salary is higherthan the average salary?
SELECT AVG(SALARY)FROM EMPLOYEE
SELECT EMPNO, LASTNAMEFROM EMPLOYEEWHERE SALARY > 27303
27303
First Select:
Second Select:
Result Using Separate Selects
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
SELECT EMPNO, LASTNAME
FROM EMPLOYEE
WHERE SALARY > (SELECT AVG(SALARY)
FROM EMPLOYEE)
Same Result Using a Subquery
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-5
Student Notebook
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.
© Copyright IBM Corporation 2007
PARKER
HAASPULASKIPARKER
300
1000700300
LASTNAME
LASTNAME
BONUS
BONUS
EMPNO
EMPNO
000290
000010000070000290
Who earned thelowest bonus?
SELECT EMPNO, LASTNAME, BONUSFROM EMPLOYEEWHERE BONUS = (SELECT MIN (BONUS)
FROM EMPLOYEE)
Subquery with Basic Predicates
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
SELECT FIRSTNME, LASTNAME, EMPNOFROM EMPLOYEEWHERE EMPNO IN (SELECT MGRNO
FROM DEPARTMENT)
List the names and employeenumbers of employees who are
managers of a department
Subquery Using IN
-
000100
000090
000070
000060
000050
000030
000020
000010
Result of subqueryFinal result
000100SPENSERTHEODORE
000090HENDERSEN
EILEEN
000070PULASKIEVA
000060STERNIRVING
000050GEYERJOHN
000030KWANSALLY
000020THOMPSONMICHAEL
000010HAASCHRISTINE
EMPNOLASTNAMEFIRSTNME
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-7
Student Notebook
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.
© Copyright IBM Corporation 2007
SELECT EMPNO, LASTNAME, WORKDEPT, JOBFROM EMPLOYEEWHERE (WORKDEPT, JOB) = ('D21', 'CLERK')
EMPNO LASTNAME WORKDEPT JOB
000230 JEFFERSON D21 CLERK
000240 MARINO D21 CLERK
000250 SMITH D21 CLERK
000260 JOHNSON D21 CLERK
000270 PEREZ D21 CLERK
Variations on Predicates
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
SELECT FIRSTNME, LASTNAME, WORKDEPT, JOB
FROM EMPLOYEEWHERE (WORKDEPT, JOB) IN
(SELECT WORKDEPT, JOB FROM EMPLOYEE
WHERE LASTNAME = 'SMITH')
List the people in Smith's department that have the
same job as Smith
FIRSTNME LASTNAME WORKDEPT JOB
JAMES JEFFERSON D21 CLERK
SALVATORE MARINO D21 CLERK
DANIEL SMITH D21 CLERK
SYBIL JOHNSON D21 CLERK
MARIA PEREZ D21 CLERK
ETHEL SCHNEIDER E11 OPERATOR
JOHN PARKER E11 OPERATOR
PHILIP SMITH E11 OPERATOR
MAUDE SETRIGHT E11 OPERATOR
Subquery Using IN
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-9
Student Notebook
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!
© Copyright IBM Corporation 2007
Result of Subquery
SPIFFY COMPUTER SERVICE
DEPTNAMEDEPTNO
DEPARTMENT Table
Final Result
A00
B01C01D01D11D21E01E11E21
SELECT DEPTNO, DEPTNAMEFROM DEPARTMENTWHERE DEPTNO NOT IN (SELECT DEPTNO
FROM PROJECTWHERE DEPTNO IS NOT NULL)
SPIFFY COMPUTER SERVICEPLANNINGINFORMATION CENTER
DEPTNAMEDEPTNO
A00B01C01. . . . . .
Which departmentsdo not have projectsassigned to them?
Subquery Using NOT IN
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 7-23. Subquery within HAVING Clause CF124.1
Notes:
Subqueries can be also used in a HAVING condition for GROUP values.
© Copyright IBM Corporation 2007
42833.3333333326110.00000000
AVG_WORKDEPTWORKDEPTA00C01
SELECT WORKDEPT, AVG(SALARY) AS AVG_WORKDEPTFROM EMPLOYEEWHERE JOB <> 'MANAGER'GROUP BY WORKDEPTHAVING AVG(SALARY) > (SELECT AVG(SALARY)
FROM EMPLOYEEWHERE JOB <> 'MANAGER')
ORDER BY AVG_WORKDEPT DESC
I need a list of the departments whoseaverage salary for non-managers is higher
than the company-wide average for non-managers. The department with thehighest average should be listed first.
25188.80000000
Result of SubqueryFinal Result
Subquery within HAVING Clause
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-11
Student Notebook
Figure 7-24. Restrictions/Reminders CF124.1
Notes:
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 7-25. Checkpoint CF124.1
Notes:
Please write down your answers below:
1.
2.
3.
© Copyright IBM Corporation 2007
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?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-13
Student Notebook
Figure 7-26. Unit Summary CF124.1
Notes:
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
7-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Unit 8. Maintaining DataWhat 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-1
Student Notebook
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.
© Copyright IBM Corporation 2007
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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
8.1 Maintaining DataCourse materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-3
Student Notebook
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.
© Copyright IBM Corporation 2007
EMPNO
000010000020000030000050000111
LASTNAME WORKDEPT HIREDATE SALARY BONUS
HAASTHOMPSONKWANGEYERSMITH
A00B01C01E01C01
1965-01-011973-10-101975-04-041949-08-171998-06-25
52750.0041250.0038250.0040175.0025000.00
1000.00800.00800.00800.00
-
TESTEMP Table
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
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
Create Table TESTEMP
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 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.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
CREATE VIEW PERSINFO ASSELECT EMPNO, LASTNAME,
SALARY AS YEAR_SAL FROM TESTEMPWHERE WORKDEPT = 'C01'
SELECT *FROM PERSINFO
EMPNO LASTNAME YEAR_SAL
000030000111
KWANSMITH
38250.0025000.00
Create View PERSINFO
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 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.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
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 Corporation 2007
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 LASTNAME WORKDEPT HIREDATE SALARY BONUS
000111 SMITH C01 1998-06-25 25000.00 -
Inserting Rows into the Table
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 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)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 8-32. Insert Multiple Rows CF124.1
Notes:
Instead of the VALUES clause, include a SELECT statement in the INSERT statement to tell DB2 UDB that another table or view contains the data for the new rows. The number and sequence of the selected columns of the EMPLOYEE table must match the number and sequence of the columns of the TESTEMP table.
If a columns list for the target table is used, all its NOT NULL columns must be included.
In the example, we assume that the rows for SMITH, JONES and THOMPSON had already been inserted in the TESTEMP table, and we use this INSERT to copy selected rows from the EMPLOYEE table into the TESTEMP table.
© Copyright IBM Corporation 2007
INSERT INTO TESTEMPSELECT EMPNO,LASTNAME,WORKDEPT,HIREDATE,SALARY,BONUSFROM EMPLOYEEWHERE EMPNO <= '000050'
SELECT * FROM TESTEMP
EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS
000111 SMITH C01 1998-06-25 25000.00 -
000113 JONES C01 2001-06-25 25000.00 -
000114 THOMPSON C01 2001-06-25 25000.00 -
000010 HAAS A00 1965-01-01 52750.00 1000.00
000020 THOMPSON B01 1973-10-10 41250.00 800.00
000030 KWAN C01 1975-04-05 38250.00 800.00
000050 GEYER E01 1949-08-17 40175.00 800.00
Insert Multiple Rows
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-11
Student Notebook
Figure 8-33. Update Columns (1 of 2) CF124.1
Notes:
The UPDATE statement updates the values of the specified columns for one ore more rows of a table or view.
Our new colleague, Mr Smith (employee number 000111) receives a first bonus and a salary raise. Therefore, we must set BONUS to 500 and SALARY to 26000
If more than one column is changed, the columns must be separated by commas. The SET keyword must precede the first column and must not be repeated.
To set BONUS to NULL, the UPDATE statement must be coded as follows:
UPDATE TESTEMP SET BONUS = NULL WHERE EMPNO = '000111'
© Copyright IBM Corporation 2007
EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS
000111 SMITH C01 1998-06-25 25000.00 -
000113 JONES C01 2001-06-25 25000.00 -
000114 THOMPSON C01 2001-06-25 25000.00 -
000010 HAAS A00 1965-01-01 52750.00 1000.00
000020 THOMPSON B01 1973-10-10 41250.00 800.00
000030 KWAN C01 1975-04-05 38250.00 800.00
000050 GEYER E01 1949-08-17 40175.00 800.00
UPDATE TESTEMPSET BONUS = 500,
SALARY = 26000WHERE EMPNO = '000111'
Before:
After:EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS
000111 SMITH C01 1998-06-25 26000.00 500.00
000113 JONES C01 2001-06-25 25000.00 -
000114 THOMPSON C01 2001-06-25 25000.00 -
000010 HAAS A00 1965-01-01 52750.00 1000.00
000020 THOMPSON B01 1973-10-10 41250.00 800.00
000030 KWAN C01 1975-04-05 38250.00 800.00
000050 GEYER E01 1949-08-17 40175.00 800.00
Update Columns (1 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 8-34. Update Columns (2 of 2) CF124.1
Notes:
Our department C01 has finished a project with great success. The salary of all employees should be increased by 1,000.
To update selected rows, use the WHERE clause to specify the rows to be updated.
If you omit the WHERE clause, all rows of the table or view are updated.
© Copyright IBM Corporation 2007
EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS
000111 SMITH C01 1998-06-25 27000.00 500.00
000113 JONES C01 2001-06-25 26000.00 -
000114 THOMPSON C01 2001-06-25 26000.00 -
000010 HAAS A00 1965-01-01 52750.00 1000.00
000020 THOMPSON B01 1973-10-10 41250.00 800.00
000030 KWAN C01 1975-04-05 39250.00 800.00
000050 GEYER E01 1949-08-17 40175.00 800.00
UPDATE TESTEMPSET SALARY = SALARY + 1000WHERE WORKDEPT = 'C01'
Before:
After:
EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS
000111 SMITH C01 1998-06-25 26000.00 500.00
000113 JONES C01 2001-06-25 25000.00 -
000114 THOMPSON C01 2001-06-25 25000.00 -
000010 HAAS A00 1965-01-01 52750.00 1000.00
000020 THOMPSON B01 1973-10-10 41250.00 800.00
000030 KWAN C01 1975-04-05 38250.00 800.00
000050 GEYER E01 1949-08-17 40175.00 800.00
Update Columns (2 of 2)
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-13
Student Notebook
Figure 8-35. Delete Rows CF124.1
Notes:
Mr Smith left the company. Therefore, we delete the row with employee number 000111.
The DELETE statement removes entire rows from a table. Depending on the search condition of the WHERE clause, the DELETE statement removes zero, one, or more rows of a table.
To delete specific rows, use the WHERE clause to specify the rows to be deleted.
If you omit the WHERE clause, all rows of the table or view are deleted.
© Copyright IBM Corporation 2007
DELETE FROM TESTEMPWHERE EMPNO = '000111'
Before:
After:
EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS
000111 SMITH C01 1998-06-25 27000.00 500.00
000113 JONES C01 2001-06-25 26000.00 -
000114 THOMPSON C01 2001-06-25 26000.00 -
000010 HAAS A00 1965-01-01 52750.00 1000.00
000020 THOMPSON B01 1973-10-10 41250.00 800.00
000030 KWAN C01 1975-04-05 39250.00 800.00
000050 GEYER E01 1949-08-17 40175.00 800.00
EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS
000113 JONES C01 2001-06-25 26000.00 -
000114 THOMPSON C01 2001-06-25 26000.00 -
000010 HAAS A00 1965-01-01 52750.00 1000.00
000020 THOMPSON B01 1973-10-10 41250.00 800.00
000030 KWAN C01 1975-04-05 39250.00 800.00
000050 GEYER E01 1949-08-17 40175.00 800.00
Delete Rows
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 8-36. Drop Table TESTEMP CF124.1
Notes:
When executing the statement DROP TESTEMP, DB2 UDB deletes the object, that is, the table. As a consequence, all rows and the table definition are deleted.
Any objects (for example, views, indexes) that are dependent on the table are deleted as well.
© Copyright IBM Corporation 2007
DROP TABLE TESTEMP
VIEW PERSINFO isautomatically dropped
Now test table TESTEMPis no longer needed.
Drop Table TESTEMP
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-15
Student Notebook
Figure 8-37. Reminders CF124.1
Notes:
See your Database Administrator (DBA) for appropriate authorizations.
© Copyright IBM Corporation 2007
Reminders
You must be authorized to execute CREATE/DROP table statementsYou must be authorized to execute statements which change table contentDropping a table drops dependent objectsSearch condition in the WHERE clause qualifies rows to be updated or deletedInserting a row into a view actually inserts the row into the table on which the view is basedUpdating a row of a view updates the row of the table on which the view is basedOmitting the WHERE clause of an UPDATE or DELETE statement causes all rows of the table or view to be updated or deleted
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
Uempty
Figure 8-38. Checkpoint CF124.1
Notes:
Please write down your answers below:
1.
2.
© Copyright IBM Corporation 2007
Checkpoint
1. True or False? You must explicitly be authorized to INSERT data rows in your own table.
2. To delete all rows of a table and its description, you must execute
a. DROP TABLE table name b. DELETE FROM table name and DROP TABLE table name c. DELETE FROM table name
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-17
Student Notebook
Figure 8-39. Unit Summary CF124.1
Notes:
© Copyright IBM Corporation 2007
Unit Summary
Having completed 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
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
8-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
AP
Appendix A. Checkpoint SolutionsUnit 1
© Copyright IBM Corporation 2006
Checkpoint Solutions
1. True2. Automatic verification of correctness
Date arithmeticDate, time, timestamp sortingExtraction of components
3. CHAR/CHARACTER (fixed length)VARCHAR (variable length)SMALLINTINTEGER, INTDECIMAL(x,y), DEC(x,y)
4. SELECTINSERTUPDATEDELETE
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Appendix A. Checkpoint Solutions A-1
Student Notebook
Unit 2
© Copyright IBM Corporation 2007
Checkpoint Solutions
1. False
2. c
3. SELECT, FROM
4. Apostrophes (or single quotes)
5. The keyword LIKE
6. FalseThey are joined by AND or OR.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
A-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
AP
Unit 3© Copyright IBM Corporation 2007
Checkpoint Solutions
1. True
2. b
3. As short names for (qualified) tablesTo avoid ambiguityTo establish correlated references
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Appendix A. Checkpoint Solutions A-3
Student Notebook
Unit 4
© Copyright IBM Corporation 2007
Checkpoint Solutions
1. False
2. c
3. DECIMALSUBSTRCOALESCEVALUEYEARMONTHDAYDAYSROUND
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
A-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
AP
Unit 5© Copyright IBM Corporation 2007
Checkpoint Solutions
1. False. A column function produces a summary row for a set of rows.
2. False. A GROUP BY is required and all three columns not in column functions must be listed in the GROUP BY clause.
3. e
4. False. Column functions may not be used in a WHERE clause.
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Appendix A. Checkpoint Solutions A-5
Student Notebook
Unit 6
© Copyright IBM Corporation 2007
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?
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
A-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
AP
Unit 7© Copyright IBM Corporation 2007
Checkpoint Solutions
1. True
2. b
3. IN
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Appendix A. Checkpoint Solutions A-7
Student Notebook
Unit 8
© Copyright IBM Corporation 2007
Checkpoint Solutions
1. False. The owner of a table has all privileges on the table.
2. a, b
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
A-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007
Student NotebookV3.1.0.1
AP
Appendix B. Built-in FunctionsFollowing is a list of SQL functions generally available on most platforms. Please refer to the SQL Reference manual for your platform and version, and to the SQL Reference for Cross-Platform Development.
Aggregate functions
Scalar functions
AVG COUNT COUNT_BIG MAXMIN STDDEV SUM VARIANCE
ABS ACOS ASIN ATANATANH ATAN2 BLOB CEILINGCHAR CLOB COALESCE CONCATCOS COSH DATE DAYDAYNAME DAYOFWEEK DAYOFWEEK_ISO DAYOFYEARDAYS DBCLOB DECIMAL DECRYPT_BITDECRYPT_CHAR DEGREES DIGITS DOUBLE_PRECISIONENCRYPT EXP FLOAT FLOORGETHINT GRAPHIC HEX HOURIDENTITY_VAL_LOCAL INSERT INTEGER JULIAN_DAYLCASE LEFT LENGTH LNLOCATE LOG10 LOWER LTRIMMICROSECOND MIDNIGHT_SECONDS MINUTE MODMONTH MONTHNAME MULTIPLY_ALT NULLIFPOSSTR POWER QUARTER RADIANSRAISE_ERROR RAND REAL REPEATREPLACE RIGHT ROUND RTRIMSECOND SIGN SIN SINHSMALLINT SPACE SQRT SUBSTRTAN TANH TIME TIMESTAMPTRANSLATE TRUNCATE UCASE UPPERVALUE VARCHAR VARGRAPHIC WEEK
WEEK_ISO YEAR
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
© Copyright IBM Corp. 1999, 2007 Appendix B. Built-in Functions B-1
Student Notebook
Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
B-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007