Vous êtes sur la page 1sur 196

V3.1.0.

cover

 Front cover

DB2 SQL Workshop

(Course Code CF12)

Student Notebook
ERC 4.1

IBM Certified Course Material


Student Notebook

Trademarks
IBM® is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
AIX DB2 iSeries
OS/390 POWER QMF
WebSphere z/OS 400
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Windows is a trademark of Microsoft Corporation in the United States, other countries, or
both.
UNIX® is a registered trademark of The Open Group in the United States and other
countries.
Linux® is a registered trademark of Linus Torvalds in the United States, other countries, or
both.
Other company, product, or service names may be trademarks or service marks of others.

February 2007 Edition

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

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

TOC Contents
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii

Course Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

Unit 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-1


Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
1.1 Introduction to Relational Data Management Systems . . . . . . . . . . . . . . . . . . . 1-3
Computerless Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4
Relational Database Management System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Computerless Data Retrieval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Asking for Information - RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-7
SQL Structured Query Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
Table Name Construction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10
Sample Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Sample Alphanumeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
Date Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13
Time Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-14
CREATE TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15
NULL Characteristic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17
VIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19
Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20

Unit 2. Simple SQL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1


Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
2.1 Simple SQL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
EMPLOYEE Table - Part 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
EMPLOYEE Table - Part 1 (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
DEPARTMENT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
PROJECT Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Structure of an SQL Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Retrieving All Columns, All Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Retrieving All Columns, Limited Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
Selecting Specific Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
Select with Ordered Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13
Select with Ordered Output (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-14
Alternate ORDER BY Specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15
Suppressing Duplicate Output Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
Suppressing Duplicate Output Rows (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
Retrieving Rows by Character Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18

© Copyright IBM Corp. 1999, 2007 Contents iii


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

Retrieving Rows by Numerical Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-19


Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-20
AND and OR - Principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-21
Multiple Conditions - AND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-22
Multiple Conditions - OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-23
Multiple Conditions - AND/OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-24
Multiple Conditions - Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-25
SELECT with IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-26
SELECT with BETWEEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-27
Retrieving Rows - Null Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-28
Partial String Search - LIKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-29
Partial String Search - Examples with '%' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-30
Partial String Search - Example with '_' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-31
Negation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-32
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-33
Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-34

Unit 3. Retrieving Data from Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-1


Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-2
3.1 Accessing Data Stored in Multiple Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Retrieving Data from Multiple Tables (Principle) . . . . . . . . . . . . . . . . . . . . . . . . . . .3-4
Retrieving Data from Multiple Tables (JOIN) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-5
Correlation Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-6
JOIN Syntax 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-7
JOIN Syntax 2 (JOIN Keyword) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-8
Another JOIN Example (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-9
Another JOIN Example (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-10
JOIN with Three Tables (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-11
JOIN with Three Tables (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-12
Joining a Table with Itself (1 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-13
Joining a Table with Itself (2 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-14
Joining a Table with Itself (3 of 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-15
Joining a Table with Itself – Other Example (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . .3-16
Joining a Table with Itself – Other Example (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . .3-17
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-18
Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-19

Unit 4. Scalar Functions and Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-1


Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-2
4.1 Scalar Functions and Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Selecting Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-4
Naming Result Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-5
Substitution of NULL Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-6
Arithmetic with NULL Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-7
Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-8
Decimal Representation of a Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-9
Decimal Values - Truncation and Rounding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-10

iv DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

TOC Condition on Calculated Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11


Date and Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-12
CHAR Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13
Comparison with Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14
DATE / TIME Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15
Subtraction of Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-16
Date / Time Scalar Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17
Date Scalar Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18
DATE Arithmetic (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-19
DATE Arithmetic (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20
Substring of Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-21
Substring of Strings (Cont) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-22
Concatenation of Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-23
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-24
Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-25

Unit 5. Column Functions and Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-1


Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
5.1 Column Functions and Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
SQL Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Column Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-5
Sample Column Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Beware of Nulls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
Column Functions Based on Subset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
GROUP BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
GROUP BY More than One Column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11
The Hardest to Remember Rule in All of SQL! . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12
GROUP BY, ORDER BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13
GROUP BY, HAVING (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14
GROUP BY, HAVING (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15
Examples with HAVING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16
Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-17
SELECT Statement - Six Clauses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18
Conceptual Execution of a SELECT (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-19
Conceptual Execution of a SELECT (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21
Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22

Unit 6. UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1


Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
6.1 UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Multiple Queries - Multiple Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4
UNIONing Queries Together - Single Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5
Union Rule Number 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
Union Rule Number 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
Union Rule Number 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
UNION ALL - Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9

© Copyright IBM Corp. 1999, 2007 Contents v


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

UNION ALL - Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-10


UNION ALL - Example 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-11
UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-12
UNION - Generation of Fitting Result Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-13
EXCEPT and INTERSECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-15
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-16
Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6-17

Unit 7. Using Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-1


Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-2
7.1 Using Subqueries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Result Using Separate Selects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-4
Same Result Using a Subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-5
Subquery with Basic Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-6
Subquery Using IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-7
Variations on Predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-8
Subquery Using IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-9
Subquery Using NOT IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-10
Subquery within HAVING Clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-11
Restrictions/Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-12
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-13
Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-14

Unit 8. Maintaining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-1


Unit Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-2
8.1 Maintaining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-3
TESTEMP Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-4
Create Table TESTEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-5
Create View PERSINFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-7
Inserting Rows into the Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-9
Insert Multiple Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-11
Update Columns (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-12
Update Columns (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-13
Delete Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-14
Drop Table TESTEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-15
Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-16
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-17
Unit Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-18

Appendix A. Checkpoint Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-1

Appendix B. Built-in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-1

vi DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

TMK Trademarks
The reader should recognize that the following terms, which appear in the content of this
training document, are official trademarks of IBM or other companies:
IBM® is a registered trademark of International Business Machines Corporation.
The following are trademarks of International Business Machines Corporation in the United
States, or other countries, or both:
AIX® DB2® iSeries™
OS/390® POWER™ QMF™
WebSphere® z/OS® 400®
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the
United States, other countries, or both.
Windows is a trademark of Microsoft Corporation in the United States, other countries, or
both.
UNIX® is a registered trademark of The Open Group in the United States and other
countries.
Linux® is a registered trademark of Linus Torvalds in the United States, other countries, or
both.
Other company, product, or service names may be trademarks or service marks of others.

© Copyright IBM Corp. 1999, 2007 Trademarks vii


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

viii DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Course Description

DB2 SQL Workshop

Duration: 2 days

Purpose
This course provides an introduction to the SQL language and applies
to the entire DB2 Family.
This course is appropriate for customers working in all DB2
environments, that is, z/OS, VM/VSE, iSeries, Linux, UNIX, and
Windows.

Audience
Everyone needing to write, support, or understand SQL queries. This
includes but is not limited to end-users, programmers, application
designers, database administrators, and system administrators who
do not yet have knowledge of the SQL Data Manipulation Language
(DML).

Prerequisites
• Basic computer literacy
• Basic editing skills
• Database skills are not required

Objectives
On completion of this course, you should be able to:
• Code SQL statements to retrieve data from a DB2 table, including
the SELECT, FROM, WHERE, GROUP BY, HAVING and ORDER
BY clauses
• Code inner Joins, including joining a table to itself
• Use SQL arithmetic operations
• Use scalar and column functions
• Use UNION and UNION ALL
• INSERT, UPDATE and DELETE rows
• Code simple CREATE TABLE and CREATE VIEW statements

© Copyright IBM Corp. 1999, 2007 Course Description ix


Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
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

x DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Agenda

Day 1
Welcome
Introduction
Simple SQL Queries
Exercise 1
Exercise Review
Retrieving Data from Multiple Tables
Exercise 2
Exercise Review
Scalar Functions and Arithmetic
Exercise 3

Day 2
Exercise review
Column Functions and Grouping
Exercise 4
Exercise Review
Union
Exercise 5
Exercise Review
Using Subqueries
Exercise 6
Exercise Review
Maintaining Data
Exercise 7
Exercise Review

© Copyright IBM Corp. 1999, 2007 Agenda vii


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

xii DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Unit 1. Introduction

What This Unit Is About


Database concepts, data types, tables, and views.

What You Should Be Able to Do


After completing this unit, you should be able to:
• Define the terms:
- Database, table, row, column, view
• State the more common DB2 UDB data types
• List the most commonly used SQL statements in the:
- Data Definition Language (DDL)
- Data Manipulation Language (DML)
- Data Control Language (DCL)
• State three null characteristics, and their meaning

How You Will Check Your Progress


• Checkpoint questions

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-1


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

Unit Objectives
After completing this unit, you should be able to:
ƒ Define the terms
– Database, table, row, column, view

ƒ State the more common DB2 data types


ƒ List the most commonly used SQL statements in the
– Data definition language (DDL)
– Data manipulation language (DML)
– Data control language (DCL)

ƒ State three null characteristics and their meaning

© Copyright IBM Corporation 2006

Figure 1-1. Unit Objectives CF124.1

Notes:

1-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty 1.1 Introduction to Relational Data Management Systems

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-3


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

Computerless Data Storage

Departments

Projects

Employees

© Copyright IBM Corporation 2006

Figure 1-2. Computerless Data Storage CF124.1

Notes:
In a traditional office,
• Employee data was filed in an 'EMPLOYEES' folder.
• Department data was filed in a 'DEPARTMENTS' folder.
• Project data was filed in a 'PROJECTS' folder.
People manually managed the data, updated the data, search through it, and retrieved it on
demand.

1-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Relational Database Management System

EMPLOYEE DEPARTMENT
..
MID WORK DEPT
EMPNO FIRSTNME LASTNAME ... DEPTNAME .
INIT DEPT NO
000010 CHRISTINE I HAAS A00 A00 SPIFFY COMPUTER SERVICE DIV.

000020 MICHAEL L THOMPSON B01 B01 PLANNING

000030 SALLY A KWAN C01 C01 INFORMATION CENTER

000050 JOHN B GEYER E01 D01 DEVELOPMENT CENTER

000060 IRVING F STERN D11 D11 MANUFACTURING SYSTEMS

000070 EVA D PULASKI D21 D21 ADMINISTRATION SYSTEMS

PROJECT ..
DEPT
PROJNO PROJNAME NO .

Database AD3100 ADMIN SERVICES D01


A collection of AD3110 GENERAL ADMIN SYSTEMS D21
tables
AD3111 PAYROLL PROGRAMMING D21

AD3112 PERSONNEL PROGRAMMING D21

AD3113 ACCOUNT PROGRAMMING D21

IF1000 QUERY SERVICES C01

© Copyright IBM Corporation 2006

Figure 1-3. Relational Database Management System CF124.1

Notes:
A relational database is a collection of tables.
A table is a set of columns and rows. All data is stored in tables.
Every table has a name.
In a well-designed database, each table contains data about a specific subject (entity); for
instance, one table contains employee data, another table department data, and a third one
data about projects.
The data base management system manages the data.
If someone requires information about an employee, he/she must talk to the data
management system in a language which the system understands: SQL - Structured Query
Language.

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-5


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

Computerless Data Retrieval

Please give me a list


of all employees in
department D11
sorted by name.

000010 HAAS I CHRISTINA


A00
000340GOUNOT R JASON E21
000050GEYER B JOHN E01
000200 BROWN DAVID D11
000150 ADAMSON BRUCE D11

© Copyright IBM Corporation 2006

Figure 1-4. Computerless Data Retrieval CF124.1

Notes:
A query requires:
1. Someone who requests data (data requestor)
2. Someone who returns the data
3. A language understood by both sides
4. A medium for communication
5. A pool with the desired information

1-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Asking for Information - RDBMS


RDBMS
Return a list of
EMPLOYEE
employees in MID
EMPNO LASTNAME FIRSTNME WORKDEPT PHONENO
INIT
department D11
sorted by last name 000150 ADAMSON BRUCE D11 4510

000200 BROWN DAVID D11 4501

000050 GEYER B JOHN E01 6789

000340 GOUNOT R JASON E21 5698

000010 HAAS T CHRISTINE A00 3978

SELECT * FROM
EMPLOYEE WHERE
WORKDEPT = 'D11'
ORDER BY LASTNAME
SE L E
CT S
tatem
ent

© Copyright IBM Corporation 2006

Figure 1-5. Asking for Information - RDBMS CF124.1

Notes
Human communication RDBMS
Data requestor End-user, programmer, designer
Human language Structured Query Language (SQL)
A medium for communication - phone, notes, The medium depends on the environment.
etc. The medium could be a program, a query
tool, etc.
Pool (folders) with the desired information Tables
Someone who fetches the information Integrated search and retrieval functions

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-7


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

SQL Structured Query Language

© Copyright IBM Corporation 2006

Figure 1-6. SQL Structured Query Language CF124.1

Notes:
SQL has similarities with the human language. By means of SQL, we communicate with
the RDBMS. We tell DB2 UDB what we want, not how DB2 UDB should access the data.
SQL can be used either interactively or embedded in an application program, for example,
COBOL, PL/1, C or Java.
The object of a DML query is a set of tables. The result of the DML query is a set of
qualifying rows from these tables.
• DDL is mostly used by data base administrators to define DB2 UDB objects such as
tables, views and indices
• DML is used by all data base users to retrieve information or to maintain data
• DCL is also used by data base administrators to allow or disallow activities in DB2 UDB
by granting or revoking privileges
Most Relational Database Managers understand SQL.

1-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Table
USERA.EMPLOYEE

EMPNO FIRSTNME MIDINIT LASTNAME . . . BIRTHDATE COMM

000010 CHRISTINE I HAAS . . . 1933-08-24 9220

000020 MICHAEL L THOMSON . . . 1948-02-02 0

row 000030 SALLY A KWAN . . . 1941-05-11 -- - - -

000050 JOHN B GEYER . . . 1925-09-15 3214

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

000330 WING LEE . . . 1941-07-18 2030

column text column date column numeric


column
© Copyright IBM Corporation 2006

Figure 1-7. Table CF124.1

Notes:
• Every table has a name.
• Every column has a name.
• Column names must be unique within a table.
• A table consists of a set of rows and columns.
• Rows are normally stored unordered.
• For each row, a column has one entry (field).
• All values of a column have the same data type.

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-9


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

Table Name Construction


Qualified Table Name
USERA.EMPLOYEE

Table owner / Schema Simple Name

USERA © Copyright IBM Corporation 2006


EMPLOYEE
Figure 1-8. Table Name Construction CF124.1

Notes:
• Every table must have a unique name.
• Every table name consists of at least two parts referred to as simple table name and its
qualifier (tables used in a distributed processing environment may have three part
names).
• The qualifier precedes the simple table name and is separated from it by a period.
• The simple table name must be unique within a qualifier.

1-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Sample Numeric Data Types

Data Type Comment

SMALLINT Whole numbers from -32768 to +32767

INTEGER Whole numbers from -2,147,483,648 to


+2,147,483,647

DECIMAL(m,n) Decimal numbers with max. 31 digits


m = total number of digits
n = number of decimal digits

© Copyright IBM Corporation 2006

Figure 1-9. Sample Numeric Data Types CF124.1

Notes:
The visual shows a few of the DB2 UDB supported numeric data types. For complete list of
supported data types in your environment, see the appropriate reference manual.

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-11


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

Sample Alphanumeric Data Types

Data Type Comment

CHAR(n) or STRING (fixed length)


CHARACTER(n)

VARCHAR(n) STRING (variable length)

© Copyright IBM Corporation 2006

Figure 1-10. Sample Alphanumeric Data Types CF124.1

Notes:
The visual shows a few of the alphanumeric data types available for the various platforms.
For completeness, see the reference manual for your environment.
Alphanumeric data may contain any character or printable special character.
In queries, alphanumeric values must be enclosed in single quotes.

1-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Date Data Type

Data Type Comment

DATE Display / Input Format


YYYYMMDD USA mm/dd/yyyy
EUR dd.mm.yyyy
ISO yyyy-mm-dd
JIS yyyy-mm-dd

DATE / TIME / TIMESTAMP data type - input verification


allows arithmetic
sorting
component extraction
© Copyright IBM Corporation 2006

Figure 1-11. Date Data Type CF124.1

Notes:
USA = US Standard
EUR = European Standard
ISO = International Standards Organization
JIS = Japanese Industrial Standard
Within an SQL statement, enclose dates in apostrophes.
Examples:
'2005-01-15'
'01/15/2005'
'15.01.2005'
Within an SQL statement, all date formats (USA, JIS, EUR, ISO) are accepted.

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-13


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

Time Data Type

Data Type Comment

TIME Display / Input Formats


HHMMSS USA hh:mm AM or PM
EUR hh.mm.ss
ISO hh.mm.ss
JIS hh:mm:ss

© Copyright IBM Corporation 2006

Figure 1-12. Time Data Type CF124.1

Notes
USA = US Standard
EUR = European Standard
ISO = International Standards Organization
JIS = Japanese Industrial Standard
Within an SQL statement, enclose times in apostrophes.
Examples:
'21.45.00'
'9:45 PM'
'21:45:00'

1-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Create Table

CREATE TABLE EMPLOYEE


( EMPNO CHAR(6) NOT NULL,
FIRSTNME VARCHAR(12) NOT NULL,
MIDINIT CHAR(1) NOT NULL,
LASTNAME VARCHAR(15) NOT NULL,
WORKDEPT CHAR(3) ,
. . .
. . .
BIRTHDATE DATE ,
SALARY DECIMAL(9,2) ,
BONUS DECIMAL(9,2) ,
COMM DECIMAL(9,2) )
© Copyright IBM Corporation 2006

Figure 1-13. CREATE TABLE CF124.1

Notes:
If a table name qualifier is not explicitly supplied in the CREATE TABLE statement, the DB2
UDB environment determines the qualifier to be assigned (e.g. userid.tablename).
For each column, at a minimum, the following must be defined:
Column name
Data type (and length)
NULL characteristic

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-15


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

NULL Characteristic

"nullable" Column can be marked as having


an 'unknown value'

NOT NULL Column must always have a value

NOT NULL WITH Column must always have a value


DEFAULT if we do not supply one, a system
[(value)] or user defined default value will be
supplied

© Copyright IBM Corporation 2006

Figure 1-14. NULL Characteristic CF124.1

Notes:
When a table is created, if a null characteristic is not provided the column is marked as
"nullable".
A column that is specified as NOT NULL must always contain a value for every row in the
table.
NOT NULL WITH DEFAULT columns are automatically supplied a value when the inserting
user or application does not supply its value.

1-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Authorization

GRANT SELECT ON PROJECT TO SALLY

DEPARTMENT

PROJECT
EMPLOYEE

REVOKE SELECT ON PROJECT FROM SALLY


© Copyright IBM Corporation 2006

Figure 1-15. Authorization CF124.1

Notes:
A table owner or DB2 UDB administrator can grant privileges to other users.
Example 1: Table owner USERX issues the following SQL GRANT and REVOKE
statement:
GRANT SELECT ON PROJECT TO SALLY
This statement gives SALLY permission to retrieve data (SELECT) from the table named
USERX.PROJECT.
REVOKE SELECT ON PROJECT FROM SALLY
This statement revokes SALLY's permission to retrieve data (SELECT) from the table
named USERX.PROJECT.
Example 2: USERX issues the following SQL GRANT:
GRANT SELECT, INSERT, UPDATE ON EMPLOYEE TO SECR1
This statement authorizes user SECR1 to retrieve data from (SELECT), add rows to
(INSERT), or change values of (UPDATE) table USERX.EMPLOYEE.

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-17


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

VIEW

You only see what you should

EMPNO FIRSTNME MIDINIT LASTNAME WORKDEPT PHONENO

000150 BRUCE ADAMSON D11 4510

000200 DAVID BROWN D11 4501

000050 JOHN B GEYER E01 6789

000340
JASON R GOUNOT E21 5698

000010 CHRISTINE T HAAS A00 3978

z Data security z Simplification


© Copyright IBM Corporation 2006

Figure 1-16. VIEW CF124.1

Notes:
Views provide alternative ways of looking at the data of one or more tables. A view can be
thought of as containing the data of selected columns and rows of the base table. For
retrieval, all views can be used as base tables.
Purpose:
• Improved data security.
• Improved data independence.
• Simplification for the end user
(less data, more user-friendly column names)
Properties:
• No additional data is stored.
• A view encompasses a subset of columns and rows.
• A view may encompass data from several tables and/or other views.
• A view may encompass derived data, for example, averages.
• Data manipulation via some views is limited.

1-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Checkpoint

1. True or False? A database is a collection of tables.


2. What are some of the advantages of using date data
types?
3. Name the alphanumeric and numeric data types covered in
this unit.
4. Name the types of SQL statements in the Data
Manipulation Language (DML).

© Copyright IBM Corporation 2006

Figure 1-17. Checkpoint CF124.1

Notes:
Please write down your answers below:
1.
2.
3.
4.

© Copyright IBM Corp. 1999, 2007 Unit 1. Introduction 1-19


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

Unit Summary
Having completed this unit, you should be able to:
ƒ Define the terms
– Database, table, row, column, view

ƒ State the more common DB2 data types


ƒ List the most commonly used SQL statements in the
– Data definition language (DDL)
– Data manipulation language (DML)
– Data control language (DCL)

ƒ State three null characteristics and their meaning

© Copyright IBM Corporation 2006

Figure 1-18. Unit Summary CF124.1

Notes:

1-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Unit 2. Simple SQL Queries

What This Unit Is About


The SELECT statement is used to retrieve data from a table. In this
unit, we will discuss some of the SELECT statement's clauses and
their syntax. In subsequent units, we will be looking at more complex
SELECT statements.

What You Should Be Able to Do


After completing this unit, you should be able to
• Describe four SELECT statement clauses (SELECT, FROM,
WHERE, ORDER BY) and their purpose.
• Retrieve all rows of a table
• Retrieve specific columns
• Retrieve rows based on comparisons to numeric or alphanumeric
column values
• Use the keywords BETWEEN, IN, LIKE, DISTINCT
• Order the resulting rows in a desired sequence

How You Will Check Your Progress


• Checkpoint questions
• Machine labs

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit Objectives
After completing this unit, you should be able to:
ƒ Describe four clauses of an SQL SELECT statement
ƒ Use a SELECT statement to:
– Retrieve all rows of a table
– Retrieve specific columns
– Retrieve rows based on comparisons to numeric or alphanumeric
data
– Retrieve rows based on specific columns containing NULL values

ƒ Use the keywords BETWEEN, IN, LIKE, DISTINCT


ƒ Order the resulting rows in a desired sequence

© Copyright IBM Corporation 2007

Figure 2-1. Unit Objectives CF124.1

Notes:

2-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty 2.1 Simple SQL Queries

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

EMPLOYEE Table - Part 1 (1 of 2)


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

© Copyright IBM Corporation 2007

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

2-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

EMPLOYEE Table - Part 1 (2 of 2)


ED
EMPNO JOB LEVEL SEX BIRTHDATE SALARY BONUS COMM
------ -------- ----- --- ---------- --------- --------- ---------
000010 PRES 18 F 1933-08-24 52750.00 1000.00 4220.00
000020 MANAGER 18 M 1948-02-02 41250.00 800.00 3300.00
000030 MANAGER 20 F 1941-05-11 38250.00 800.00 3060.00
000050 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

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
2-6
Employee Table Data

M
Student Notebook

I
D
I

DB2 SQL Workshop


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

without the prior written permission of IBM.


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

Course materials may not be reproduced in whole or in part


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

© Copyright IBM Corp. 1999, 2007


V3.1.0.1
Student Notebook

Uempty

DEPARTMENT Table

DEPTNO DEPTNAME MGRNO ADMRDEPT LOCATION


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

© Copyright IBM Corporation 2007

Figure 2-4. DEPARTMENT Table CF124.1

Notes:
DEPTNO Department number
DEPTNAME Department name
MGRNO Employee serial number of the responsible manager
ADMRDEPT Department number of the department to which this department reports
LOCATION Location
The dashes in the MGRNO and LOCATION columns indicate unknown values. The dashes
are not physically stored in the table, they are displayed by the report writer to represent
unknown values.

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

PROJECT Table
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
© Copyright IBM Corporation 2007

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

2-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Structure of an SQL Query

SELECT - Defines result columns


Column names
Arithmetic expressions
Literals (text or numeric)
Scalar functions
Column functions
Concatenation
FROM - Table or view names
WHERE - Conditions (qualifies rows)
ORDER BY - Sorts result rows

© Copyright IBM Corporation 2007

Figure 2-6. Structure of an SQL Query CF124.1

Notes:
Clauses must be coded in the sequence indicated in the visual. Each SELECT statement
must have a SELECT and a FROM clause. The other clauses are optional.
The individual clauses will be discussed in detail later on in this course.

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Retrieving All Columns, All Rows

I need a listing of all


department data
SELECT *
FROM DEPARTMENT

DEPTNO DEPTNAME MGRNO ADMRDEPT LOCATION


A00 SPIFFY COMPUTER SERVICE DIV. 000010 A00 -
B01 PLANNING 000020 A00 -
C01 INFORMATION CENTER 000030 A00 -
D01 DEVELOPMENT CENTER - A00 -
D11 MANUFACTURING SYSTEMS 000060 D01 -
D21 ADMINISTRATION SYSTEMS 000070 D01 -
E01 SUPPORT SERVICES 000050 A00 -
E11 OPERATIONS 000090 E01 -
E21 SOFTWARE SUPPORT 000100 E01 -
© Copyright IBM Corporation 2007

Figure 2-7. Retrieving All Columns, All Rows CF124.1

Notes:
The above statement displays all columns and all rows of the DEPARTMENT table.
The output of every SELECT statement is called the result table.
This is a simple statement useful for displaying all of the data in small tables. In practice,
we rarely need to see all of the data in a production table.
In a query, retrieve only the needed columns and rows.

2-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Retrieving All Columns, Limited Rows

What does the data


look like in the
Department table?

SELECT * FROM DEPARTMENT


FETCH FIRST 5 ROWS ONLY

DEPTNO 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 -

© Copyright IBM Corporation 2007

Figure 2-8. Retrieving All Columns, Limited Rows CF124.1

Notes:
The above statement displays all columns of the DEPARTMENT table but limits the result
table to the first x rows specified in the FETCH FIRST clause.
The FETCH FIRST clause, when used with an ORDER BY clause is useful in producing
'top 10' type reports. More on ORDER BY coming up.

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Selecting Specific Columns

For each department, I need


its number, its name and the
department to which it reports.

SELECT DEPTNO, DEPTNAME, ADMRDEPT


FROM DEPARTMENT

DEPTNO DEPTNAME ADMRDEPT


A00 SPIFFY COMPUTER SERVICE DIV. A00
B01 PLANNING A00
C01 INFORMATION CENTER A00
D01 DEVELOPMENT CENTER A00
D11 MANUFACTURING SYSTEMS D01
D21 ADMINISTRATION SYSTEMS D01
E01 SUPPORT SERVICES A00
E11 OPERATIONS E01
E21 SOFTWARE SUPPORT E01
© Copyright IBM Corporation 2007

Figure 2-9. Selecting Specific Columns CF124.1

Notes:
Items in the select list must be separated by commas. Spaces before and after commas
are optional.

2-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Select with Ordered Output (1 of 2)

By the way, the listing


should be sorted by the
department reported to

SELECT DEPTNO, DEPTNAME, ADMRDEPT


FROM DEPARTMENT
ORDER BY ADMRDEPT ASC

DEPTNO DEPTNAME ADMRDEPT


A00 SPIFFY COMPUTER SERVICE DIV.A00
C01 INFORMATION CENTER A00
B01 PLANNING A00
E01 SUPPORT SERVICES A00
D01 DEVELOPMENT CENTER A00
D11 MANUFACTURING SYSTEMS D01
D21 ADMINISTRATION SYSTEMS D01
E21 SOFTWARE SUPPORT E01
E11 OPERATIONS E01
© Copyright IBM Corporation 2007

Figure 2-10. Select with Ordered Output CF124.1

Notes:
• Resulting rows are sequenced according to columns listed in the ORDER BY clause.
• The keyword ASC means sort in ascending sequence. This is the default sort sequence
and the keyword ASC may be omitted.
• DESC means sort in descending sequence.
• Depending on the environment, columns used in the ORDER BY clause must be a part
of the result table.

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Select with Ordered Output (2 of 2)

I need the previous listing


ordered first according to the number
to which the department reports
and within that sequence sorted by
descending department numbers.
SELECT DEPTNO, DEPTNAME, ADMRDEPT
FROM DEPARTMENT
ORDER BY ADMRDEPT ASC, DEPTNO DESC

DEPTNO DEPTNAME ADMRDEPT


E01 SUPPORT SERVICES A00
D01 DEVELOPMENT CENTER A00
C01 INFORMATION CENTER A00
B01 PLANNING A00
A00 SPIFFY COMPUTER SERVICE DIV. A00
D21 ADMINISTRATION SYSTEMS D01
D11 MANUFACTURING SYSTEMS D01
E21 SOFTWARE SUPPORT E01
E11 OPERATIONS E01

© Copyright IBM Corporation 2007

Figure 2-11. Select with Ordered Output (Cont) CF124.1

Notes:
• If multiple columns are specified in the ORDER BY clause, their left to right sequence
within the ORDER BY determines their sorting priority. The first ORDER BY column
defines the primary order of the rows. Subsequent columns of the ORDER BY clause
refine the order of rows. The rows with the same first-column values are further ordered
by the values of the second column specified. The rows with identical first- and
second-column values are further ordered by the values of the third column, and so on.
• ASC or DESC may be specified for each column.
• Date AND time columns may also be sorted in ascending or descending order. Assume
you execute following statement:
SELECT EMPNO, BIRTHDATE FROM EMPLOYEE ORDER BY BIRTHDATE DESC
Then, the youngest employee (the one with the latest birth date) will be listed first.
• A selected column can be identified by the column name or by an integer, referencing
the columns position within the selection list.

2-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Alternate ORDER BY Specifications

SELECT LASTNAME, FIRSTNME, WORKDEPT, JOB, SEX


FROM EMPLOYEE
ORDER BY WORKDEPT DESC, JOB, LASTNAME, SEX DESC

Equivalent ORDER BY clauses:

ORDER BY WORKDEPT DESC, JOB ASC, LASTNAME ASC,


SEX DESC
ORDER BY 3 DESC, 4, 1, 5 DESC
ORDER BY 3 DESC, 4 ASC, 1 ASC, 5 DESC
ORDER BY 3 DESC, JOB, LASTNAME, 5 DESC
ORDER BY WORKDEPT DESC, 4 ASC, 1 ASC, SEX DESC
© Copyright IBM Corporation 2007

Figure 2-12. Alternate ORDER BY Specifications CF124.1

Notes.
Only one ORDER BY clause is allowed per query.
In queries with a SELECT, FROM, WHERE and ORDER BY clause the ORDER BY must
be coded as the last clause in the SELECT statement.

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Suppressing Duplicate Output Rows (1 of 2)

Now, I want to know


the different jobs
performed
by the employees.

SELECT JOB SELECT DISTINCT JOB


FROM EMPLOYEE FROM EMPLOYEE
ORDER BY JOB
JOB
JOB
ANALYST
ANALYST
ANALYST CLERK
CLERK DESIGNER
CLERK FIELDREP
CLERK MANAGER
CLERK OPERATOR
. PRES
. SALESREP

© Copyright IBM Corporation 2007

Figure 2-13. Suppressing Duplicate Output Rows CF124.1

Notes:
• DISTINCT ensures that the result contains unique rows. DISTINCT removes duplicate
rows.
• The keyword DISTINCT must immediately follow the word SELECT. It is effective at the
row level.

2-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Suppressing Duplicate Output Rows (2 of 2)

Also, I need a listing of the


job distribution by department

SELECT WORKDEPT, JOB SELECT DISTINCT WORKDEPT, JOB


FROM EMPLOYEE FROM EMPLOYEE
ORDER BY WORKDEPT, JOB ORDER BY WORKDEPT, JOB

WORKDEPT JOB WORKDEPT JOB


A00 CLERK A00 CLERK
A00 PRES A00 PRES
A00 SALESREP A00 SALESREP
B01 MANAGER B01 MANAGER
C01 ANALYST C01 ANALYST
C01 ANALYST C01 MANAGER
C01 MANAGER D11 DESIGNER
D11 DESIGNER D11 MANAGER
D11 DESIGNER D21 CLERK
D11 DESIGNER D21 MANAGER
D11 DESIGNER E01 MANAGER
D11 DESIGNER E11 MANAGER
D11 DESIGNER E11 OPERATOR
. . E21 FIELDREP
E21 MANAGER
. .
© Copyright IBM Corporation 2007

Figure 2-14. Suppressing Duplicate Output Rows (Cont) CF124.1

Notes:
• DISTINCT eliminates all rows that contain duplicate data in the set of columns specified
in the SELECT clause.
• DISTINCT refers to the result row.
• DISTINCT must not be used more than once within the scope of the SELECT
statement.

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Retrieving Rows by Character Comparison

I need a list of the


departments reporting to
department A00

SELECT DEPTNO, ADMRDEPT


FROM DEPARTMENT
WHERE ADMRDEPT = 'A00'

DEPTNO ADMRDEPT
A00 A00
B01 A00
C01 A00
D01 A00
E01 A00

© Copyright IBM Corporation 2007

Figure 2-15. Retrieving Rows by Character Comparison CF124.1

Notes:
To qualify specific table rows for further processing use the WHERE clause to specify the
conditions rows must meet to be part of the result table.
A WHERE clause can have one or more predicates, tests, or conditions.
A predicate in the WHERE clause specifies a condition that is true, false, or unknown for a
given row or group of rows. The values specified in a predicate must be compatible with the
data type of the column or expression to which it is compared.
For example, if you compare a column which is defined as alphanumeric, the value to
which it is to be compared must be enclosed in single quotes.
The comparison of alphanumeric columns is case sensitive.
The SELECT list need not include the columns used in the WHERE clause.

2-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Retrieving Rows by Numerical Comparison

I want the last name and


education level of all employees
with an education level
greater than or equal to 19

SELECT LASTNAME, EDLEVEL


FROM EMPLOYEE
WHERE EDLEVEL >= 19

LASTNAME EDLEVEL
KWAN 20
LUCCHESSI 19

© Copyright IBM Corporation 2007

Figure 2-16. Retrieving Rows by Numerical Comparison CF124.1

Notes:
For numeric columns, for example, INTEGER, SMALLINT or DECIMAL, the values to be
compared must not be enclosed in single quotes.

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Comparison Operators

SELECT *
FROM EMPLOYEE
WHERE SALARY = 20000 -- equal to
OR SALARY <> 20000 -- not equal to
OR SALARY > 20000 -- greater than
OR SALARY >= 20000 -- greater than or equal to
OR SALARY < 20000 -- less than
OR SALARY <= 20000 -- less than or equal to

© Copyright IBM Corporation 2007

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.

2-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

AND and OR - Principle

YY Yellow AND Oval Y

R R

Y
Y Y
Y Y
Yellow OR Oval Y
Y Y Y
R
R

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Multiple Conditions - AND

List employee number, job, and


education level for analysts with
an education level of 16

SELECT EMPNO, JOB, EDLEVEL


FROM EMPLOYEE
WHERE JOB = 'ANALYST'
AND EDLEVEL = 16

EMPNO JOB EDLEVEL


000130 ANALYST 16

© Copyright IBM Corporation 2007

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.

2-22 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Multiple Conditions - OR

List the columns below for


all analysts and all employees
with an education level of 20. Sort
the list by job and employee number.

SELECT EMPNO, JOB, EDLEVEL


FROM EMPLOYEE
WHERE JOB = 'ANALYST'
OR EDLEVEL = 20
ORDER BY JOB, EMPNO

EMPNO JOB EDLEVEL


000130 ANALYST 16
000140 ANALYST 18
000030 MANAGER 20
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Multiple Conditions - AND/OR

List the columns below for all


analysts with an ed-level of 16. Include
employees with an ed-level of 18. Sort
the list by job and employee number.
SELECT EMPNO, JOB, EDLEVEL
FROM EMPLOYEE
WHERE JOB = 'ANALYST'
AND EDLEVEL = 16
OR EDLEVEL = 18
ORDER BY JOB, EMPNO

EMPNO JOB EDLEVEL


000130 ANALYST 16
000140 ANALYST 18
000220 DESIGNER 18
000020 MANAGER 18
000010 PRES 18
© Copyright IBM Corporation 2007

Figure 2-21. Multiple Conditions - AND/OR CF124.1

Notes:
If you combine multiple conditions by AND and OR, AND takes precedence over OR.

2-24 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Multiple Conditions - Parentheses

List the columns below


for all analysts with an
ed-level of 16 or 18.

SELECT EMPNO, JOB, EDLEVEL


FROM EMPLOYEE
WHERE JOB = 'ANALYST'
AND (EDLEVEL = 16
OR EDLEVEL = 18)

EMPNO JOB EDLEVEL


000130 ANALYST 16
000140 ANALYST 18

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

SELECT with IN

List last name and ed-level for


all employees with an ed-level of
14, 19 or 20. Sort the listing
by ed-level and last name.

SELECT LASTNAME, EDLEVEL


FROM EMPLOYEE
WHERE EDLEVEL IN (14,19,20)
ORDER BY EDLEVEL, LASTNAME

LASTNAME EDLEVEL
JEFFERSON 14
LEE 14
O'CONNELL 14
SMITH 14
SPENSER 14
LUCCHESSI 19
KWAN 20
© Copyright IBM Corporation 2007

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')

2-26 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

SELECT with BETWEEN

List employee number and ed-level


for all employees with an ed-level
from 12 through 15. Sort by ed-level.

SELECT EMPNO, EDLEVEL


FROM EMPLOYEE
WHERE EDLEVEL BETWEEN 12 AND 15
ORDER BY EDLEVEL

EMPNO EDLEVEL
000290 12
000310 12
000100 14
000120 14
000230 14
000300 14
000330 14
000250 15
000270 15
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-27
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Retrieving Rows - Null Comparison

List number and name of all


departments whose manager
is unknown

SELECT DEPTNO, DEPTNAME, MGRNO


FROM DEPARTMENT
WHERE MGRNO IS NULL

DEPTNO DEPTNAME MGRNO


D01 DEVELOPMENT CENTER -

© Copyright IBM Corporation 2007

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.

2-28 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Partial String Search - LIKE

List the last name for all


employees whose last name
starts with the letter G

SELECT LASTNAME
FROM EMPLOYEE
WHERE LASTNAME LIKE 'G%'

LASTNAME
GEYER
GOUNOT

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-29
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Partial String Search - Examples with '%'

SELECT LASTNAME LASTNAME


FROM EMPLOYEE THOMPSON
WHERE LASTNAME LIKE '%SON' HENDERSON
ADAMSON
JEFFERSON
JOHNSON

SELECT LASTNAME LASTNAME


FROM EMPLOYEE THOMPSON
WHERE LASTNAME LIKE '%M%N%' ADAMSON
MARINO

© Copyright IBM Corporation 2007

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.

2-30 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Partial String Search - Example with '_'

I need a listing of all employee


last names whose
second character is the letter
'C'

SELECT LASTNAME
FROM EMPLOYEE
WHERE LASTNAME LIKE '_C%'

LASTNAME
SCOUTTEN
SCHNEIDER
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-31
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Negation

I need a listing of all departments


except those with a department
number starting with 'D'

SELECT DEPTNO, DEPTNAME


FROM DEPARTMENT
WHERE DEPTNO NOT LIKE 'D%'

DEPTNO DEPTNAME
A00 SPIFFY COMPUTER SERVICE DIV.
B01 PLANNING
C01 INFORMATION CENTER
E01 SUPPORT SERVICES
E11 OPERATIONS
E21 SOFTWARE SUPPORT
© Copyright IBM Corporation 2007

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

2-32 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Checkpoint

1. True or False? 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.
© Copyright IBM Corporation 2007

Figure 2-30. Checkpoint CF124.1

Notes:
Please write down your answers below:
1.
2.
3.
4.
5.
6.

© Copyright IBM Corp. 1999, 2007 Unit 2. Simple SQL Queries 2-33
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

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

© Copyright IBM Corporation 2007

Figure 2-31. Unit Summary CF124.1

Notes:

2-34 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Unit 3. Retrieving Data from Multiple Tables

What 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

© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

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

© Copyright IBM Corporation 2007

Figure 3-1. Unit Objectives CF124.1

Notes:

3-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty 3.1 Accessing Data Stored in Multiple Tables

© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Retrieving Data from Multiple Tables (Principle)


PROJECT

PROJNO PROJNAME DEPTNO ...

AD3100 ADMIN SERVICES D01


AD3110 GENERAL ADMIN SYSTEMS D21
AD3111 PAYROLL PROGRAMMING D21
AD3112 PERSONNEL PROGRAMMING D21

DEPARTMENT

DEPTNO DEPTNAME ...

A00 SPIFFY COMPUTER SERVICE DIV.


C01 INFORMATION CENTER
D01 DEVELOPMENT CENTER
D21 ADMINISTRATION SYSTEMS

© Copyright IBM Corporation 2007

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.

3-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

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.

SELECT PROJNO, PROJNAME, PROJECT.DEPTNO, DEPTNAME


FROM PROJECT, DEPARTMENT
WHERE PROJECT.DEPTNO=DEPARTMENT.DEPTNO -- JOIN PREDICATE
ORDER BY PROJNO

PROJNO PROJNAME DEPTNO DEPTNAME


AD3100 ADMIN SERVICES D01 DEVELOPMENT CENTER
AD3110 GENERAL ADMIN SYSTEMS D21 ADMINISTRATION SYSTEMS
AD3111 PAYROLL PROGRAMMING D21 ADMINISTRATION SYSTEMS
AD3112 PERSONNEL PROGRAMMING D21 ADMINISTRATION SYSTEMS
AD3113 ACCOUNT PROGRAMMING D21 ADMINISTRATION SYSTEMS
... ... ... ...

Avoid a Cartesian Product!


© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

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 DEPTNAME


AD3100 ADMIN SERVICES D01 DEVELOPMENT CENTER
AD3110 GENERAL ADMIN SYSTEMS D21 ADMINISTRATION SYSTEMS
AD3111 PAYROLL PROGRAMMING D21 ADMINISTRATION SYSTEMS
AD3112 PERSONNEL PROGRAMMING D21 ADMINISTRATION SYSTEMS
AD3113 ACCOUNT PROGRAMMING D21 ADMINISTRATION SYSTEMS
... ... ... ...

© Copyright IBM Corporation 2007

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.

3-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

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.

SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME


FROM EMPLOYEE, DEPARTMENT
WHERE WORKDEPT = DEPTNO
AND LASTNAME = 'HAAS'

EMPNO LASTNAME WORKDEPT DEPTNAME


000010 HAAS A00 SPIFFY COMPUTER SERVICE DIV.

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

JOIN Syntax 2 (JOIN Keyword)

SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME


FROM EMPLOYEE JOIN
DEPARTMENT
ON WORKDEPT = DEPTNO
WHERE LASTNAME = 'HAAS'

EMPNO LASTNAME WORKDEPT DEPTNAME


000010 HAAS A00 SPIFFY COMPUTER SERVICE DIV.

© Copyright IBM Corporation 2007

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.

3-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Another JOIN Example (1 of 2)

...
Display the department name, and the employee number and last
name of the manager, for department D21.

DEPARTMENT

DEPTNO DEPTNAME MGRNO . . .

A00 SPIFFY COMPUTER SERVICE DIV. 000010


B01 PLANNING 000020
C01 INFORMATION CENTER 000030
D01 DEVELOPMENT CENTER ------
D11 MANUFACTURING SYSTEMS 000060
D21 ADMINISTRATION SYSTEMS 000070
E01 SUPPORT SERVICES 000050

EMPLOYEE
EMPNO FIRSTNME MIDINIT LASTNAME ...
000010 CHRISTINE I HAAS
000020 MICHAEL L THOMPSON
000030 SALLY A KWAN
000050 JOHN B GEYER
000060 IRVING F STERN
000070 EVA D PULASKI
000090 EILEEN W HENDERSON
000100 THEODORE Q SPENSER

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Another JOIN Example (2 of 2)

SELECT DEPTNAME, MGRNO, LASTNAME


FROM DEPARTMENT, EMPLOYEE
WHERE MGRNO = EMPNO
AND DEPTNO = ‘D21’

DEPTNAME MGRNO LASTNAME

ADMINISTRATION SYSTEMS 000070 PULASKI

© Copyright IBM Corporation 2007

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, LASTNAME
FROM DEPARTMENT JOIN EMPLOYEE
ON MGRNO = EMPNO
WHERE DEPTNO = ‘D21'

3-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

JOIN with Three Tables (1 of 2)


PROJECT
PROJNO PROJNAME DEPTNO . . .

AD3100 ADMIN SERVICES D01 For department D21 list


AD3110 GENERAL AD SYSTEMS D21 PROJNO, DEPTNO,
AD3111 PAYROLL PROGRAMMING D21
AD3112 PERSONNEL PROGRAMMING D21 DEPTNAME, MGRNO, and
AD3113 ACCOUNT. PROGRAMMING D21
IF1000 QUERY SERVICES C01 LASTNAME.

DEPARTMENT
DEPTNO DEPTNAME MGRNO . . .

A00 SPIFFY COMPUTER SERVICE DIV. 000010


B01 PLANNING 000020
C01 INFORMATION CENTER 000030
D01 DEVELOPMENT CENTER ------
D11 MANUFACTURING SYSTEMS 000060
D21 ADMINISTRATION SYSTEMS 000070
E01 SUPPORT SERVICES 000050

EMPLOYEE
EMPNO FIRSTNME MIDINIT LASTNAME ...
000010 CHRISTINE I HAAS
000020 MICHAEL L THOMPSON
000030 SALLY A KWAN
000050 JOHN B GEYER
000060 IRVING F STERN
000070 EVA D PULASKI
000090 EILEEN W HENDERSON
000100 THEODORE Q SPENSER

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

JOIN with Three Tables (2 of 2)

SELECT PROJNO, P.DEPTNO, DEPTNAME, MGRNO, LASTNAME


FROM PROJECT P,
DEPARTMENT D,
EMPLOYEE E
WHERE P.DEPTNO = D.DEPTNO -- join predicate
AND D.MGRNO = E.EMPNO -- join predicate
AND D.DEPTNO = 'D21‘ -- local predicate
ORDER BY PROJNO

PROJNO DEPTNO DEPTNAME MGRNO LASTNAME

AD3110 D21 ADMINISTRATION SYSTEMS 000070 PULASKI


AD3111 D21 ADMINISTRATION SYSTEMS 000070 PULASKI
AD3112 D21 ADMINISTRATION SYSTEMS 000070 PULASKI
AD3113 D21 ADMINISTRATION SYSTEMS 000070 PULASKI

© Copyright IBM Corporation 2007

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.

3-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Joining a Table with Itself (1 of 3)

DEPARTMENT

DEPTNO DEPTNAME MGRNO ADMRDEPT

A00 SPIFFY COMPUTER SERVICE DIV. 000010 A00


B01 PLANNING 000020 A00
… … … …

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Joining a Table with Itself (2 of 3)


Display the name of department B01 and the name of. .the
.
department it reports to
DEPARTMENT (DEP)

DEPTNO DEPTNAME MGRNO ADMRDEPT

A00 SPIFFY COMPUTING SERVICE DIV. 000010 A00


B01 PLANNING 000020 A00

DEPTNO DEPTNAME MGRNO ADMRDEPT

A00 SPIFFY COMPUTING SERVICE DIV. 000010 A00 ...


B01 PLANNING 000020 A00

DEPARTMENT (SUP)

© Copyright IBM Corporation 2007

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.

3-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Joining a Table with Itself (3 of 3)

SELECT DEP.DEPTNAME, SUP. DEPTNAME


FROM DEPARTMENT DEP, DEPARTMENT SUP
WHERE DEP.ADMRDEPT = SUP.DEPTNO
AND DEP.DEPTNO = ‘B01’

DEPTNAME DEPTNAME
PLANNING SPIFFY COMPUTER SERVICE DIV.

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Joining a Table with Itself – Another Example (1 of 2)


1. Retrieve employee's row from EMPLOYEE (E)
Which EMPNO . . . LASTNAME WORKDEPT . . . BIRTHDATE . . .

employees 000100 SPENSER E21 1956-12-18


are older 000330 LEE E21 1941-07-18
than their
manager? 2. Obtain department number from DEPARTMENT (D)
DEPTNO DEPTNAME MGRNO ADMRDEPT
. . . .
. . . .
E21 SOFTWARE SUPPORT 000100 E21

3. Retrieve row for manager from EMPLOYEE (M)


EMPNO . . . LASTNAME WORKDEPT . . . BIRTHDATE . . .

000100 SPENSER E21 1956-12-18

000330 LEE E21 1941-07-18


© Copyright IBM Corporation 2007

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.

3-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Joining a Table with Itself – Another Example (2 of 2)

Which employees SELECT E.EMPNO, E.LASTNAME,


are older than E.BIRTHDATE, M.BIRTHDATE, M.EMPNO
their manager? FROM EMPLOYEE E,
DEPARTMENT D,
EMPLOYEE M
WHERE E.WORKDEPT = D.DEPTNO
AND D.MGRNO = M.EMPNO
AND E.BIRTHDATE < M.BIRTHDATE

EMPNO LASTNAME BIRTHDATE BIRTHDATE EMPNO


000110 LUCCHESI 1929-11-05 1933-08-14 000010
000130 QUINTANA 1925-09-15 1941-05-11 000030
000200 BROWN 1941-05-29 1945-07-07 000060
000230 JEFFERSON 1935-05-30 1953-05-26 000070
000250 SMITH 1939-11-12 1953-05-26 000070
000260 JOHNSON 1936-10-05 1953-05-26 000070
000280 SCHNEIDER 1936-03-28 1941-05-15 000090
000300 SMITH 1936-10-27 1941-05-15 000090
000310 SETRIGHT 1931-04-21 1941-05-15 000090
000320 MEHTA 1932-08-11 1956-12-18 000100
000330 LEE 1941-07-18 1956-12-18 000100
000340 GOUNOT 1926-05-17 1956-12-18 000100
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

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?

© Copyright IBM Corporation 2007

Figure 3-16. Checkpoint CF124.1

Notes:
Please write down your answers below:
1.
2.
3.

3-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Unit 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

© Copyright IBM Corporation 2007

Figure 3-17. Unit Summary CF124.1

Notes:

© Copyright IBM Corp. 1999, 2007 Unit 3. Retrieving Data from Multiple Tables 3-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

3-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Unit 4. Scalar Functions and Arithmetic

What 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

© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

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

© Copyright IBM Corporation 2007

Figure 4-1. Unit Objectives CF124.1

Notes:

4-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty 4.1 Scalar Functions and Arithmetic

© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Selecting Calculated Values

I need a list containing


EMPNO, SALARY, COMM,
and SALARY + COMM
for employees whose salary
is less than $20000, SELECT EMPNO, SALARY, COMM,
ordered by employee number SALARY + COMM
FROM EMPLOYEE
WHERE SALARY < 20000
ORDER BY EMPNO

EMPNO SALARY COMM


000210 18270.00 1462.00 19732.00
000250 19180.00 1534.00 20714.00
000260 17250.00 1380.00 18630.00
000290 15340.00 1227.00 16567.00
000300 17750.00 1420.00 19170.00
000310 15900.00 1272.00 17172.00
000320 19950.00 1596.00 21546.00
© Copyright IBM Corporation 2007

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.

4-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Naming Result Columns

SELECT EMPNO, SALARY, COMM, SALARY + COMM AS INCOME


FROM EMPLOYEE
WHERE SALARY < 20000
ORDER BY EMPNO

EMPNO SALARY COMM INCOME

000210 18270.00 1462.00 19732.00


000250 19180.00 1534.00 20714.00
000260 17250.00 1380.00 18630.00
000290 15340.00 1227.00 16567.00
000300 17750.00 1420.00 19170.00
000310 15900.00 1272.00 17172.00
000320 19950.00 1596.00 21546.00
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Substitution of NULL Values

I need a listing containing


department names and the
employee number of its manager,
sorted by department name.

SELECT DEPTNAME
, COALESCE (MGRNO, 'UNKNOWN')
AS MANAGER
FROM DEPARTMENT
ORDER BY DEPTNAME

DEPTNAME MANAGER
ADMINISTRATION SYSTEMS 000070
DEVELOPMENT CENTER UNKNOWN
INFORMATION CENTER 000030
MANUFACTURING SYSTEMS 000060
OPERATIONS 000090
PLANNING 000020
SOFTWARE SUPPORT 000100
SPIFFY COMPUTER SERVICE DIV. 000010
SUPPORT SERVICES 000050
© Copyright IBM Corporation 2007

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).

4-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Arithmetic with NULL Values

I need a list of the total income


(salary and commission).
In the total, assume unknown
commissions to be zero.
SELECT EMPNO, SALARY, COMM,
SALARY +
SELECT EMPNO, SALARY, COMM, COALESCE (COMM, 0)
SALARY + COMM AS "TOTAL INCOME"
AS "TOTAL INCOME" FROM EMPLOYEE
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
... ... ... ...
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 - -
... ... ... ...
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Calculated Values

SELECT EMPNO, SALARY, SALARY * 1.0375


FROM EMPLOYEE
WHERE SALARY < 20000
ORDER BY EMPNO

EMPNO SALARY
000210 18270.00 18955.125000
000250 19180.00 19899.250000
000260 17250.00 17896.875000
000290 15340.00 15915.250000
000300 17750.00 18415.625000
000310 15900.00 16496.250000
000320 19950.00 20698.125000
© Copyright IBM Corporation 2007

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).

4-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Decimal Representation of a Value


SELECT EMPNO, SALARY,
DECIMAL (SALARY * 1.0375, 8, 2)
FROM EMPLOYEE
WHERE SALARY < 20000
ORDER BY EMPNO

EMPNO SALARY
000210 18270.00 18955.12
000250 19180.00 19899.25
000260 17250.00 17896.87
000290 15340.00 15915.25
000300 17750.00 18415.62
000310 15900.00 16496.25
000320 19950.00 20698.12
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Decimal Values - Truncation and Rounding


SELECT EMPNO, SALARY,
DECIMAL (SALARY * 1.0375 + 0.005, 8, 2)
FROM EMPLOYEE
WHERE SALARY < 20000
ORDER BY EMPNO

EMPNO SALARY
000210 18270.00 18955.13
000250 19180.00 19899.25
000260 17250.00 17896.88
000290 15340.00 15915.25
000300 17750.00 18415.63
000310 15900.00 16496.25
000320 19950.00 20698.13
© Copyright IBM Corporation 2007

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.

4-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Condition on Calculated Values

SELECT EMPNO, COMM, SALARY, (COMM/SALARY) * 100


FROM EMPLOYEE
WHERE (COMM/SALARY) * 100 > 8
ORDER BY EMPNO

EMPNO COMM SALARY


000140 2274.00 28420.00 8.001400
000210 1462.00 18270.00 8.002100
000240 2301.00 28760.00 8.000600
000330 2030.00 25370.00 8.001500

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Date and Time


ƒ DATE, TIME, TIMESTAMP data internally stored as
packed decimal, without sign
DataType Internal Format Internal Length
DATE yyyymmdd 4 bytes
TIME hhmmss 3 bytes
TIMESTAMP yyyymmddhhmmssnnnnnn 10 bytes

ƒ Program uses an external format, that is,


Format Time Format Length Date Format Length
ISO hh.mm.ss 8 bytes yyyy-mm-dd 10 bytes
USA hh:mm AM 8 bytes mm/dd/yyyy 10 bytes
hh:mm PM 8 bytes
EUR hh.mm.ss dd.mm.yyyy 10 bytes
JIS hh:mm:ss 8 bytes yyyy-mm-dd 10 bytes
LOCAL ??? ??? ??? ???
TIMESTAMP DATA: yyyy-mm-dd-hh.mm.ss.nnnnnn 26 bytes
© Copyright IBM Corporation 2007

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.

4-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

CHAR Function

ƒ CHAR controls the external format of date / time data

SELECT CHAR (TIMECOL, USA), CHAR (TIMECOL, ISO)...

03:30 PM 15.30.00

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Comparison with Dates

SELECT EMPNO, LASTNAME, BIRTHDATE


FROM EMPLOYEE
WHERE BIRTHDATE >= '1955-01-01'
ORDER BY BIRTHDATE

EMPNO LASTNAME BIRTHDATE


000160 PIANKA 1955-04-12
000100 SPENCER 1956-12-18

© Copyright IBM Corporation 2007

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.

4-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

DATE / TIME Arithmetic


ƒ Subtraction only
time - 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 Æ time
date + labeled duration Æ date
timestamp + duration Æ timestamp

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Subtraction of Dates

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 EMPLOYEE
WHERE CURRENT_DATE - BIRTHDATE >= 720000
ORDER BY DIFFER DESC

EMPNO LASTNAME DIFFER


000130 QUINTANA 790727.
000050 GEYER 790727.
000340 GOUNOT 781126.
000110 LUCCHESSI 750607.
000310 SETRIGHT 740021.
000320 MEHTA 720901.
© Copyright IBM Corporation 2007

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.

4-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

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

© Copyright IBM Corporation 2007

Figure 4-15. Date / Time Scalar Functions CF124.1

Notes:
The visual shows some scalar functions for date and time values.

© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Date Scalar Functions


SELECT LASTNAME, FIRSTNME,
CURRENT_DATE - BIRTHDATE AS AGE,
YEAR(CURRENT_DATE - BIRTHDATE) AS YEARS,
MONTH(CURRENT_DATE - BIRTHDATE) AS MONTHS,
DAY(CURRENT_DATE - BIRTHDATE) AS DAYS
FROM EMPLOYEE
WHERE YEAR(CURRENT_DATE - BIRTHDATE) >= 72
ORDER BY AGE DESC, LASTNAME

LASTNAME FIRSTNME AGE YEARS MONTHS DAYS


GEYER JOHN 790727. 79 7 27
QUINTANA DOLORES 790727. 79 7 27
GOUNOT JASON 781126. 78 11 26
LUCCHESSI VINCENZO 750607. 75 6 7
SETRIGHT MAUDE 740021. 74 0 21
MEHTA RAMLAL 720901. 72 9 1
© Copyright IBM Corporation 2007

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.

4-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

DATE Arithmetic (1 of 2)

SELECT PROJNO,
DAYS(PRENDATE) - DAYS(PRSTDATE) AS DAYS
FROM PROJECT
WHERE DAYS(PRENDATE) - DAYS(PRSTDATE) <= 300
ORDER BY DAYS

PROJNO DAYS
PL2100 257
MA2113 289

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

DATE Arithmetic (2 of 2)

SELECT PROJNO, PRENDATE,


PRENDATE + 2 MONTHS + 15 DAYS
FROM PROJECT
WHERE PROJNO = 'AD3100'
ORDER BY PROJNO

PROJNO PRENDATE

AD3100 1983-02-01 1983-04-16

© Copyright IBM Corporation 2007

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.

4-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Substring of Strings (1 of 2)

COURSINF

C F1 2 SQL B AS I CS
C F1 3 SQL A DV A NCED

SELECT SUBSTR(COURSINF, 6, 15) ...

SQL B AS I CS
SQL A DV A NCED

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Substring of Strings (2 of 2)

SELECT SUBSTR(PROJNO,1, 2) AS PROJ_CLASS,


PROJNAME
FROM PROJECT
WHERE PROJNO LIKE 'IF%'

PROJ_CLASS PROJNAME
IF QUERY SERVICES
IF USER EDUCATION

© Copyright IBM Corporation 2007

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.

4-22 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Concatenation of Values

SELECT LASTNAME CONCAT ', '


CONCAT FIRSTNME AS NAME
FROM EMPLOYEE
WHERE WORKDEPT = 'A00'
ORDER BY NAME

NAME
HAAS, CHRISTINE
LUCCHESSI, VINCENZO
O'CONNELL, SEAN

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-23
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

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.YYYY
b. YYYY-MM-DD
c. YYYYMMDD

3. Name several scalar functions.

© Copyright IBM Corporation 2007

Figure 4-22. Checkpoint CF124.1

Notes:
Please write down your answers below:
1.
2.
3.

4-24 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Unit Summary
Having completed this unit, you should be able to:
ƒ 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

© Copyright IBM Corporation 2007

Figure 4-23. Unit Summary CF124.1

Notes:

© Copyright IBM Corp. 1999, 2007 Unit 4. Scalar Functions and Arithmetic 4-25
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

4-26 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Unit 5. Column Functions and Grouping

What 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

© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-1
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

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

© Copyright IBM Corporation 2007

Figure 5-1. Unit Objectives CF124.1

Notes:

5-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty 5.1 Column Functions and Grouping

© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-3
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

SQL Functions

Function_name(f_argument)

Column Scalar
Functions Functions
AVG(SALARY) YEAR(HIREDATE)
________ __________ _____
________
________
________
________
}
______
__________ _____
__________ _____
__________ _____
__________ _____

© Copyright IBM Corporation 2007

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.

5-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Column Functions

Compute Total SUM(expression)

Calculate Average AVG(expression)

Find Minimum Value MIN(expression)

Find Maximum Value MAX(expression)

Determine the number of rows COUNT(*)


meeting the search condition COUNT_BIG(*)
Determine the number of COUNT(DISTINCT col-name)
unique non-null values in a COUNT_BIG(DISTINCT col-
column name)

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-5
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
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.

5-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Sample Column Functions

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

SUM AVG MIN MAX COUNT DEPT


873715.00 27303.59375000 15340.00 52750.00 32 8

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-7
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Beware of Nulls

SUM(SALARY)+SUM(BONUS)+SUM(COMM)
VERSUS
SUM(SALARY+BONUS+COMM)

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
===== ===== ==== ====

© Copyright IBM Corporation 2007

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.

5-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Column Functions Based on Subset

I need the sum


of all salaries
for workdepts beginning
with the letter D

SELECT SUM(SALARY) AS SUM


FROM EMPLOYEE
WHERE WORKDEPT LIKE 'D%'

SUM
373020.00
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-9
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

GROUP BY

I need a listing of the salaries for all


employees in the departments A00, B01,
and C01. In addition, for these departments,
I want the totals spent for salaries.

SELECT WORKDEPT, SALARY SELECT WORKDEPT, SUM(SALARY) AS SUM


FROM EMPLOYEE FROM EMPLOYEE
WHERE WORKDEPT IN ('A00', 'B01', 'C01') WHERE WORKDEPT IN ('A00', 'B01', 'C01')
ORDER BY WORKDEPT GROUP BY WORKDEPT
ORDER BY WORKDEPT

WORKDEPT SALARY
A00 52750.00
A00 46500.00 WORKDEPT SUM
A00 29250.00 A00 128500.00
B01 41250.00 B01 41250.00
C01 38250.00 C01 90470.00
C01 23800.00
C01 28420.00
© Copyright IBM Corporation 2007

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.

5-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

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

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

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
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-11
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

The Hardest to Remember Rule in All of SQL!

Only applies to queries with COLUMN FUNCTIONS


in the SELECT Clause

If a SELECT clause has COLUMN functions


AND
columns not in COLUMN functions

ALL

columns not in COLUMN functions must be


included in the GROUP BY clause

© Copyright IBM Corporation 2007

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.

5-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

GROUP BY, ORDER BY


SELECT MAJPROJ, DEPTNO,
AVG(PRSTAFF) AS "AVG(PRSTAFF)",
COUNT(*) AS "COUNT(*)"
FROM PROJECT
GROUP BY MAJPROJ, DEPTNO
ORDER BY MAJPROJ DESC

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
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-13
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

GROUP BY, HAVING (1 of 2)

Now, I just want to see


departments with total spent
for salaries higher than 50000

SELECT WORKDEPT, SUM(SALARY) AS SUM SELECT WORKDEPT, SUM(SALARY) AS SUM


FROM EMPLOYEE FROM EMPLOYEE
WHERE WORKDEPT IN ('A00', 'B01', 'C01') WHERE WORKDEPT IN ('A00', 'B01', 'C01')
GROUP BY WORKDEPT GROUP BY WORKDEPT
ORDER BY WORKDEPT HAVING SUM(SALARY) > 50000
ORDER BY WORKDEPT

WORKDEPT SUM
A00 128500.00 WORKDEPT SUM
A00 128500.00
B01 41250.00
C01 90470.00
C01 90470.00
© Copyright IBM Corporation 2007

Figure 5-11. GROUP BY, HAVING (1 of 2) CF124.1

Notes:
So far we built groups. With HAVING, we now can select groups satisfying certain
conditions. Conditions for groups must be specified in the having clause.
HAVING may specify any column function on any column in a table being queried. This
column need not be in the SELECT list.
HAVING is used to qualify or disqualify a group from further processing.

5-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

GROUP BY, HAVING (2 of 2)

By department, I need a listing of


jobs, excluding managers, designer,
and field representative, with an
average salary higher than $25,000.

SELECT WORKDEPT, JOB, AVG(SALARY) AS AVG


FROM EMPLOYEE
WHERE JOB NOT IN ('MANAGER', 'DESIGNER', 'FIELDREP')
GROUP BY WORKDEPT, JOB
HAVING AVG(SALARY) > 25000
ORDER BY WORKDEPT, JOB

WORKDEPT JOB AVG


A00 CLERK 29250.00000000
A00 PRES 52750.00000000
A00 SALESREP 46500.00000000
C01 ANALYST 26110.00000000

© Copyright IBM Corporation 2007

Figure 5-12. GROUP BY, HAVING (2 of 2) CF124.1

Notes:
In the above example, we see another example of a GROUP BY clause with two columns,
and another example of HAVING.
The first three rows in the result have the same value ('A00') in the WORKDEPT column,
but different values in the JOB column. The results of a GROUP BY clause is one result
row for each unique set of values across the columns being grouped.

© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-15
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Examples with HAVING

Display the departments


with more than one employee

SELECT WORKDEPT, SELECT WORKDEPT,


COUNT(* ) AS NUMB COUNT(* ) AS NUMB
FROM EMPLOYEE FROM EMPLOYEE
GROUP BY WORKDEPT GROUP BY WORKDEPT
ORDER BY NUMB, WORKDEPT HAVING COUNT(*) > 1
ORDER BY NUMB, WORKDEPT

WORKDEPT NUMB WORKDEPT NUMB


B01 1 A00 3
E01 1 C01 3
A00 3 E21 4
C01 3 E11 5
E21 4 D21 6
E11 5 D11 9
D21 6
D11 9
© Copyright IBM Corporation 2007

Figure 5-13. Examples with HAVING CF124.1

Notes:
The left SELECT is displayed to show the result without a HAVING clause.
The right SELECT determines the result table consisting of groups for which the search
condition of the HAVING clause is true.
The condition COUNT(*) > 1 applies to the result table of the left SELECT

5-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Restrictions
ƒ Column functions may be specified only in
– SELECT
– HAVING

ƒ SELECT may specify only


– Column functions
– Columns specified in 'GROUP BY'

ƒ HAVING may specify


– Any column function on any column in a table being queried.
This column need not be in the SELECT.

ƒ Column functions may not be nested

© Copyright IBM Corporation 2007

Figure 5-14. Restrictions CF124.1

Notes:

© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-17
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

SELECT Statement - Six Clauses


SELECT DEP, JOB, AVG(SAL)

FROM EMPL

WHERE JOB <> 'M'

GROUP BY DEP, JOB

HAVING AVG(SAL) > 28000

ORDER BY 3 DESC

© Copyright IBM Corporation 2007

Figure 5-15. SELECT Statement - Six Clauses CF124.1

Notes:
The SELECT clause tells DB2 UDB which column(s) of information we want on our report.
The SELECT list contains a column function (also known as a summary function) AVG.
Column functions tell DB2 UDB to produce a single summary row for a set of detail rows.
The FROM clause tells DB2 UDB which table(s) contain the requested data.
The WHERE clause specifies which row(s) of information are to be used based upon some
qualification criteria.
The GROUP BY clause tells DB2 UDB which row(s) of information are to be grouped
together (that is, summarized) based upon values in a column(s).
The HAVING clause tells DB2 UDB which group(s) of information are to be processed
based upon a group qualification criteria.
The ORDER BY clause specifies sequence of the result rows in the final result table.

5-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Conceptual Execution of a SELECT (1 of 2)

BASE TABLE WHERE GROUP BY

JOB SAL DEP JOB SAL DEP JOB SAL DEP


S 31000 BLU S 31000 BLU C 27000 BLU
M 32000 RED
S 30000 BLU S 30000 BLU S 31000 BLU
C 27000 GRE C 27000 GRE S 29000 BLU
S 33000 GRE S 33000 GRE S 30000 BLU
M 31000 BLU
S 32000 RED S 32000 RED C 27000 GRE
C 28000 GRE C 28000 GRE C 28000 GRE
S 30000 RED S 30000 RED
M 33000 GRE S 33000 GRE
S 31000 RED S 31000 RED S 35000 GRE
S 35000 GRE S 35000 GRE
C 27000 BLU C 27000 BLU S 32000 RED
S 29000 RED S 29000 RED S 30000 RED
S 29000 BLU S 29000 BLU S 31000 RED
S 29000 RED

© Copyright IBM Corporation 2007

Figure 5-16. Conceptual Execution of a SELECT (1 of 2) CF124.1

Notes:
The clauses are executed in this sequence:
• FROM
• WHERE
• GROUP BY
Through the FROM clause DB2 UDB locates the table.
The WHERE clause extracts into the conceptual intermediate table rows that will be
processed further.
The GROUP BY clause sorts the rows in the intermediate table into subsets.

© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-19
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Conceptual Execution of a SELECT (2 of 2)

HAVING SELECT ORDER BY


JOB SAL DEP DEP JOB AVG(SAL) DEP JOB AVG(SAL)

GRE S 34000
S 31000 BLU BLU S 30000 RED S 30500
S 29000 BLU BLU S 30000
S 30000 BLU

S 33000 GRE GRE S 34000


S 35000 GRE

S 32000 RED RED S 30500


S 30000 RED
S 31000 RED
S 29000 RED

© Copyright IBM Corporation 2007

Figure 5-17. Conceptual Execution of a SELECT (2 of 2) CF124.1

Notes:
Only those groups passing the HAVING clause test are processed further.

5-20 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Checkpoint
1. True or False? A scalar function produces a summary row
for a set of rows.
2. A SELECT statement whose SELECT list includes a
column function (SUM, AVG, MIN, MAX, COUNT, and so
forth) and three columns not in column functions does not
require a GROUP BY clause.
3. Which clause qualifies groups for further processing?
a. SELECT
b. FROM
c. WHERE
d. GROUP BY
e. HAVING
f. ORDER BY
4. True or False? The following query is syntactically correct.
SELECT WORKDEPT, AVG(SALARY)
FROM EMPLOYEE
WHERE AVG(SALARY) > 20000
GROUP BY WORKDEPT
HAVING COUNT(*) > 3
ORDER BY 2 DESC
© Copyright IBM Corporation 2007

Figure 5-18. Checkpoint CF124.1

Notes:
Please write down your answers below:
1.
2.
3.
4.

© Copyright IBM Corp. 1999, 2007 Unit 5. Column Functions and Grouping 5-21
Course materials may not be reproduced in whole or in part
without the prior written permission of IBM.
Student Notebook

Unit Summary
Having completed this unit, you should be able to:
ƒ Describe the difference between scalar and column functions
ƒ List the more common DB2 column functions
ƒ Group rows into sets based on one or more columns

© Copyright IBM Corporation 2007

Figure 5-19. Unit Summary CF124.1

Notes:

5-22 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Unit 6. UNION

What This Unit Is About


This unit describes the syntax of an SQL statement that will produce a
result table containing the results of two or more SELECT statements.

What You Should Be Able to Do


After completing this unit, you should be able to:
• Produce a single result table containing data from more than one
query
• State the UNION rules
• State the difference between UNION and UNION ALL

How You Will Check Your Progress


Accountability:
• Checkpoint
• Machine labs

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-1


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

Unit Objectives
After completing this unit, you should be able to:
ƒ Produce a single result table containing data from more than
one query
ƒ State the UNION rules
ƒ State the difference between UNION and UNION ALL

© Copyright IBM Corporation 2007

Figure 6-1. Unit Objectives CF124.1

Notes:

6-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty 6.1 UNION

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-3


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

Multiple Queries - Multiple Reports

QUERY 1 DATA FROM QUERY 1


SELECT some_columns
FROM some_table(s)
WHERE some_conditions

QUERY 2 DATA FROM QUERY 2


SELECT some_columns
FROM some_table(s)
WHERE some_conditions

© Copyright IBM Corporation 2007

Figure 6-2. Multiple Queries - Multiple Reports CF124.1

Notes:
Each time a query is executed a single report is produced.
Sometimes we have a requirement for data returned by one query to appear in a report
with data from additional queries.

6-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

UNIONing Queries Together - Single Report

-- QUERY 1
SELECT some_columns DATA FROM QUERY 1
FROM some_table(s)
WHERE some_conditions

UNION ALL
DATA FROM QUERY 2
-- QUERY 2
SELECT some_columns
FROM some_table(s)
WHERE some_conditions

© Copyright IBM Corporation 2007

Figure 6-3. UNIONing Queries Together - Single Report CF124.1

Notes:
By following the UNION RULES, and adding a UNION ALL clause between the queries the
data from both queries appears in a single report.

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-5


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

Union Rule Number 1

SELECT COL_6, COL_3, COL_8, COL_14


FROM TEST_TAB_A
WHERE COL_7 = 'Y'

UNION ALL

SELECT COL_D, COL_Y, COL_A, COL_P


FROM TEST_TAB_B
WHERE COL_R < 7

Every query in the stack must return


the same number of columns
© Copyright IBM Corporation 2007

Figure 6-4. Union Rule Number 1 CF124.1

Notes:
If the first query in the stack returns x number of columns every query in the stack must
return x number of columns.

6-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Union Rule Number 2


SELECT COL_6, COL_3, COL_8, COL_14
FROM TEST_TAB_A
WHERE COL_7 = 'Y'

UNION ALL

SELECT COL_D, COL_Y, COL_A, COL_P


FROM TEST_TAB_B
WHERE COL_R < 7

The data types of the nth column of each


query in the stack must be compatible

© Copyright IBM Corporation 2007

Figure 6-5. Union Rule Number 2 CF124.1

Notes:
If the nth column in the first query returns character data then the corresponding nth
column in every query of the stack must return character data.
Column lengths do not have to match.
Numeric precision and scale do not have to match (integer and DEC(7,2) data can appear
in the same column). The report column will carry the largest precision and scale of all
numbers in the column.

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-7


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

Union Rule Number 3


SELECT COL_6, COL_3, COL_8 AS C3
FROM TEST_TAB_A
WHERE COL_7 = 'Y'

UNION ALL

SELECT COL_D, COL_Y, COL_A AS C3


FROM TEST_TAB_B
WHERE COL_R < 7
ORDER BY C3 DESC, 2

The ORDER BY clause must be the last


clause on the last query in the stack
© Copyright IBM Corporation 2007

Figure 6-6. Union Rule Number 3 CF124.1

Notes:
Only one ORDER BY clause allowed on a UNIONed query.

6-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

UNION ALL - Example 1


SELECT WORKDEPT, LASTNAME || ', ' ||
FIRSTNME AS NAME,
'MALE' AS GENDER
For workdepts C01 and A00 display FROM EMPLOYEE
workdept, last name concatenated to
WHERE SEX = 'M'
first name and in a GENDER column
AND WORKDEPT IN ('A00', 'C01')
print MALE or FEMALE where
appropriate
UNION ALL

SELECT WORKDEPT, LASTNAME || ', ' ||


FIRSTNME AS NAME,
'FEMALE' AS GENDER
FROM EMPLOYEE
WHERE SEX = 'F'
AND WORKDEPT IN ('A00', 'C01')
ORDER BY WORKDEPT

WORKDEPT 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

© Copyright IBM Corporation 2007

Figure 6-7. UNION ALL - Example 1 CF124.1

Notes:
The above example is one of several ways of translating coded data into more human
terms (the value of M replaced with the word MALE, the value of F replaced with the word
FEMALE.

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-9


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

UNION ALL - Example 2

SELECT MGRNO , 'Dept.:',


As sketched out below, use two lines DEPTNAME AS NAME
per department. On line one print FROM DEPARTMENT
manager's information, on line two
WHERE MGRNO IS NOT NULL
print department information.
UNION ALL
SELECT MGRNO, 'Mgr.:',
LASTNAME AS NAME
FROM DEPARTMENT D, EMPLOYEE E
WHERE D.MGRNO = E.EMPNO
ORDER BY 1,2 DESC

MGRNO NAME
000010 Mgr.: HAAS
000010 Dept.: SPIFFY COMPUTER SERVICE DIV.
000020 Mgr.: THOMPSON
000020 Dept.: PLANNING
000030 Mgr.: KWAN
000030 Dept.: INFORMATION CENTER
000050 Mgr.: GEYER
000050 Dept.: SUPPORT SERVICES
© Copyright IBM Corporation 2007

Figure 6-8. UNION ALL - Example 2 CF124.1

Notes:
The first SELECT establishes the column headings of the result.
If a column you wish to sort by has the same name in each query in the stack, then the
column name can be used in the ORDER BY clause. Otherwise, the column's position
number must be used.

6-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

UNION ALL - Example 3

SELECT LASTNAME, EDLEVEL LASTNAME EDLEVEL


FROM EMPLOYEE QUINTANA 16
WHERE JOB = 'ANALYST' NICHOLLS 18

SELECT LASTNAME, EDLEVEL LASTNAME EDLEVEL


FROM EMPLOYEE HAAS 18
WHERE EDLEVEL = 18 THOMPSON 18
NICHOLLS 18
LUTZ 18

SELECT LASTNAME, EDLEVEL LASTNAME EDLEVEL


FROM EMPLOYEE QUINTANA 16
WHERE JOB = 'ANALYST' NICHOLLS 18
UNION ALL HAAS 18
SELECT LASTNAME, EDLEVEL THOMPSON 18
FROM EMPLOYEE NICHOLLS 18
WHERE EDLEVEL = 18 LUTZ 18

© Copyright IBM Corporation 2007

Figure 6-9. UNION ALL - Example 3 CF124.1

Notes:
UNION ALL does not eliminate duplicates.
Use UNION ALL if the queries cannot return duplicate rows.

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-11


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

UNION

SELECT LASTNAME, EDLEVEL LASTNAME EDLEVEL


FROM EMPLOYEE NICHOLLS 18
WHERE JOB = 'ANALYST' QUINTANA 16

SELECT LASTNAME, EDLEVEL LASTNAME EDLEVEL


FROM EMPLOYEE HAAS 18
WHERE EDLEVEL = 18 LUTZ 18
NICHOLLS 18
THOMPSON 18

SELECT LASTNAME, EDLEVEL LASTNAME EDLEVEL


FROM EMPLOYEE HAAS 18
WHERE JOB = 'ANALYST' LUTZ 18
UNION NICHOLLS 18
SELECT LASTNAME, EDLEVEL QUINTANA 16
FROM EMPLOYEE THOMPSON 18
WHERE EDLEVEL = 18

© Copyright IBM Corporation 2007

Figure 6-10. UNION CF124.1

Notes:
UNION combines two sets of rows and removes duplicates.
Therefore, UNION ALL often performs better than UNION.
The problem to list last name and education level of employees who are analysts or have
an education level of 18 can be solved by means of a UNION performing the following
three steps:
1. Each SELECT is evaluated separately
2. The results are merged and ordered
3. Duplicates are removed

6-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

UNION - Generation of Fitting Result Rows


SELECT EMPNO, SUBSTR(FIRSTNME, 1, 1) || '.' || MIDINIT,
LASTNAME, SALARY AS INCOME, 1 AS SORT
FROM EMPLOYEE
UNION ALL
SELECT EMPNO, ' ',
' ', BONUS, 2 AS SORT
FROM EMPLOYEE
UNION ALL
SELECT EMPNO, ' ',
' ', COMM, 3 AS SORT
FROM EMPLOYEE
UNION ALL
SELECT EMPNO, ' ',
'SUM: ', SALARY + BONUS + COMM,
4 AS SORT
FROM EMPLOYEE
ORDER BY EMPNO, SORT

EMPNO LASTNAME INCOME SORT


000010 C.I HAAS 52750.00 1
000010 1000.00 2
000010 4220.00 3
000010 SUM: 57970.00 4
000020 M.L THOMPSON 41250.00 1
000020 800.00 2
000020 3300.00 3
000020
. . SUM:. 45350.00
. 4.
© Copyright IBM Corporation 2007

Figure 6-11. UNION - Generation of Fitting Result Rows CF124.1

Notes:
Any type of SELECT statement can be used as long as the rules for UNION are adhered
to. All column and scalar functions can be used.
In the above example, a substring of first name concatenated with the MIDINIT and the last
name are selected in the first SELECT. To get the equivalent number of columns in the
other SELECT statements, blanks (compatible to the data types of the concatenated value
and the last name value) are specified as corresponding column values. Numeric literals,
current date or current time can be 'place holders' at the appropriate spots in UNIONed
queries.
EMPNO must be selected to order the result table.
To get a four row result for each employee in the desired order
(1st salary, 2nd bonus, 3rd commission, 4th sum), we need an additional sort column.
The double exclamation points (!!), and double bars (||) (in environments where they are
supported), are equivalent to the CONCAT operator (which is supported in all

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-13


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

environments). Check the manuals for your environment to determine its supported
operator concatenation operators.

6-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

EXCEPT and INTERSECT

SELECT LASTNAME, EDLEVEL LASTNAME EDLEVEL


FROM EMPLOYEE
WHERE JOB = 'ANALYST'
EXCEPT QUINTANA 16
SELECT LASTNAME, EDLEVEL
FROM EMPLOYEE
WHERE EDLEVEL = 18

SELECT LASTNAME, EDLEVEL LASTNAME EDLEVEL


FROM EMPLOYEE
WHERE JOB = 'ANALYST'
INTERSECT NICHOLLS 18
SELECT LASTNAME, EDLEVEL
FROM EMPLOYEE
WHERE EDLEVEL = 18

© Copyright IBM Corporation 2007

Figure 6-12. EXCEPT and INTERSECT CF124.1

Notes:
Here are two other sets of words that can be used in place of UNION ALL and UNION.
They are also used for merging data, but work differently.
EXCEPT displays what is in the first result set but not in the second result set. In this case,
it displays ANALYSTS who are not edlevel 18. This would show duplicates if there were
any; EXCEPT ALL would not.
INTERSECT displays only what is in both the first result set and in the second result set. In
this case, it displays ONLY ANALYSTS who are ALSO edlevel 18. This would show
duplicates if there were any; INTERSECT ALL would not.

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-15


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

Checkpoint

1. True or False? The results of arbitrary SELECTs can be


combined by means of UNION and ordered to get a new
result.
2. Why or when should you use UNION?
a. When all duplicate rows have to be eliminated.
b. When SELECTs with an arbitrary number of columns should be
combined.

3. Which rules do you have to consider when using UNION?

© Copyright IBM Corporation 2007

Figure 6-13. Checkpoint CF124.1

Notes:
Please write down your answers below:
1.
2.
3.

6-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Unit Summary
Having completed this unit, you should be able to:
ƒ Produce a single result table containing data from more than
one query
ƒ State the UNION rules
ƒ State the difference between UNION and UNION ALL

© Copyright IBM Corporation 2007

Figure 6-14. Unit Summary CF124.1

Notes:

© Copyright IBM Corp. 1999, 2007 Unit 6. UNION 6-17


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

6-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Unit 7. Using Subqueries

What This Unit Is About


This unit provides information on how to use subqueries.

What You Should Be Able to Do


After completing this unit, you should be able to:
• Use subqueries in WHERE and HAVING clauses
• Code subqueries using basic predicates
• Code subqueries using the IN keyword

How You Will Check Your Progress


Accountability:
• Checkpoint
• Machine labs

© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-1


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

Unit Objectives
After completing this unit, you should be able to:
ƒ Use subqueries in WHERE and HAVING clauses
ƒ Code subqueries using basic predicates
ƒ Code subqueries using IN

© Copyright IBM Corporation 2007

Figure 7-15. Unit Objectives CF124.1

Notes:
It is often useful to imbed a query within another. This enables the inner query to provide an
answer to a question for use in the outer query. The inner query is referred to as a
subquery.

7-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty 7.1 Using Subqueries

© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-3


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

Result Using Separate Selects

Whose salary is higher


than the average salary?

First Select: SELECT AVG(SALARY)


FROM EMPLOYEE

27303

Second Select: SELECT EMPNO, LASTNAME


FROM EMPLOYEE
WHERE SALARY > 27303
© Copyright IBM Corporation 2007

Figure 7-16. Result Using Separate Selects CF124.1

Notes:
Assume that you want to identify all employees whose salary is higher than the average
salary of all employees.
Without subqueries, you would have to do the following:
• Evaluate the average salary of all employees (first select)
• Code a second query using the result (27303) in the WHERE clause.
• Run the second query to find the employees whose salary is higher than the average
salary (27303).

7-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Same Result Using a Subquery

SELECT EMPNO, LASTNAME

FROM EMPLOYEE

WHERE SALARY > (SELECT AVG(SALARY)

FROM EMPLOYEE)

© Copyright IBM Corporation 2007

Figure 7-17. Same Result Using a Subquery CF124.1

Notes:
The problem, described on the previous visual can be solved by means of a single
execution of a query containing a subquery.
We can code the first SELECT of the previous visual in the WHERE condition of the
second SELECT of the previous visual at the place where the average is needed.
As a consequence, the second SELECT is executed by the outer(main) query. The inner
SELECT is referred to as the subquery.
The subquery runs first, and the result is used to evaluate the WHERE condition of the
main query.
A subquery cannot contain an ORDER BY.
The results of the subquery are passed to the outer query and are not visible to the user.

© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-5


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

Subquery with Basic Predicates

EMPNO LASTNAME BONUS


Who earned the
lowest bonus? 000010 HAAS 1000
000070 PULASKI 700
000290 PARKER 300

SELECT EMPNO, LASTNAME, BONUS


FROM EMPLOYEE
WHERE BONUS = (SELECT MIN (BONUS)
FROM EMPLOYEE)

EMPNO LASTNAME BONUS


000290 PARKER 300
© Copyright IBM Corporation 2007

Figure 7-18. Subquery with Basic Predicates CF124.1

Notes:
In this example, we look for the employee(s) who earned the lowest bonus.
The subquery will determine the lowest bonus and it will be compared with the bonuses of
all employees. If the bonus of an employee matches the value provided by the subquery,
the result of the predicate is true and the row is returned.
A basic predicate is one that uses single value comparison operator (=, <, >, or any
combination thereof). A subquery in a basic predicate must not return more than one value.

7-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Subquery Using IN
SELECT FIRSTNME, LASTNAME, EMPNO
FROM EMPLOYEE
List the names and employee
numbers of employees who are WHERE EMPNO IN (SELECT MGRNO
FROM DEPARTMENT)
managers of a department
Final result Result of subquery

FIRSTNME LASTNAME EMPNO


000010
CHRISTINE HAAS 000010
MICHAEL THOMPSON 000020 000020

SALLY KWAN 000030 000030

JOHN GEYER 000050 000050

IRVING STERN 000060 000060

EVA PULASKI 000070 000070

EILEEN HENDERSE 000090 000090


N 000100
THEODORE SPENSER 000100 -
© Copyright IBM Corporation 2007

Figure 7-19. Subquery Using IN CF124.1

Notes:
IN and NOT IN can be used to compare with a list of values. IN means that for the condition
to evaluate TRUE, the value in the first operand (EMPNO in the example) must be equal to
at least one of the values in the list returned by the subquery.

© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-7


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

Variations on Predicates

SELECT EMPNO, LASTNAME, WORKDEPT, JOB


FROM EMPLOYEE
WHERE (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

© Copyright IBM Corporation 2007

Figure 7-20. Variations on Predicates CF124.1

Notes:
In later releases of DB2 UDB it is possible to use the syntax illustrated in this WHERE
clause. A list of items enclosed in parenthesis can be compared with a list of values, also
enclosed in parenthesis, on the right hand side of the comparison operator. Both lists must
contain the same number of items and the items must be data type compatible. The
comparison operator must be equal (=) or not equal (<>).
DB2 UDB will rewrite the WHERE clause to the equivalent of:
WHERE WORKDEPT = 'D21' AND JOB = 'CLERK'
Check the reference manuals for your environment to determine if the syntax is supported.

7-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Subquery Using IN

List the people in Smith's SELECT FIRSTNME, LASTNAME,


department that have the WORKDEPT, JOB
same job as Smith FROM EMPLOYEE
WHERE (WORKDEPT, JOB) IN
(SELECT WORKDEPT, JOB
FROM EMPLOYEE
WHERE LASTNAME = '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
© Copyright IBM Corporation 2007

Figure 7-21. Subquery Using IN CF124.1

Notes:
Later releases of DB2 UDB support the above syntax with a list of items enclosed in
parenthesis compared with a multiple value comparison operator to a subquery returning
zero, one or more rows with the same number of items as in the list on the left. The
comparison operator must be IN or NOT IN, even if the subquery returns only one row.

© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-9


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

Subquery Using NOT IN


DEPARTMENT Table
DEPTNO DEPTNAME
Which departments
A00 SPIFFY COMPUTER SERVICE
do not have projects
B01 PLANNING
assigned to them? C01 INFORMATION CENTER
... ...

SELECT DEPTNO, DEPTNAME


FROM DEPARTMENT
WHERE DEPTNO NOT IN (SELECT DEPTNO
FROM PROJECT
WHERE DEPTNO IS NOT NULL)

Result of Subquery
Final Result B01
DEPTNO DEPTNAME C01
D01
A00 SPIFFY COMPUTER SERVICE
D11
D21
E01
E11
E21
© Copyright IBM Corporation 2007

Figure 7-22. Subquery Using NOT IN CF124.1

Notes:
The subquery in the example builds a list of the DEPTNO values for every department of
the PROJECT table. The outer query determines the department number and department
name of any department whose department number is NOT in the list returned by the
subquery. In other words, the query is reporting on departments which do not have
projects.
The IN predicate, when used with a subquery, enables the outer query to compare the
values in a column of the outer table with a list of values provided by the subquery.
For an IN predicate, if any of the non-null values returned by the subquery match any of the
non-null values of the column being searched in the outer query, the rows in the outer
query that contain the matching value will appear in the final result set. Nulls in the
subquery result will never match nulls in the outer query result.
When the IN is prefaced with a NOT, as in the example, the subquery should be written to
return only non-null values. Then, all of the rows of the outer query that do not match any of
the values returned by the subquery will appear in the result set. If the NOT IN subquery
returns a null, the outer query will always produce an empty result set!

7-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Subquery within HAVING Clause

I need a list of the departments whose


average salary for non-managers is higher
than the company-wide average for
non-managers. The department with the
highest average should be listed first.

SELECT WORKDEPT, AVG(SALARY) AS AVG_WORKDEPT


FROM EMPLOYEE
WHERE JOB <> 'MANAGER'
GROUP BY WORKDEPT
HAVING AVG(SALARY) > (SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE JOB <> 'MANAGER')
ORDER BY AVG_WORKDEPT DESC

Final Result
WORKDEPT AVG_WORKDEPT Result of Subquery
A00 42833.33333333 25188.80000000
C01 26110.00000000
© Copyright IBM Corporation 2007

Figure 7-23. Subquery within HAVING Clause CF124.1

Notes:
Subqueries can be also used in a HAVING condition for GROUP values.

© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-11


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

Restrictions/Reminders
Subqueries
ƒ Must be on right side of search condition when used
ƒ in WHERE clause or in HAVING clause
ƒ Must be enclosed in parentheses
ƒ Can return single or multiple values
ƒ Number of values subquery can return must be compatible
with operator in outer SELECT
ƒ The subquery must return the same number of items as in the
list to which it is compared

© Copyright IBM Corporation 2007

Figure 7-24. Restrictions/Reminders CF124.1

Notes:

7-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Checkpoint

1. True or False? Subqueries can be used in WHERE or


HAVING clauses of a SELECT.
2. If you want to list the employees whose salary is the highest,
the outer query's WHERE clause may be coded:
a. WHERE SALARY > (SELECT SALARY FROM EMPLOYEE..)
b. WHERE SALARY = (SELECT MAX(SALARY) FROM
EMPLOYEE..)
c. WHERE SALARY > ALL (SELECT SALARY FROM
EMPLOYEE..)

3. What is the keyword taught in this topic that compares a


single value to a set of values returned by a subquery,
looking for a match?

© Copyright IBM Corporation 2007

Figure 7-25. Checkpoint CF124.1

Notes:
Please write down your answers below:
1.
2.
3.

© Copyright IBM Corp. 1999, 2007 Unit 7. Using Subqueries 7-13


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

Unit Summary
Having completed this unit, you should be able to:
ƒ Use subqueries in WHERE and HAVING clauses
ƒ Code subqueries using basic predicates
ƒ Code subqueries using IN

© Copyright IBM Corporation 2007

Figure 7-26. Unit Summary CF124.1

Notes:

7-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty Unit 8. Maintaining Data

What This Unit Is About


Along with the SELECT statement, the SQL Data Manipulation
Language (DML) has three additional SQL statements. These are
used to add rows to a table (INSERT), modify data within existing rows
(UPDATE), and remove rows (DELETE).

What You Should Be Able to Do


After completing this unit, you should be able to:
• Create a simple table for testing DML statements
• Create a simple view
• Insert rows into a table
• Update data in a table
• Delete rows from a table
• Drop a table

How You Will Check Your Progress


Accountability:
• Checkpoint
• Machine labs

© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-1


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

Unit Objectives
After completing this unit, you should be able to:
ƒ Create a simple table to test DML statements
ƒ Create a view
ƒ Insert rows into a table
ƒ Update data in a table
ƒ Delete rows from a table
ƒ Drop a table

© Copyright IBM Corporation 2007

Figure 8-27. Unit Objectives CF124.1

Notes:
Creating tables is normally done by database administrators. For test purposes, it could be
helpful to create a simple test table by yourself.
After the test table has been created, INSERT, UPDATE, and DELETE statements can be
used to add rows, change rows, and remove rows.

8-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty 8.1 Maintaining Data

© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-3


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

TESTEMP Table

EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS

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-04 38250.00 800.00
000050 GEYER E01 1949-08-17 40175.00 800.00
000111 SMITH C01 1998-06-25 25000.00 -

© Copyright IBM Corporation 2007

Figure 8-28. TESTEMP Table CF124.1

Notes:
The visual shows the contents of the TESTEMP table. This table will be the basis for the
exercises of this unit.

8-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Create Table TESTEMP

CREATE TABLE TESTEMP


(EMPNO CHAR(6) NOT NULL,
LASTNAME VARCHAR(15) NOT NULL,
WORKDEPT CHAR(3) ,
HIREDATE DATE ,
SALARY DECIMAL(9,2) ,
BONUS DECIMAL(9,2) )
-- IN DB_NAME.TS_NAME
-- or
-- IN DATABASE DB_NAME
-- or
-- IN TS_NAME
© Copyright IBM Corporation 2007

Figure 8-29. Create Table TESTEMP CF124.1

Notes:
This CREATE TABLE statement creates the TESTEMP table.
In addition to the column definitions, an IN clause may be required. The format of the IN
clause depends on the environment.
z/OS:
IN DB_NAME.TS_NAME - Table must be created in the named table space
IN DATABASE DB_NAME - If a database DB_NAME has been provided, and the table is
to be created in a table space which will be created by the system in this database.
No IN clause if the table is to be created in the default database. This is almost never
allowed by administrators in a z/OS environment.

Linux, UNIX, and Windows:


IN TS_NAME - If a table space TS_NAME has been provided and the table should be
created in this table space.

© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-5


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

No IN clause if a default table space has been provided and the table should be created in
the default table space.

iSeries: the IN clause is not used.


Databases or table spaces are generally provided by a database administrator.

8-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Create View PERSINFO

CREATE VIEW PERSINFO AS


SELECT EMPNO, LASTNAME,
SALARY AS YEAR_SAL
FROM TESTEMP
WHERE WORKDEPT = 'C01'

SELECT *
FROM PERSINFO

EMPNO LASTNAME YEAR_SAL


000030 KWAN 38250.00
000111 SMITH 25000.00

© Copyright IBM Corporation 2007

Figure 8-30. Create View PERSINFO CF124.1

Notes:
This CREATE VIEW statement describes a part of the base table, consisting of employee
number, last name, and yearly salary of all employees in department C01.
The AS clause in the subselect enables you to specify column names in the view different
from the column names in the referenced table. In the above example, "SALARY AS
YEAR_SAL" is used to rename the SALARY column in the base table TESTEMP to
YEAR_SAL in view PERSINFO. Users referencing the view PERSINFO must use the new
column name.
Another possibility for renaming columns in a view is:
CREATE VIEW PERSINFO (EMPNO, LASTNAME, YEAR_SAL)
AS SELECT EMPNO, LASTNAME, SALARY
FROM EMPLOYEE WHERE WORKDEPT = 'C01'
When using this syntax, the number of column names listed in the parentheses must match
the number of the selected columns.

© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-7


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

Users who are authorized to use view PERSINFO will get the listed columns for employees
whose department number is C01. Other data is not visible.

8-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Inserting Rows into the Table

INSERT INTO TESTEMP


VALUES ('000111', 'SMITH', 'C01', '1998-06-25', 25000, NULL)

OR

INSERT INTO TESTEMP


(EMPNO, LASTNAME, WORKDEPT, HIREDATE, SALARY)
VALUES ('000111', 'SMITH', 'C01', '1998-06-25', 25000)

EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS


000111 SMITH C01 1998-06-25 25000.00 -

© Copyright IBM Corporation 2007

Figure 8-31. Inserting Rows into the Table CF124.1

Notes:
Use an INSERT statement to insert a row into a table. Inserting a row via a view inserts the
row into the table on which the view is based. Therefore, inserts via a view are only
possible if the view contains all columns that are defined with NOT NULL without a
DEFAULT value in the base table.
In the first example, the column list is omitted. In this case, a value for each column in the
table or view must be provided in the VALUES clause, in the order they are defined for the
table or the view.
In the second example, a column list is specified. The number of values provided for a row
via the VALUES clause must be equal to the number of column names in the column list.
The first value is inserted in the first column of the list, the second value in the second
column, and so on.

© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-9


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

DB2 UDB for Linux, UNIX, and Windows allows inserting multiple rows in one INSERT
statement; for example:
INSERT INTO TESTEMP
VALUES ('000111', 'SMITH', 'C01', '1998-06-25', 25000, NULL),
('000113', 'JONES', 'C01', '2001-06-25', 25000, NULL),
('000114', 'THOMPSON', 'C01', '2001-06-25', 25000, NULL)

8-10 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Insert Multiple Rows


INSERT INTO TESTEMP
SELECT EMPNO,LASTNAME,WORKDEPT,HIREDATE,SALARY,BONUS
FROM EMPLOYEE
WHERE EMPNO <= '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

© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 8. Maintaining Data 8-11


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

Update Columns (1 of 2)
Before:
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 TESTEMP
SET BONUS = 500,
SALARY = 26000
WHERE EMPNO = '000111'

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
© Copyright IBM Corporation 2007

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'

8-12 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Update Columns (2 of 2)
Before:
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 TESTEMP
SET SALARY = SALARY + 1000
WHERE WORKDEPT = 'C01'

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
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 8. Maintaining Data 8-13


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

Delete Rows
Before:
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

DELETE FROM TESTEMP


WHERE EMPNO = '000111'

After:
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
© Copyright IBM Corporation 2007

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.

8-14 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

Drop Table TESTEMP

Now test table TESTEMP


is no longer needed.

DROP TABLE TESTEMP

VIEW PERSINFO is
automatically dropped
© Copyright IBM Corporation 2007

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 Corp. 1999, 2007 Unit 8. Maintaining Data 8-15


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

Reminders
ƒ You must be authorized to execute CREATE/DROP table
statements
ƒ You must be authorized to execute statements which change
table content
ƒ Dropping a table drops dependent objects
ƒ Search condition in the WHERE clause qualifies rows to be
updated or deleted
ƒ Inserting a row into a view actually inserts the row into the
table on which the view is based
ƒ Updating a row of a view updates the row of the table on which
the view is based
ƒ Omitting the WHERE clause of an UPDATE or DELETE
statement causes all rows of the table or view to be updated or
deleted
© Copyright IBM Corporation 2007

Figure 8-37. Reminders CF124.1

Notes:
See your Database Administrator (DBA) for appropriate authorizations.

8-16 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

Uempty

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

© Copyright IBM Corporation 2007

Figure 8-38. Checkpoint CF124.1

Notes:
Please write down your answers below:
1.
2.

© Copyright IBM Corp. 1999, 2007 Unit 8. Maintaining Data 8-17


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

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

© Copyright IBM Corporation 2007

Figure 8-39. Unit Summary CF124.1

Notes:

8-18 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

AP Appendix A. Checkpoint Solutions


Unit 1

Checkpoint Solutions

1. True
2. Automatic verification of correctness
Date arithmetic
Date, time, timestamp sorting
Extraction of components
3. CHAR/CHARACTER (fixed length)
VARCHAR (variable length)
SMALLINT
INTEGER, INT
DECIMAL(x,y), DEC(x,y)
4. SELECT
INSERT
UPDATE
DELETE
© Copyright IBM Corporation 2006

© Copyright IBM Corp. 1999, 2007 Appendix A. Checkpoint Solutions A-1


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

Unit 2

Checkpoint Solutions

1. False
2. c
3. SELECT, FROM
4. Apostrophes (or single quotes)
5. The keyword LIKE
6. False
They are joined by AND or OR.

© Copyright IBM Corporation 2007

A-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

AP Unit 3

Checkpoint Solutions

1. True
2. b
3. As short names for (qualified) tables
To avoid ambiguity
To establish correlated references

© Copyright IBM Corporation 2007

© Copyright IBM Corp. 1999, 2007 Appendix A. Checkpoint Solutions A-3


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

Unit 4

Checkpoint Solutions

1. False
2. c
3. DECIMAL
SUBSTR
COALESCE
VALUE
YEAR
MONTH
DAY
DAYS
ROUND

© Copyright IBM Corporation 2007

A-4 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

AP Unit 5

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.

© Copyright IBM Corporation 2007

© Copyright IBM Corp. 1999, 2007 Appendix A. Checkpoint Solutions A-5


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

Unit 6

Checkpoint

1. True or False? The results of arbitrary SELECTs can be


combined by means of UNION and ordered to get a new
result.
2. Why or when should you use UNION?
a. When all duplicate rows have to be eliminated.
b. When SELECTs with an arbitrary number of columns should be
combined.

3. Which rules do you have to consider when using UNION?

© Copyright IBM Corporation 2007

A-6 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

AP Unit 7

Checkpoint Solutions

1. True

2. b

3. IN

© Copyright IBM Corporation 2007

© Copyright IBM Corp. 1999, 2007 Appendix A. Checkpoint Solutions A-7


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

Unit 8

Checkpoint Solutions

1. False. The owner of a table has all privileges on the table.


2. a, b

© Copyright IBM Corporation 2007

A-8 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

AP Appendix B. Built-in Functions


Following 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
AVG COUNT COUNT_BIG MAX
MIN STDDEV SUM VARIANCE

Scalar functions
ABS ACOS ASIN ATAN
ATANH ATAN2 BLOB CEILING
CHAR CLOB COALESCE CONCAT
COS COSH DATE DAY
DAYNAME DAYOFWEEK DAYOFWEEK_ISO DAYOFYEAR
DAYS DBCLOB DECIMAL DECRYPT_BIT
DECRYPT_CHAR DEGREES DIGITS DOUBLE_PRECISION
ENCRYPT EXP FLOAT FLOOR
GETHINT GRAPHIC HEX HOUR
IDENTITY_VAL_LOCAL INSERT INTEGER JULIAN_DAY
LCASE LEFT LENGTH LN
LOCATE LOG10 LOWER LTRIM
MICROSECOND MIDNIGHT_SECONDS MINUTE MOD
MONTH MONTHNAME MULTIPLY_ALT NULLIF
POSSTR POWER QUARTER RADIANS
RAISE_ERROR RAND REAL REPEAT
REPLACE RIGHT ROUND RTRIM
SECOND SIGN SIN SINH
SMALLINT SPACE SQRT SUBSTR
TAN TANH TIME TIMESTAMP
TRANSLATE TRUNCATE UCASE UPPER
VALUE VARCHAR VARGRAPHIC WEEK
WEEK_ISO YEAR

© Copyright IBM Corp. 1999, 2007 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.
Student Notebook

B-2 DB2 SQL Workshop © Copyright IBM Corp. 1999, 2007


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

backpg
Back page
®

Vous aimerez peut-être aussi