Вы находитесь на странице: 1из 202

Business

Intelligence

Data
Centre

Cloud

Mobility

Enterprise Computing Solutions

Student Manual

Direccin General de Formacin


CONSEJERA DE EMPLEO,
TURISMO Y CULTURA

Comunidad de Madrid

UNIN EUROPEA
FONDO SOCIAL EUROPEO
El Fondo Social Europeo invierte en tu futuro

EDUCATION
S

V6.0

cover

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Front cover

DB2 SQL Workshop


(Course code CE121)

Student Notebook

pr

Ex

cl

ERC 6.1

IBM certified course material

Student Notebook

Trademarks
IBM and the IBM logo are registered trademarks of International Business Machines
Corporation.
The following are trademarks of International Business Machines Corporation, registered in
many jurisdictions worldwide:
DB2
RACF
400

Informix
z/OS

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

AIX
QMF
zSeries

Linux is a registered trademark of Linus Torvalds 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.

Java and all Java-based trademarks and logos are trademarks or registered trademarks
of Oracle and/or its affiliates.

Ex

cl

Other product and service names might be trademarks of IBM or other companies.

pr

February 2013 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 customers ability to evaluate and integrate them into the customers 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 2013.


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.

V7.0
Student Notebook

Contents
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . vii
Course description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

DB2 SQL Workshop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 01


Course objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 0-2
Agenda . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 0-3
Introductions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 0-4

cl

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


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Introduction to Relational Database Management Systems . . . . . . . . . . . . . . . . . . . . . . 1-3
Relational Database Management System (RDBMS) . . . . . . . . . . . . . . . . . . . . . . . 1-4
Asking for information: RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
SQL Structured Query Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
Table names in DB2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10
Sample Numeric data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Sample Alphanumeric data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
DB2 DATE data type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13
DB2 TIME and TIMESTAMP data types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15
CREATE TABLE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17
NULL characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-18
Authorization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-20
VIEW . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-22
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-24
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-25
Unit 2. Simple SQL Queries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-1
Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
EMPLOYEE table (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
EMPLOYEE table (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
DEPARTMENT table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5
PROJECT table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-6
EMP_ACT (Activity) table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Structure of an SQL query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Retrieving all columns, all rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Retrieving all columns, limited rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Selecting specific columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-11
SELECT with ordered output (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
SELECT with ordered output (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13

pr

Ex

TOC

Copyright IBM Corp. 2013

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

iii

Student Notebook

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Alternate ORDER BY specifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-15


Suppressing duplicate output rows (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-16
Suppressing duplicate output rows (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-17
Retrieving rows by character comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-18
Retrieving rows by numerical comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-20
Comparison operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-21
AND and OR: Principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-22
Multiple conditions: AND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-23
Multiple conditions: OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-24
Multiple conditions: AND/OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-25
Multiple conditions: Parentheses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-26
SELECT with IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-27
SELECT with BETWEEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-28
Retrieving rows: Null comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-29
Partial string search: LIKE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-30
Partial string search: Examples with \'%\' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-31
Partial string search: Example with \'_\' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-32
Negation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-33
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-34
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2-35

cl

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


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-2
Retrieving data from multiple tables (Principle) . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-3
Retrieving data from multiple tables (JOIN) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-4
Correlation names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-6
Joining tables (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-7
Joining tables (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-8
Another way to join . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-9
INNER JOIN example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-10
INNER and OUTER JOINs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-11
JOIN with three tables (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-13
JOIN with three tables (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-14
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-15
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3-16

pr

Ex

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


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-2
Selecting calculated values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-3
Naming result set columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-4
Substitution of NULL values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-5
Arithmetic with NULL values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-6
Calculated values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-7
Rounding and Truncation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-8
Condition on calculated values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-9
Upper and lower case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-10
Substring of strings (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-11
Concatenation of values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4-12

iv

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

4-13
4-14
4-16
4-17
4-18
4-19
4-20
4-21
4-22
4-23
4-24

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Order of precedence in predicate processing . . . . . . . . . . . . . . . . . . . . . . . . . . . .


DB2 DATE, TIME and TIMESTAMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DB2: Different date formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DB2 DATE comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DB2 Special Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DB2 DATE / TIME scalar functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DB2 subtraction of dates (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DB2 subtraction of dates (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
DB2 DATE arithmetic and labeled durations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

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


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
SQL functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3
Column functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4
Sample column functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6
Beware of NULLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7
Column functions based on subset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
GROUP BY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-9
GROUP BY more than one column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-10
GROUP BY, HAVING (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-11
GROUP BY, HAVING (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-12
Examples with HAVING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-13
An important rule for column functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-14
Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-15
SELECT statement: Six clauses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-16
Conceptual execution of a SELECT (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-18
Conceptual execution of a SELECT (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-20
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-22

cl

Unit 6. Union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-1


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Multiple queries: Multiple reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
UNIONing queries together: Single report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-4
UNION rule number 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-5
UNION rule number 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
UNION rule number 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-7
UNION ALL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
UNION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-9
UNION ALL: Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-10
UNION ALL: Example 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11
UNION: Generation of fitting result set rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-12
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-14
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-15

pr

Ex

TOC

Copyright IBM Corp. 2013

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

Student Notebook

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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


Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-2
Result using separate SELECTs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-3
Same result using a subquery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-4
Subquery with basic predicates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-5
Subquery using IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-6
Subquery using NOT IN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-7
Subquery within HAVING clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-9
Restrictions/Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-10
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-11
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-12
Unit 8. Maintaining Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-1
Unit objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-2
TESTEMP table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-3
CREATE TABLE TESTEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-4
CREATE VIEW PERSINFO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-5
Inserting rows into the table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-7
INSERT multiple rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-9
UPDATE columns (1 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-10
UPDATE columns (2 of 2) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-11
DELETE rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-12
Prototyping Change SQL using a unit of work . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-13
DROP TABLE TESTEMP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-15
Reminders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-17
Checkpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-18
Unit summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-19

pr

Ex

cl

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

vi

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

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.

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

DB2
RACF
400

Informix
z/OS

Linux is a registered trademark of Linus Torvalds 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.

Java and all Java-based trademarks and logos are trademarks or registered trademarks
of Oracle and/or its affiliates.

cl

Other product and service names might be trademarks of IBM or other companies.

pr

Ex

TMK

Copyright IBM Corp. 2013

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

vii

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Student Notebook

viii

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V6.0
Student Notebook

Uempty

Course description
DB2 SQL Workshop

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Duration: 2 days
Purpose

This course provides an introduction to the SQL language and applies


to DB2.
This course is appropriate for customers working in all DB2
environments, that is, z/OS, VM/VSE, 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

On completion of this course, you should be able to:

pr

Ex

cl

Objectives

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 and non-correlated subqueries
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. 2013

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

ix

Student Notebook

Contents
Introduction
Simple SQL Queries
Retrieving Data from Multiple Tables
Scalar Functions and Arithmetic
Column Functions and Grouping
UNION
Using Subqueries
Maintaining data

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V6.0
Student Notebook

Uempty

Agenda
Day 1

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

pr

Ex

cl

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

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

xi

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Student Notebook

xii

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

DB2 SQL Workshop

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Uempty

What you should be able to do

After completing 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

Use SQL arithmetic operations

Use scalar and column functions

Use UNION and UNION ALL

Code SQL statements to INSERT, UPDATE and DELETE rows

Code simple CREATE TABLE and CREATE VIEW statements

What this unit is about

This course provides an introduction to the SQL language.

This course is appropriate for customers working in all DB2


environments, that is, z/OS, VM/VSE, Linux, UNIX and Windows.

cl

After completing this course, you should be able to:

Ex

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

Use SQL arithmetic operations

pr

Use scalar and column functions


Use UNION and UNION ALL

Code SQL statements to INSERT, UPDATE and DELETE rows


Code simple CREATE TABLE and CREATE VIEW statements

Copyright IBM Corp. 2013

DB2 SQL Workshop


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

0-1

Student Notebook

Course objectives
After completing this course, you should be able to:

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

Use SQL arithmetic operations

Use scalar and column functions


Use UNION and UNION ALL

Code SQL statements to INSERT, UPDATE and DELETE


rows

Code simple CREATE TABLE and CREATE VIEW statements


Copyright IBM Corporation 2010, 2013

Figure 0-1. Course objectives

CE1216.1

pr

Ex

cl

Notes:

0-2

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Agenda
Day 1

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

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

Copyright IBM Corporation 2010, 2013

Figure 0-2. Agenda

CE1216.1

pr

Ex

cl

Notes:

Copyright IBM Corp. 2013

DB2 SQL Workshop


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

0-3

Student Notebook

Introductions
Name

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Company

Where you live


Your job role

Experience with relational database

Do you meet the course prerequisites?


Class expectations

Copyright IBM Corporation 2010, 2013

Figure 0-3. Introductions

CE1216.1

pr

Ex

cl

Notes:

0-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit 1. Introduction
What this unit is about

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

pr

Ex

cl

Checkpoint questions

Copyright IBM Corp. 2013

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

1-1

Student Notebook

Unit objectives

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 1-1. Unit objectives

CE1216.1

pr

Ex

cl

Notes:

1-2

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Introduction to Relational Database Management


Systems

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Uempty

Copyright IBM Corp. 2013

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

1-3

Student Notebook

Relational Database Management System


(RDBMS)
DEPARTMENT

EMPLOYEE
WORK
DEPT
A00

DEPT DEPTNAME
...
NO
A00 SPIFFY COMPUTER SERVICE DIV.

...

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPNO FIRSTNME

MID
LASTNAME
INIT

000010

CHRISTINE

HAAS

000020

MICHAEL

THOMPSON B01

B01

PLANNING

000030

SALLY

KWAN

C01

C01

INFORMATION CENTER

000050

JOHN

GEYER

E01

D01

DEVELOPMENT CENTER

000060

IRVING

STERN

D11

D11

MANUFACTURING SYSTEMS

000070

EVA

PULASKI

D21

D21

ADMINISTRATION SYSTEMS

PROJECT

Database
A collection of
tables

PROJNO

PROJNAME

DEPT
NO

AD3100

ADMIN SERVICES

D01

AD3110

GENERAL ADMIN SYSTEMS

D21

AD3111

PAYROLL PROGRAMMING

D21

AD3112

PERSONNEL PROGRAMMING D21

AD3113

ACCOUNT PROGRAMMING

D21

IF1000

QUERY SERVICES

C01

...

Copyright IBM Corporation 2010, 2013

Figure 1-2. Relational Database Management System (RDBMS)

CE1216.1

Notes:

cl

Visualize a table as being a set of columns and rows. At the juncture of each column and
row there can be only one value. When working with relational databases, the term
relation is synonymous with table. Therefore, a relational database is a collection of tables,
with all data being stored in rows and columns.

Ex

Every table has a name, and every column has a name.

pr

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. Each entity has a number of attributes or characteristics, which
become the columns in the table. For example, each row in the employee table has an
employee number, first and last name, job title/description, salary, hire date, etc. Each
occurrence (or instance) of an employee becomes a row ... i.e. Bob Jones, Sally Smith, etc.
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.

1-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Asking for information: RDBMS


Return a list of
employees in
department D11
sorted by last name

RDBMS

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPLOYEE
EMPNO LASTNAME

MID
FIRSTNME
INIT

WORKDEPT

PHONENO

000150 ADAMSON

BRUCE

D11

4510

000200 BROWN

DAVID

D11

4501

000050 GEYER

JOHN

E01

6789

000340 GOUNOT

JASON

E21

5698

000010 HAAS

CHRISTINE

A00

3978

SELECT * FROM

EMPLOYEE WHERE
WORKDEPT = 'D11'

ORDER BY LASTNAME

SE L E

CT S

tatem

ent

Copyright IBM Corporation 2010, 2013

Figure 1-3. Asking for information: RDBMS

CE1216.1

Notes:

Human communication RDBMS

End-user, programmer, designer

Human language

Structured Query Language (SQL)

Pool (folders) with the desired information

Tables

Ex

cl

Data requestor

Someone who fetches the information

Integrated search and retrieval functions

pr

A medium for communication - phone, notes, etc. The medium depends on the
environment. The medium could be a program, a query tool, etc.

Copyright IBM Corp. 2013

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

1-5

Student Notebook

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SQL Structured Query Language

COMMIT

ROLLBACK

Copyright IBM Corporation 2010, 2013

Figure 1-4. SQL Structured Query Language

CE1216.1

Notes:

pr

Ex

cl

SQL is the language that is understood by DB2 and other relational database management
systems. SQL has some similarities with human language. By means of SQL, we
communicate with the RDBMS. We tell DB2 what we want, not how DB2 should access the
data. SQL can be used either interactively or embedded in an application program, for
example, COBOL, PL/1, C or Java.

1-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

SQL consists of three "dialects", that is three major categories of statements:


Data Definition Language (DDL) statements are used to define, modify and remove
DB2 objects. DDL is used mostly by database administrators to create objects such as
tables, views and indexes.

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Data Manipulation Language (DML) statements allow users and application programs
to access DB2 data, either by reading or changing the data. DML is issued by users and
applications to retrieve or modify information in DB2 tables.

pr

Ex

cl

Data Control Language (DCL) statements are used to control which users and
applications have access to DB2 data and objects. DCL is used by database
administrators or security personnel to allow or disallow activities in DB2 by granting or
revoking privileges.

Copyright IBM Corp. 2013

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

1-7

Student Notebook

Table
EMPLOYEE
FIRSTNME

MIDINIT LASTNAME

. . . BIRTHDATE

SALARY

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPNO

row

000010

CHRISTINE

HAAS

. . . 1933-08-24

9220

000020

MICHAEL

THOMSON

. . . 1948-02-02

000030

SALLY

KWAN

. . . 1941-05-11

-- - - -

000050

JOHN

GEYER

. . . 1925-09-15

3214

.....

.....

.....

.....

...

LEE

. . . 1941-07-18

000330

WING

column

text column

.....

.....

date column

2030

numeric
column

Copyright IBM Corporation 2010, 2013

Figure 1-5. Table

CE1216.1

Notes:

Tables are commonly used to represent data. They are easy to read. Their interpretation
does not require extensive education. Examples of commonly used data tables are:

cl

Menus

Time tables

Ex

Agendas

Phone books

pr

In a relational database, each table has a name. Each column also has a name, and can
hold a specific type of data, such as character, date, or numeric.

1-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Table names in DB2


Simple Table Name

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Seattle

PARTS

Chicago

Qualified Table Name

Atlanta

PROD. PARTS

Fully-Qualified Table Name

ATLANTA.PROD. PARTS

Copyright IBM Corporation 2010, 2013

Figure 1-6. Table names in DB2

CE1216.1

Notes:

cl

Every table in DB2 must be given a unique name. A table name always has two parts,
separated by a period ... a schema/owner/creator name, followed by the table name.
Optionally, if there are multiple DB2 systems connected together, it may become necessary
to qualify the table with a location name as well. When that is the case, the location name
comes first.

pr

Ex

In the visual above, we refer to PARTS as the simple table name. There could be many
schemas or owners with a DB2 table named PARTS. There could be a TEST.PARTS, a
QA.PARTS and a PROD.PARTS ...a PARTS table each for a Test, a Quality Assurance and
a Production environment. PROD.PARTS, which is referred to as a qualified table name, is
the PARTS table that was created by the schema/owner known as PROD. Finally, if our
company had manufacturing facilities in Atlanta, Chicago and Seattle, and we needed to
maintain a PROD.PARTS table and DB2 system at each of those locations, we could fully
qualify the table name... for example, ATLANTA.PROD.PARTS.
Each simple table name must be unique within a schema. Each qualified table name must
be unique within a location.
Copyright IBM Corp. 2013

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

1-9

Student Notebook

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Names

First character
must be:
A-Z, $, @, #
Remaining:
A-Z, $, @, #, 0-9, _

Every table and


every column
must be named

Table name
unique to
owner/schema

Column
names
unique to
table

Copyright IBM Corporation 2010, 2013

Figure 1-7. Names

CE1216.1

Notes:

Column and table names must conform to the following rules, as shown in the visual
above:

cl

Every table, and every column within a table, must be given a name
Each table name must be unique within a schema

Ex

Each column name must be unique within a table

Any name in DB2 may include the alphabetic characters A - Z, the numbers 0 9, and
the special characters @, #, $, and _ (These are known as the standard characters.)

pr

DB2 allows the user to utilize "non-standard" characters in a name, if that name is
enclosed with double quote marks

A DB2 name may begin with any of the characters in the bullet point above, EXCEPT
for the underscore

1-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Sample Numeric data types


Comment

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Data Type
SMALLINT

Whole numbers from -32768 to +32767

INTEGER

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


+2,147,483,647

BIGINT

Whole numbers from -8 XB to +8 XB

XB = exabytes, 2 raised to the 60th power

DECIMAL(p,s) Decimal numbers

p = precision (total number of digits)

s = scale (number of decimal digits)


Copyright IBM Corporation 2010, 2013

Figure 1-8. Sample Numeric data types

CE1216.1

Notes:

pr

Ex

cl

The visual shows a few of the DB2 supported numeric data types. For complete list of
supported data types in your environment, see the appropriate SQL reference manual for
the respective DB2 platform.

Copyright IBM Corp. 2013

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

1-11

Student Notebook

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Sample Alphanumeric data types

Data Type

Comment

CHAR(n) or

STRING (fixed length)

CHARACTER(n)
VARCHAR(n)

STRING (variable length)

Copyright IBM Corporation 2010, 2013

Figure 1-9. Sample Alphanumeric data types

CE1216.1

Notes:

The visual shows a few of the alphanumeric data types available for the various platforms.
For completeness, see the SQL reference manual for your DB2 environment.

Ex

cl

Fixed character (CHAR) is always stored as a value with X number of bytes. Variable
character (VARCHAR) is stored as the real length of the value for the column, up to a
maximum of X bytes. In order for DB2 to determine the actual length and location of a
VARCHAR, DB2 first creates (at LOAD or INSERT time), and then examines (when
accessing the existing rows) a pointer/displacement within the row for each VARCHAR
column in the row.

pr

The general recommendation is to not use VARCHAR unless the nature of the data stored
in a column is truly going to be variable in nature (such as comments, or another type of
data that could be either quite long or quite short).
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. 2013


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

V7.0
Student Notebook

Uempty

DB2 DATE data type


Comment

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Data Type
DATE
YYYYMMDD

Display / Input Format


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

DATE / TIME / TIMESTAMP data types - input verification


allows arithmetic
sorting
component extraction
Copyright IBM Corporation 2010, 2013

Figure 1-10. DB2 DATE data type

CE1216.1

Notes:

Date data is always stored on DASD as a packed decimal number. However, when date
data is part of the result set, it is displayed in one of the following formats:

cl

USA=US Standard

EUR=European Standard

Ex

ISO=International Standards Organization


JIS=Japanese Industrial Standard

Within an SQL statement, enclose dates in apostrophes. Examples:

pr

'2005-01-15'
'01/15/2005'
'15.01.2005'

Within an SQL statement, all date formats (USA, JIS, EUR, ISO) are accepted as input.
The output display format will default to one of those mentioned above, but can also be
overridden by the application program or query writer.
Copyright IBM Corp. 2013

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

1-13

Student Notebook

DB2 date data supports a wide variety of function, including:


1. Input verification DB2 knows that there are only 28 days in February, except on leap
years.
2. Arithmetic DB2 can add and subtract date values, yielding an output of a duration of
time.

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

3. Sorting Rows in the result set can be sequenced based upon date columns.

pr

Ex

cl

4. Component Extraction DB2 provides scalar functions for extracting the individual
year, month and day portions of a complete date column.

1-14 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

DB2 TIME and TIMESTAMP data types


Comment

TIME

Display / Input Formats

HHMMSS

USA

hh:mm AM or PM

EUR

hh.mm.ss

ISO

hh.mm.ss

JIS

hh:mm:ss

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Data Type

TIMESTAMP

Display / Input Format

YYYYMMDDHHMMSSXXXXXX

yyyy-mm-dd-hh.mm.ss.xxxxxx

where xxxxxx = microseconds

Copyright IBM Corporation 2010, 2013

Figure 1-11. DB2 TIME and TIMESTAMP data types

CE1216.1

Notes:

Time data is always stored on DASD as a packed decimal number. However, when time
data is part of the result set, it is displayed in one of the recognized formats:

cl

USA=US Standard

EUR=European Standard

Ex

ISO=International Standards Organization


JIS=Japanese Industrial Standard

Within an SQL statement, enclose times in apostrophes. Examples:

pr

'21.45.00'
'9:45 PM'
'21:45:00'

Within an SQL statement, all time formats (USA, JIS, EUR, ISO) are accepted as input.
The output display format will default to one of those mentioned above, but can also be
overridden by the application program or query writer.
Copyright IBM Corp. 2013

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

1-15

Student Notebook

DB2 time data supports a wide variety of function, including:


1. Input verification DB2 knows that there are only 60 seconds in an minute, 60 seconds
in an hour..
2. Arithmetic DB2 can add and subtract time values, yielding an output of a duration of
time.

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

3. Sorting Rows in the result set can be sequenced based upon time columns.

pr

Ex

cl

4. Component Extraction DB2 provides scalar functions for extracting the individual
hour, minute and second portions of a larger time data type column.

1-16 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

CREATE TABLE
CREATE TABLE EMPLOYEE
CHAR(6)

NOT NULL,

FIRSTNME

VARCHAR(12)

NOT NULL,

MIDINIT

CHAR(1)

NOT NULL,

LASTNAME

VARCHAR(15)

NOT NULL,

WORKDEPT

CHAR(3)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

( EMPNO

BIRTHDATE

DATE

SALARY

DECIMAL(9,2)

BONUS

DECIMAL(9,2)

COMM

DECIMAL(9,2)

Copyright IBM Corporation 2010, 2013

Figure 1-12. CREATE TABLE

CE1216.1

Notes:

If a table name qualifier is not explicitly supplied in the CREATE TABLE statement, the DB2
environment determines the qualifier to be assigned (e.g. userid.tablename).

cl

For each column, at a minimum, the following must be defined:


Column name

Ex

Data type (and length, if required based upon the data type)

pr

NULL characteristic

Copyright IBM Corp. 2013

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

1-17

Student Notebook

NULL characteristics

Column can be marked as having


an 'unknown value'

NOT NULL

Column must always have a value

NOT NULL WITH


DEFAULT

Column must always have a value


if we do not supply one, a system
or user-defined default value will be
supplied

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

"nullable"

Copyright IBM Corporation 2010, 2013

Figure 1-13. NULL characteristics

CE1216.1

Notes:

cl

NULL has the meaning of "unknown". It does NOT mean blanks for character date and
zeroes for numeric data. Be aware that NULL is the default, so that when you omit the third
parameter in a column definition, that column will allow the NULL value.
There are three null characteristics:

Ex

NOT NULL Column must always have a value.

NOT NULL WITH DEFAULT Column must always have a value - if we don't supply
one, DB2 does.

pr

"nullable" Column can be marked as having an 'unknown value'.

Please note that the way you code a column definition to allow the null attribute is to leave
the third parameter of the column blank. In other words, you simply code the column name
and data type, followed by a comma (delimiting the beginning of the next column to be
defined in the table). In fact, if you key in the word NULL as the third parameter for a
column definition, it results in a syntax error.

1-18 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

It is generally recommended that you do not define columns as being nullable, unless that
is specifically dictated by the database model or the application requirements. Here are the
reasons for avoiding nulls:
1. A null attribute byte takes up one byte of space for each column defined as nullable.

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

2. More importantly, DB2 has to do extra work in navigating the row, and checking the null
attribute byte (CPU cycles)
3. A single null value can invalidate a major arithmetic calculation

4. Programmers usually need to write extra code for error checking and condition handling
when nulls are possibly present.

pr

Ex

cl

When defining a column as NOT NULL WITH DEFAULT, the user may specify a constant
value (which must be compatible with the columns data type - numeric or character) for the
column, if no value is supplied for that column when the row is LOADed or INSERTed into
the table. If the user does not specify a default value, then numeric columns are populated
with zero, character columns are filled with blanks, and TIME, DATE and TIMESTAMP
columns are populated with the CURRENT TIME, CURRENT DATE and CURRENT
TIMESTAMP respectively.

Copyright IBM Corp. 2013

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

1-19

Student Notebook

Authorization

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

GRANT SELECT ON PROJECT TO SALLY

DEPARTMENT

PROJECT

EMPLOYEE

REVOKE SELECT ON PROJECT FROM SALLY


Copyright IBM Corporation 2010, 2013

Figure 1-14. Authorization

CE1216.1

Notes:

cl

A table owner, database administrator or security administrator can give and/or remove
privileges to/from other DB2 users. This is accomplished via the GRANT and REVOKE
statements, which comprise part of the DCL (Data Control Language) subset of the overall
SQL language.
Example

Ex

1+1
=2

pr

Example 1: USERX issues the following SQL GRANT and REVOKE statement:
GRANT SELECT ON PROJECT TO SALLY
Assuming that USERX can GRANT the SELECT privilege on table or view
USERX.PROJECT (we will see views next), this statement gives SALLY permission to
retrieve data (SELECT) from the table or view named USERX.PROJECT.

REVOKE SELECT ON PROJECT FROM SALLY


This statement revokes SALLY's permission to retrieve data (SELECT) from the table or
view named USERX.PROJECT.

1-20 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

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.

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Uempty

Copyright IBM Corp. 2013

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

1-21

Student Notebook

VIEW
z Data security

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

You only see what you should


EMPNO

FIRSTNME

MIDINIT

LASTNAME

WORKDEPT

000150

BRUCE

ADAMSON

D11

4510

000200

DAVID

BROWN

D11

4501

000050

JOHN

GEYER

E01

6789

000340

JASON

GOUNOT

E21

5698

000010

CHRISTINE

A00

3978

HAAS

z Data independence

PHONENO

z Simplification

Copyright IBM Corporation 2010, 2013

Figure 1-15. VIEW

CE1216.1

Notes:

cl

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.
Some of the reasons for using views rather than directly accessing the table include:

Ex

Improved data security.

Improved data independence.

pr

Simplification for the end user


(less data, more user-friendly column names)

Here are some key points to understand about views in DB2:


No additional data is stored.
A view encompasses a subset of columns and rows. The columns returned may be
limited by the SELECT statement, and the rows returned may be limited by the WHERE
clause.
1-22 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

A view may encompass data from several tables and/or other views (joins).
A view may encompass derived data, for example, averages.

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Data manipulation via some views is limited (some views are R/O, that is read only).

Copyright IBM Corp. 2013

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

1-23

Student Notebook

Checkpoint

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 1-16. Checkpoint

CE1216.1

Notes:

Please write down your answers below:


1.

cl

2.

Ex

3.

pr

4.

1-24 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit summary

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 1-17. Unit summary

CE1216.1

pr

Ex

cl

Notes:

Copyright IBM Corp. 2013

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

1-25

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Student Notebook

1-26 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit 2. Simple SQL Queries


What this unit is about

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

pr

Ex

cl

Machine Labs

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-1

Student Notebook

Unit objectives

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

Copyright IBM Corporation 2010, 2013

Figure 2-1. Unit objectives

CE1216.1

pr

Ex

cl

Notes:

2-2

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

EMPLOYEE table (1 of 2)

FIRSTNME
------------

MID
INIT
-------

LASTNAME
---------------

WORK
DEPT
--------

PHONE
NO
-------

HIREDATE
----------

000010

CHRISTINE

HAAS

A00

3978

1965-01-01

000020

MICHAEL

THOMPSON

B01

3476

1973-10-10

000030

SALLY

KWAN

C01

4738

1975-04-05

000050

JOHN

GEYER

E01

6789

1949-08-17

000060

IRVING

STERN

D11

6423

1973-09-14

000070

EVA

PULASKI

D21

7831

1980-09-30

000090

EILEEN

HENDERSON

E11

5498

1970-08-15

000100

THEODORE

SPENSER

E21

0972

1980-06-19

000110

VINCENZO

LUCCHESSI

A00

3490

1958-05-16

000120

SEAN

O'CONNELL

A00

2167

1963-12-05

000130

DOLORES

QUINTANA

C01

4578

1971-07-28

000140

HEATHER

NICHOLLS

C01

1793

1976-12-15

000150

BRUCE

ADAMSON

D11

4510

1972-02-12

000160

ELIZABETH

PIANKA

D11

3782

1977-10-11

000170

MASATOSHI

YOSHIMURA

D11

2890

1978-09-15

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPNO
------

Copyright IBM Corporation 2010, 2013

Figure 2-2. EMPLOYEE table (1 of 2)

CE1216.1

Notes:

The following two visuals display the partial contents of the EMPLOYEE table, showing the
column names and values for the first 15 rows in the table.

cl

Column names and descriptions:

Employee number

FIRSTNME

First name

MIDINIT

Middle initial

LASTNAME

Last name

WORKDEPT

Department number

PHONENO

Phone number

HIREDATE

Hire date

pr

Ex

EMPNO

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-3

Student Notebook

EMPLOYEE table (2 of 2)
ED
LEVEL
-----

JOB
--------

SEX
---

000010

PRES

18

000020

MANAGER

18

000030

MANAGER

20

000050

MANAGER

16

000060

MANAGER

16

000070

MANAGER

000090
000100

BIRTHDATE
----------

SALARY
---------

BONUS
---------

COMM
---------

1933-08-24

52750.00

1000.00

4220.00

1948-02-02

41250.00

800.00

3300.00

1941-05-11

38250.00

800.00

3060.00

1925-09-15

40175.00

800.00

3214.00

1945-07-07

32250.00

500.00

2580.00

16

1953-05-26

36170.00

700.00

2893.00

MANAGER

16

1941-05-15

29750.00

600.00

2380.00

MANAGER

14

1956-12-18

26150.00

500.00

2092.00

000110

SALESREP

19

1929-11-05

46500.00

900.00

3720.00

000120

CLERK

14

1942-10-18

29250.00

600.00

2340.00

000130

ANALYST

16

1925-09-15

23800.00

500.00

1904.00

000140

ANALYST

18

1946-01-19

28420.00

600.00

2274.00

000150

DESIGNER

16

1947-05-17

25280.00

500.00

2022.00

000160

DESIGNER

17

1955-04-12

22250.00

400.00

1780.00

000170

DESIGNER

16

1951-01-05

24680.00

500.00

1974.00

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPNO
------

Copyright IBM Corporation 2010, 2013

Figure 2-3. EMPLOYEE table (2 of 2)

CE1216.1

Notes:

EMPNO*

Employee number (repeated for readability purpose)

cl

Column names and descriptions:

JOB

Job

SEX

Sex

Education level

Ex

EDLEVEL

Date of birth

SALARY

Salary (yearly)

pr

BIRTHDATE

BONUS

Bonus (yearly)

COMM

Commission (yearly)

* Note: EMPNO is repeated on this page to facilitate row location. It is found only once
within the Employee table.

2-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

DEPARTMENT table

DEPTNO
------

DEPTNAME
-----------------------------

MGRNO
------

ADMRDEPT
--------

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

LOCATION
--------

Copyright IBM Corporation 2010, 2013

Figure 2-4. DEPARTMENT table

CE1216.1

Notes:

Column names and descriptions:

Department number

DEPTNAME

Department name

MGRNO

Employee serial number of the responsible manager

Ex

cl

DEPTNO

ADMRDEPT

Department number of the department to which this department reports

LOCATION

Location

pr

The dashes in the MGRNO and LOCATION columns indicate unknown (NULL) values. The
dashes are not physically stored in the table, they are displayed in the result set output by
DB2 to represent NULL.
The dash (or hyphen) character is used for another purpose as input. Two consecutive
dashes in an SQL statement indicate to DB2 that all of the remaining characters to the right
are to be treated as a comment. Upon encountering two consecutive dashes, the SQL
parser skips to the next line to continue its syntax check of the statement.
Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-5

Student Notebook

PROJECT table

PROJNAME
--------------------ADMIN SERVICES
GENERAL ADMIN SYSTEMS
PAYROLL PROGRAMMING
PERSONNEL PROGRAMMING
ACCOUNT PROGRAMMING
QUERY SERVICES
USER EDUCATION
WELD LINE AUTOMATION
W L PROGRAMMING
W L PROGRAM DESIGN
W L ROBOT DESIGN
W L PROD CONT PROGS
OPERATION SUPPORT
OPERATION
GEN SYSTEMS SERVICES
SYSTEMS SUPPORT
SCP SYSTEMS SUPPORT
APPLICATIONS SUPPORT
DB/DC SUPPORT
WELD LINE PLANNING

DEPT
NO
---D01
D21
D21
D21
D21
C01
C01
D01
D11
D11
D11
D11
E01
E11
E01
E21
E21
E21
E21
B01

RESP
EMP
-----000010
000070
000230
000250
000270
000030
000030
000010
000060
000220
000150
000160
000050
000090
000050
000100
000320
000330
000340
000020

PR
STAFF
----6.50
6.00
2.00
1.00
2.00
2.00
1.00
12.00
9.00
2.00
3.00
3.00
6.00
5.00
5.00
4.00
1.00
1.00
1.00
1.00

PRSTDATE
---------1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-02-15
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01
1982-01-01

PRENDATE
---------1983-02-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1982-12-01
1982-12-01
1982-12-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1983-02-01
1982-09-15

MAJ
PROJ
-----AD3100
AD3110
AD3110
AD3110
MA2100
MA2110
MA2110
MA2110
OP1000
OP2000
OP2010
OP2010
OP2010
MA2100

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

PROJNO
-----AD3100
AD3110
AD3111
AD3112
AD3113
IF1000
IF2000
MA2100
MA2110
MA2111
MA2112
MA2113
OP1000
OP1010
OP2000
OP2010
OP2011
OP2012
OP2013
PL2100

Copyright IBM Corporation 2010, 2013

Figure 2-5. PROJECT table

CE1216.1

Notes:

Column names and descriptions:

Project number

PROJNAME
DEPTNO

Responsible department

Project name

RESPEMP

Employee number of the responsible employee

PRSTAFF

Estimated mean staffing

PRSTDATE

Estimated starting date

pr

Ex

cl

PROJNO

PRENDATE

Estimated ending date

MAJPROJ

Major project for a subproject

2-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMP_ACT (Activity) table

Copyright IBM Corporation 2010, 2013

Figure 2-6. EMP_ACT (Activity) table

CE1216.1

Notes:

Column names and descriptions:

Employee number

PROJNO

Project number

ACTNO

Activity number

Ex

cl

EMPNO

Proportion of employees time spent on project

EMSTDATE

Estimated starting date

EMENDATE

Estimated ending date

pr

EMPTIME

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-7

Student Notebook

Structure of an SQL query


- Defines result set columns

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT

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 set rows

Copyright IBM Corporation 2010, 2013

Figure 2-7. Structure of an SQL query

CE1216.1

Notes:

Clauses must be coded in the sequence indicated in the visual. Each SELECT statement
must have a SELECT clause and a FROM clause. The other clauses are optional.

cl

The individual clauses will be discussed in detail later on in this course.

Ex

The SELECT clause defines what information is returned in the result set. Usually the
output consists of data from columns in one or more tables. However, the result data can
be derived from a variety of sources (such as literals, arithmetic expressions, functions,
etc.). These items will be covered in more detail throughout the course.

pr

The default delimiter for an SQL statement is the semicolon (;). If you are submitting a
single query to DB2, then it is not required to end the SQL statement with a semicolon.
However, if you are submitting multiple SQL statements to DB2, then it is mandatory to
separate the queries with the delimiter. It is generally recommended practice to be in the
habit of ending your SQL statements with the delimiter.

2-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Retrieving all columns, all rows

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I need a listing of all


department data.

SELECT *

FROM DEPARTMENT;

DEPTNO DEPTNAME

MGRNO ADMRDEPT LOCATION

A00
B01
C01
D01
D11
D21
E01
E11
E21

000010
000020
000030
000060
000070
000050
000090
000100

SPIFFY COMPUTER SERVICE DIV.


PLANNING
INFORMATION CENTER
DEVELOPMENT CENTER
MANUFACTURING SYSTEMS
ADMINISTRATION SYSTEMS
SUPPORT SERVICES
OPERATIONS
SOFTWARE SUPPORT

A00
A00
A00
A00
D01
D01
A00
E01
E01

Copyright IBM Corporation 2010, 2013

Figure 2-8. Retrieving all columns, all rows

CE1216.1

Notes:

cl

The SELECT followed by an asterisk (*) in the above statement instructs DB2 to display all
columns of the DEPARTMENT table in the output. The absence of a WHERE clause
above tells DB2 that there are no particular criteria that the rows of the table must meet.
Rather, DB2 returns all the rows.

Ex

The output of every SELECT statement is called the result set. For the example above,
the result set includes every column of every row in the DB2 table. The statement SELECT
* FROM DEPARTMENT is the simplest form of the SELECT, since the SELECT and FROM
clauses are mandatory, and all the other clauses of a SELECT statement are optional.

pr

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, and if the table were sizeable,
considerable system resources will be consumed. Therefore, when writing a query,
retrieve only the columns and rows needed to fulfill the requirements of the application.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-9

Student Notebook

Retrieving all columns, limited rows

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

What does the data


look like in the
Department table?

DB2:

DEPTNO
A00
B01
C01
D01
D11

SELECT * FROM DEPARTMENT


FETCH FIRST 5 ROWS ONLY;

DEPTNAME
SPIFFY COMPUTER SERVICE DIV.
PLANNING
INFORMATION CENTER
DEVELOPMENT CENTER
MANUFACTURING SYSTEMS

MGRNO
000010
000020
000030
000060

ADMRDEPT
A00
A00
A00
A00
D01

LOCATION
-

Copyright IBM Corporation 2010, 2013

Figure 2-9. Retrieving all columns, limited rows

CE1216.1

Notes:

pr

Ex

cl

The above statement displays all columns of the DEPARTMENT table but limits the result
set 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 is coming up.

2-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Selecting specific columns

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

For each department, I need


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

SELECT DEPTNO, DEPTNAME, ADMRDEPT


FROM DEPARTMENT;

DEPTNO
A00
B01
C01
D01
D11
D21
E01
E11
E21

DEPTNAME
SPIFFY COMPUTER SERVICE DIV.
PLANNING
INFORMATION CENTER
DEVELOPMENT CENTER
MANUFACTURING SYSTEMS
ADMINISTRATION SYSTEMS
SUPPORT SERVICES
OPERATIONS
SOFTWARE SUPPORT

ADMRDEPT
A00
A00
A00
A00
D01
D01
A00
E01
E01

Copyright IBM Corporation 2010, 2013

Figure 2-10. Selecting specific columns

CE1216.1

Notes:

pr

Ex

cl

The SELECT statement above indicates which (and in which order) columns to include in
the result set. The items in the SELECT list must be separated by commas. Spaces before
and after commas are optional, but usually recommended for readability.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-11

Student Notebook

SELECT with ordered output (1 of 2)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

By the way, the listing


should be sorted by the
department reported to.

SELECT
DEPTNO, DEPTNAME, ADMRDEPT
FROM
DEPARTMENT
ORDER BY ADMRDEPT ASC;

DEPTNO
A00
C01
B01
E01
D01
D11
D21
E21
E11

DEPTNAME
ADMRDEPT
SPIFFY COMPUTER SERVICE DIV.A00
A00
INFORMATION CENTER
A00
PLANNING
A00
SUPPORT SERVICES
A00
DEVELOPMENT CENTER
D01
MANUFACTURING SYSTEMS
D01
ADMINISTRATION SYSTEMS
E01
SOFTWARE SUPPORT
E01
OPERATIONS
Copyright IBM Corporation 2010, 2013

Figure 2-11. SELECT with ordered output (1 of 2)

CE1216.1

Notes:

When the ORDER BY clause is included in a SELECT, DB2 returns the rows of the result
set in the designated sequence. Keep these points in mind:

cl

Resulting rows are sequenced according to the column or columns listed in the
ORDER BY clause.

Ex

The keyword ASC means sort in ascending sequence. This is the default sort
sequence and therefore the keyword ASC may be omitted.
DESC means sort in descending sequence.

pr

Depending on the environment, columns used in the ORDER BY clause must be a part
of the result set. DB2 for LUW requires that the columns in the ORDER BY clause also
appear in the SELECT clause. DB2 for z/OS does not require this.

2-12 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

SELECT with ordered output (2 of 2)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I need the previous listing ordered


first according to the department
to which the department reports
and within that sequence sorted by
the department number in
descending order

SELECT
FROM

DEPTNO, DEPTNAME, ADMRDEPT


DEPARTMENT

ORDER BY ADMRDEPT ASC, DEPTNO DESC;

DEPTNO
E01
D01
C01
B01
A00
D21
D11
E21
E11

DEPTNAME
SUPPORT SERVICES
DEVELOPMENT CENTER
INFORMATION CENTER
PLANNING
SPIFFY COMPUTER SERVICE DIV.
ADMINISTRATION SYSTEMS
MANUFACTURING SYSTEMS
SOFTWARE SUPPORT
OPERATIONS

ADMRDEPT
A00
A00
A00
A00
A00
D01
D01
E01
E01

Copyright IBM Corporation 2010, 2013

Figure 2-12. SELECT with ordered output (2 of 2)

CE1216.1

Notes:

More things to keep in mind regarding the ORDER BY clause:

Ex

cl

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

pr

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.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-13

Student Notebook

Be cognizant of the collating sequence of the coded character set in your environment
(ASCII, EBCDIC, Unicode, etc.), as this will affect the result set.

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

A selected column can be identified by the column name or by an integer, referencing


the columns relative position within the selection list.

2-14 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Alternate ORDER BY specifications

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 2-13. Alternate ORDER BY specifications

CE1216.1

Notes:

cl

The SELECT statement above includes an ORDER BY clause to sequence the rows in the
result set by WORKDEPT in ascending order, then within WORKDEPT by JOB in
ascending order, then within JOB by LASTNAME in ascending order, and finally by SEX in
descending order.

Ex

A selected column can be identified by the column name or by an integer, referencing the
columns relative position within the selection list. The bottom half of the visual above
shows some of the many alternative ways of coding the ORDER BY clause that would all
result in the same sequencing of the rows in the output result set.

pr

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

Unit 2. Simple SQL Queries


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

2-15

Student Notebook

Suppressing duplicate output rows (1 of 2)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Now, I want to know the


different jobs performed
by the employees.

SELECT DISTINCT JOB

SELECT JOB
FROM EMPLOYEE

FROM EMPLOYEE;

ORDER BY JOB;

JOB
ANALYST
CLERK
DESIGNER
FIELDREP
MANAGER
OPERATOR
PRES
SALESREP

JOB
ANALYST
ANALYST
CLERK
CLERK
CLERK
CLERK
.
.

Copyright IBM Corporation 2010, 2013

Figure 2-14. Suppressing duplicate output rows (1 of 2)

CE1216.1

Notes:

cl

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

pr

Ex

There are different ways to retrieve the information required in the visual above. The query
on the left returns duplicate result set rows, so that the result set shows some jobs multiple
times. However, we want all jobs listed only once. To achieve this, we add the keyword
DISTINCT, as is shown in the right-hand query.

2-16 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Suppressing duplicate output rows (2 of 2)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Also, I need a listing of the


job distribution by department.

SELECT WORKDEPT, JOB


FROM EMPLOYEE
ORDER BY WORKDEPT, JOB;

SELECT DISTINCT WORKDEPT, JOB


FROM EMPLOYEE
ORDER BY WORKDEPT, JOB;

WORKDEPT
A00
A00
A00
B01
C01
C01
C01
D11
D11
D11
D11
D11
D11

WORKDEPT
A00
A00
A00
B01
C01
C01
D11
D11
D21
D21
E01
E11
E11
E21
E21

JOB
CLERK
PRES
SALESREP
MANAGER
ANALYST
ANALYST
MANAGER
DESIGNER
DESIGNER
DESIGNER
DESIGNER
DESIGNER
DESIGNER

.
.

.
.

JOB
CLERK
PRES
SALESREP
MANAGER
ANALYST
MANAGER
DESIGNER
MANAGER
CLERK
MANAGER
MANAGER
MANAGER
OPERATOR
FIELDREP
MANAGER

Copyright IBM Corporation 2010, 2013

Figure 2-15. Suppressing duplicate output rows (2 of 2)

CE1216.1

Notes:

Ex

cl

Here is an example using DISTINCT for more than one column. In the query on the right,
the DISTINCT keyword causes each combination of WORKDEPT and JOB found in the
table to be output only once. The query on the left does not contain the DISTINCT
keyword, so an output row is generated for each and every row in the entire table, including
duplicates of the combinations of WORKDEPT and JOB. For instance, there are two
analysts in department C01, and multiple designers in department D11.
Keep in mind the following information regarding DISTINCT:

pr

DISTINCT eliminates all rows that contain duplicate data in the set of columns
specified in the SELECT clause.

DISTINCT refers to the result set row.


DISTINCT cannot be used more than once within the scope of the SELECT statement.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-17

Student Notebook

Retrieving rows by character comparison

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I need a list of the


departments reporting to
department A00.

SELECT
FROM
WHERE

DEPTNO
A00
B01
C01
D01
E01

DEPTNO, ADMRDEPT
DEPARTMENT
ADMRDEPT = 'A00;

ADMRDEPT
A00
A00
A00
A00
A00

Copyright IBM Corporation 2010, 2013

Figure 2-16. Retrieving rows by character comparison

CE1216.1

Notes:

cl

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 set. A WHERE clause can have one or
more predicates, which are tests, or selection criteria or conditions applied to the rows, in
order to determine whether or not they will be included in the result set.

pr

Ex

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.

2-18 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Things to know about the WHERE clause:


The SELECT list need not include the columns used in the WHERE clause.
When making comparisons to character or data/time data, the values must be enclosed
in apostrophes (single quotes).

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

When making comparisons to numeric data, the values must NOT be enclosed in
apostrophes.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-19

Student Notebook

Retrieving rows by numerical comparison

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I want the last name and


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

SELECT
FROM
WHERE

LASTNAME
KWAN
LUCCHESSI

LASTNAME, EDLEVEL
EMPLOYEE
EDLEVEL >= 19;

EDLEVEL
20
19

Copyright IBM Corporation 2010, 2013

Figure 2-17. Retrieving rows by numerical comparison

CE1216.1

Notes:

pr

Ex

cl

Here is an example of a WHERE clause whose predicate is checking for numeric values.
As stated on the previous page, for numeric columns (for example, INTEGER, SMALLINT
or DECIMAL) the values to be compared must not be enclosed in apostrophes (single
quotes).

2-20 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Comparison operators

SELECT

FROM

EMPLOYEE

WHERE

-- operator means:

SALARY = 20000 -- equal to

OR

SALARY <> 20000 -- not equal to

OR

SALARY >

OR

SALARY >= 20000 -- greater than or equal to

OR

SALARY <

OR

SALARY <= 20000 -- less than or equal to

20000 -- greater than

20000 -- less than

Copyright IBM Corporation 2010, 2013

Figure 2-18. Comparison operators

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

pr

Ex

cl

Two hyphens side by side (no space between them) represent a comment marker. Text to
the right of the comment marker is ignored.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-21

Student Notebook

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

AND and OR: Principle

Y
Y

Yellow AND Oval

Y
Y

Y
Y

Yellow OR Oval

Y
Y

Y
Y

Copyright IBM Corporation 2010, 2013

Figure 2-19. AND and OR: Principle

CE1216.1

Notes:

pr

Ex

cl

If a query requires multiple tests to determine which rows should be returned, then the
predicates are linked by the Boolean operators, AND and OR. When the predicates are
combined via AND, for a row to qualify, both predicates must be true. For predicates
combined via OR, rows qualify if either predicate is true.

2-22 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Multiple conditions: AND

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

List employee number, job, and


education level for analysts with
an education level of 16.

SELECT
FROM
WHERE
AND

EMPNO
000130

JOB
ANALYST

EMPNO, JOB, EDLEVEL


EMPLOYEE
JOB = 'ANALYST'
EDLEVEL = 16;

EDLEVEL
16

Copyright IBM Corporation 2010, 2013

Figure 2-20. Multiple conditions: AND

CE1216.1

Notes:

pr

Ex

cl

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. It
just so happens that in the EMPLOYEE table, there exist 2 analysts, and 12 employees
with an education level of 16, but there is only one analyst with the specific education level
of 16.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-23

Student Notebook

Multiple conditions: OR

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

List the columns below for


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

SELECT
FROM
WHERE
OR
ORDER BY

EMPNO
000130
000140
000030

JOB
ANALYST
ANALYST
MANAGER

EMPNO, JOB, EDLEVEL


EMPLOYEE
JOB = 'ANALYST'
EDLEVEL = 20
JOB, EMPNO;

EDLEVEL
16
18
20

Copyright IBM Corporation 2010, 2013

Figure 2-21. Multiple conditions: OR

CE1216.1

Notes:

pr

Ex

cl

Rows qualify for further processing if either condition is met. In the above example, all
employees who are analysts (regardless of their education level), and all employees with
an education level of 20 (regardless of their job) are displayed in the result set.

2-24 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Multiple conditions: AND/OR

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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
FROM
WHERE
AND
OR
ORDER BY

EMPNO
000130
000140
000220
000020
000010

JOB
ANALYST
ANALYST
DESIGNER
MANAGER
PRES

EMPNO, JOB, EDLEVEL


EMPLOYEE
JOB = 'ANALYST'
EDLEVEL = 16
EDLEVEL = 18
JOB, EMPNO;

EDLEVEL
16
18
18
18
18

Copyright IBM Corporation 2010, 2013

Figure 2-22. Multiple conditions: AND/OR

CE1216.1

Notes:

pr

Ex

cl

If you combine multiple conditions by AND and OR, AND takes precedence over OR. That
means that the AND is evaluated first, and then the OR. Therefore, the query above
returns those employee who are analysts with an education level of 16, and all employees
(regardless of job) whose education level is 18. Notice that there are 5 rows in the result
set.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-25

Student Notebook

Multiple conditions: Parentheses

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

List the columns below


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

SELECT
FROM
WHERE
AND
OR

EMPNO
000130
000140

JOB
ANALYST
ANALYST

EMPNO, JOB, EDLEVEL


EMPLOYEE
JOB = 'ANALYST'
(EDLEVEL = 16
EDLEVEL = 18);

EDLEVEL
16
18

Copyright IBM Corporation 2010, 2013

Figure 2-23. Multiple conditions: Parentheses

CE1216.1

Notes:

Ex

cl

Search conditions within parentheses are evaluated first, beginning with the innermost set
of parentheses if there are multiple, nested parentheses. For the query above, that means
that the OR condition is checked first because of the parentheses, and then the AND.
Therefore, the query above returns those employee who have and education level of either
16 or 18, AND are analysts. Notice that the results here are different from the previous
query. Here there are only 2 rows in the result set, because there are only two employees
that are analysts with an education level of either 16 or 18.

pr

In some queries with multiple predicates, it may be advantageous to code parentheses


(even if not absolutely required to return the correct result set) for claritys sake. In the lab
there is an excellent example of this principle (Exercise 1, problems 7 and 8), and it is a
recommended practice to code your queries as clearly as possible.

2-26 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

SELECT with IN

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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
FROM
WHERE
ORDER BY

LASTNAME
JEFFERSON
LEE
O'CONNELL
SMITH
SPENSER
LUCCHESSI
KWAN

LASTNAME, EDLEVEL
EMPLOYEE
EDLEVEL IN (14,19,20)
EDLEVEL, LASTNAME;

EDLEVEL
14
14
14
14
14
19
20

Copyright IBM Corporation 2010, 2013

Figure 2-24. SELECT with IN

CE1216.1

Notes:

cl

The IN predicate compares a value with a set of values, which is known as an IN-list. In
essence, the IN predicate is an alternative way of checking for multiple OR conditions. For
example, the following two queries would return the same results set:
1. SELECT NAME, JOB, WORKDEPT FROM EMPLOYEE

Ex

WHERE WORKDEPT = D01 OR WORKDEPT = D11;

2. SELECT NAME, JOB, WORKDEPT FROM EMPLOYEE


WHERE WORKDEPT IN (D01,D11);

pr

The values in an IN-list may be numeric, or alphanumeric, date, or time, but of course they
must match the data type of the column that is being compared to the IN-list of values. For
alphanumeric values, dates, or time data types, each value in the IN-list must be enclosed
within single quotes.
Example:
SELECT * FROM DEPARTMENT WHERE DEPTNO IN ('B01', 'C01', 'D01')
Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-27

Student Notebook

SELECT with BETWEEN

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

List employee number and ed-level


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

SELECT
FROM
WHERE
ORDER BY

EMPNO
000290
000310
000100
000120
000230
000300
000330
000250
000270

EMPNO, EDLEVEL
EMPLOYEE
EDLEVEL BETWEEN 12 AND 15
EDLEVEL;

EDLEVEL
12
12
14
14
14
14
14
15
15

Copyright IBM Corporation 2010, 2013

Figure 2-25. SELECT with BETWEEN

CE1216.1

Notes:

Ex

cl

The BETWEEN predicate determines if a given value lies between two values specified in
ascending order (low value listed first, the higher or equal value must be listed after the
AND). This predicate is an inclusive BETWEEN operation, which means that the exact
low value and high value in the range are included in the result set. Therefore, in the
example query above, DB2 returns those employee rows where the EDLEVEL is exactly
12 and exactly 15, as well as those in between (13 and 14).
The clause

WHERE EDLEVEL BETWEEN 12 AND 15

pr

is equivalent to

WHERE EDLEVEL >= 12 AND EDLEVEL <= 15

Alphanumeric as well as number values can be used in a BETWEEN predicate. For


example:
WHERE WORKDEPT BETWEEN 'A00' AND 'D00'

2-28 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Retrieving rows: Null comparison

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

List number and name of all


departments whose manager
is unknown.

SELECT
FROM
WHERE

DEPTNO
D01

DEPTNAME
DEVELOPMENT CENTER

DEPTNO, DEPTNAME, MGRNO


DEPARTMENT
MGRNO IS NULL;

MGRNO
-

Copyright IBM Corporation 2010, 2013

Figure 2-26. Retrieving rows: Null comparison

CE1216.1

Notes:

cl

The IS NULL predicate enables a user or application to test for the null value (unknown
value). 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.

pr

Ex

As a reminder, when a hyphen appears in the output display, it is usually indicative of the
NULL value, rather than an actual hyphen character.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-29

Student Notebook

Partial string search: LIKE

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

List the last name for all


employees whose last name
starts with the letter G.

SELECT
FROM
WHERE

LASTNAME
EMPLOYEE
LASTNAME LIKE 'G% ;

LASTNAME
GEYER
GOUNOT

Copyright IBM Corporation 2010, 2013

Figure 2-27. Partial string search: LIKE

CE1216.1

Notes:

cl

The LIKE predicate searches for character strings that match a certain pattern. This is
sometimes referred to as partial string search, masking, or wild-carding. In SQL there are
two special characters that are used to enable the user to specify the pattern match that is
desired:

Ex

In the pattern the percent sign ('%') serves as place holder for a string of zero or more
arbitrary characters.

In the pattern the underscore (_) serves as place holder for exactly one arbitrary
characters.

pr

The above SELECT searches for names beginning with the letter 'G'.

2-30 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Partial string search: Examples with '%'


LASTNAME
EMPLOYEE
LASTNAME LIKE '%SON ;

LASTNAME
THOMPSON
HENDERSON
ADAMSON
JEFFERSON
JOHNSON

SELECT
FROM
WHERE

LASTNAME
EMPLOYEE
LASTNAME LIKE '%M%N% ;

LASTNAME
THOMPSON
ADAMSON
MARINO

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE

Copyright IBM Corporation 2010, 2013

Figure 2-28. Partial string search: Examples with \'%\'

CE1216.1

Notes:

cl

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 (because with the CHAR data type,
any unused bytes in the fixed-length column are blanks).

pr

Ex

The second example displays all names containing 'M' and 'N' in that sequence. Names
beginning with 'M' and ending with 'N' (such as MARTIN) would also be displayed. Names
where an M immediately precedes an N would also be displayed (such as AMNESTY).
A name such as DENMARK would not be selected, since the N precedes the M.

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-31

Student Notebook

Partial string search: Example with '_'

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I need a listing of all employee


last names whose second
character is the letter 'C'.

SELECT
FROM
WHERE

LASTNAME
EMPLOYEE
LASTNAME LIKE '_C% ;

LASTNAME
SCOUTTEN
SCHNEIDER

Copyright IBM Corporation 2010, 2013

Figure 2-29. Partial string search: Example with \'_\'

CE1216.1

Notes:

cl

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.

pr

Ex

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.

2-32 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Negation

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I need a listing of all departments


except those with a department
number starting with 'D'.

SELECT
FROM
WHERE

DEPTNO
A00
B01
C01
E01
E11
E21

DEPTNO, DEPTNAME
DEPARTMENT
DEPTNO NOT LIKE 'D% ;

DEPTNAME
SPIFFY COMPUTER SERVICE DIV.
PLANNING
INFORMATION CENTER
SUPPORT SERVICES
OPERATIONS
SOFTWARE SUPPORT

Copyright IBM Corporation 2010, 2013

Figure 2-30. Negation

CE1216.1

Notes:

In the example above, the query retrieves department information for all departments that
do not begin with the letter D.

cl

All predicates can be negated by preceding the entire predicate with the word NOT. For
example:

pr

Ex

WHERE NOT SALARY > 2000

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-33

Student Notebook

Checkpoint

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 set 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. True or False? WHERE clause predicates must be
separated from each other by commas.

Copyright IBM Corporation 2010, 2013

Figure 2-31. Checkpoint

CE1216.1

Notes:

Please write your answers here.


1.

cl

2.

Ex

3.
4.

pr

5.

2-34 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit summary

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Having completed 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

Copyright IBM Corporation 2010, 2013

Figure 2-32. Unit summary

CE1216.1

pr

Ex

cl

Notes:

Copyright IBM Corp. 2013

Unit 2. Simple SQL Queries


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

2-35

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Student Notebook

2-36 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit 3. Retrieving Data from Multiple Tables


What this unit is about

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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


Checkpoint questions

pr

Ex

cl

Machine labs

Copyright IBM Corp. 2013

Unit 3. Retrieving Data from Multiple Tables


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

3-1

Student Notebook

Unit objectives

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 3-1. Unit objectives

CE1216.1

pr

Ex

cl

Notes:

3-2

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Retrieving data from multiple tables (Principle)


PROJECT
DEPTNO

PROJNAME

...

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

PROJNO
AD3100
AD3110
AD3111
AD3112

ADMIN SERVICES
GENERAL ADMIN SYSTEMS
PAYROLL PROGRAMMING
PERSONNEL PROGRAMMING

D01
D21
D21
D21

DEPARTMENT
DEPTNO
A00
C01
D01
D21

...

DEPTNAME

SPIFFY COMPUTER SERVICE DIV.


INFORMATION CENTER
DEVELOPMENT CENTER
ADMINISTRATION SYSTEMS

Copyright IBM Corporation 2010, 2013

Figure 3-2. Retrieving data from multiple tables (Principle)

CE1216.1

Notes:

pr

Ex

cl

For each department number in the PROJECT table, one row exists in the DEPARTMENT
table. By looking at the data within the two tables we can see how a row in one table is
related to a row in the other table. The rows are related by the values in the DEPTNO
columns.

Copyright IBM Corp. 2013

Unit 3. Retrieving Data from Multiple Tables


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

3-3

Student Notebook

Retrieving data from multiple tables (JOIN)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

For every project, list the project number, project name, and the
number and name of the department responsible for the project.

SELECT
FROM
WHERE
ORDER BY

PROJNO
AD3100
AD3110
AD3111
AD3112
AD3113
...

PROJNO, PROJNAME, PROJECT.DEPTNO, DEPTNAME


PROJECT, DEPARTMENT
PROJECT.DEPTNO=DEPARTMENT.DEPTNO -- JOIN PREDICATE
PROJNO;

PROJNAME
ADMIN SERVICES
GENERAL ADMIN SYSTEMS
PAYROLL PROGRAMMING
PERSONNEL PROGRAMMING
ACCOUNT PROGRAMMING
...

...

DEPTNO
D01
D21
D21
D21
D21
...

DEPTNAME
DEVELOPMENT CENTER
ADMINISTRATION SYSTEMS
ADMINISTRATION SYSTEMS
ADMINISTRATION SYSTEMS
ADMINISTRATION SYSTEMS

Avoid a Cartesian Product!


Copyright IBM Corporation 2010, 2013

Figure 3-3. Retrieving data from multiple tables (JOIN)

CE1216.1

Notes:

cl

You can use the SELECT statement to produce reports that contain information from
multiple tables. This is commonly referred as a join. In order to join two tables, specify the
following:
the columns you want to be displayed in the SELECT clause,

Ex

the table names in the FROM clause, and


the join predicate in the WHERE clause.

pr

Because DEPTNO is a column name in both the DEPARTMENT and PROJECT tables, 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 qualified in order to avoid potential errors.
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
undesirable result. The result set, which consists of all the combinations of joining qualified
rows from all tables, does not normally satisfy a legitimate business requirement.

3-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Furthermore, the join operation itself consumes considerable system resources, thereby
potentially degrading the performance of other uses in the system.

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Uempty

Copyright IBM Corp. 2013

Unit 3. Retrieving Data from Multiple Tables


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

3-5

Student Notebook

Correlation names
SELECT

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

P.PROJNO, P.PROJNAME, P.DEPTNO, D.DEPTNAME

FROM

PROJECT P,

WHERE

P.DEPTNO = D.DEPTNO

ORDER BY

P.PROJNO;

PROJNO
AD3100
AD3110
AD3111
AD3112
AD3113
...

DEPARTMENT D

PROJNAME
ADMIN SERVICES
GENERAL ADMIN SYSTEMS
PAYROLL PROGRAMMING
PERSONNEL PROGRAMMING
ACCOUNT PROGRAMMING
...

DEPTNO
D01
D21
D21
D21
D21
...

DEPTNAME
DEVELOPMENT CENTER
ADMINISTRATION SYSTEMS
ADMINISTRATION SYSTEMS
ADMINISTRATION SYSTEMS
ADMINISTRATION SYSTEMS
...

Copyright IBM Corporation 2010, 2013

Figure 3-4. Correlation names

CE1216.1

Notes:

cl

Correlation names can be defined in the FROM clause of any query. A correlation name is
a substitute (usually abbreviated) name that you give to a table in an SQL SELECT
statement.

pr

Ex

In the FROM clause, if you code a separate character string after the real table name (and
before the comma delimiting the name of the next table accessed), that becomes a
correlation name. The other parts of your query can now refer to the abbreviated table
name, rather than the real table name. If you give a table a correlation name, then that
correlation name must be used to qualify any column names occuring in the query, rather
than using the actual table name to qualify the column. Correlation names only exist
within the query in which they are defined. They are not recognized outside their own
query.
The SQL statement above shows the use of correlation names and thereby follows the
recommendation to qualify all column names in a join.

3-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Joining tables (1 of 2)
...

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Display the department name, and the


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

DEPARTMENT

MGRNO . . .

DEPTNO DEPTNAME
A00
B01
C01
D01
D11
D21
E01

SPIFFY COMPUTER SERVICE DIV. 000010


000020
PLANNING
000030
INFORMATION CENTER
-----DEVELOPMENT CENTER
000060
MANUFACTURING SYSTEMS
000070
ADMINISTRATION SYSTEMS
000050
SUPPORT SERVICES

EMPLOYEE

EMPNO FIRSTNME
000010
000020
000030
000050
000060
000070
000090
000100

CHRISTINE
MICHAEL
SALLY
JOHN
IRVING
EVA
EILEEN
THEODORE

MIDINIT LASTNAME
I
L
A
B
F
D
W
Q

...

HAAS
THOMPSON
KWAN
GEYER
STERN
PULASKI
HENDERSON
SPENSER

Copyright IBM Corporation 2010, 2013

Figure 3-5. Joining tables (1 of 2)

CE1216.1

Notes:

pr

Ex

cl

The DEPARTMENT and EMPLOYEE tables can be joined by another set of columns in the
respective tables: the MGRNO column in the DEPARTMENT table contains the employee
number (EMPNO in the EMPLOYEE table) of the manager of the department.

Copyright IBM Corp. 2013

Unit 3. Retrieving Data from Multiple Tables


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

3-7

Student Notebook

Joining tables (2 of 2)
DEPTNAME, MGRNO, LASTNAME
DEPARTMENT, EMPLOYEE
MGRNO = EMPNO
DEPTNO = D21 ;

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE
AND

OR

SELECT
FROM

DEPTNAME, MGRNO, LASTNAME


DEPARTMENT INNER JOIN EMPLOYEE
ON MGRNO = EMPNO
DEPTNO = D21 ;

WHERE

DEPTNAME

MGRNO

LASTNAME

ADMINISTRATION SYSTEMS

000070

PULASKI

Copyright IBM Corporation 2010, 2013

Figure 3-6. Joining tables (2 of 2)

CE1216.1

Notes:

cl

The query above returns the result set for the business requirement stated on the previous
visual. In this example it is not mandatory to user correlation names, because all of the
column names specified are just in one table or the other, not both. Therefore there are no
ambiguous column references.

Ex

Note that we can use either the older, original join syntax, or the newer syntax.

pr

Here is a summary of the difference between the two syntaxes Instead of separating the table names in
the FROM clause with a comma, the keyword JOIN (or INNER JOIN, they are synonymous) is used. And
instead of the join condition appearing as a predicate in the WHERE clause, there is the ON keyword, which
is an extension of the FROM clause. Either syntax will work for inner joins. Later in this course, we will briefly
introduce outer joins, and the newer syntax is required for outer joins.

3-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Another way to join

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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
FROM
WHERE
AND

EMPNO, LASTNAME, WORKDEPT, DEPTNAME


EMPLOYEE, DEPARTMENT
WORKDEPT = DEPTNO
LASTNAME = 'HAAS'

EMPNO LASTNAME WORKDEPT

DEPTNAME

000010

SPIFFY COMPUTER SERVICE DIV.

HAAS

A00

Copyright IBM Corporation 2010, 2013

Figure 3-7. Another way to join

CE1216.1

Notes:

cl

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 to combine the row for an employee with
the row for the department to which the employee belongs.

Ex

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:

pr

The number of tables minus one (n-1) is minimum number of join predicates needed for the query, ensuring
that there are no un-linked tables.

Copyright IBM Corp. 2013

Unit 3. Retrieving Data from Multiple Tables


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

3-9

Student Notebook

INNER JOIN example


EMPNO, LASTNAME, WORKDEPT, DEPTNAME
EMPLOYEE INNER JOIN
DEPARTMENT
WORKDEPT = DEPTNO
LASTNAME = 'HAAS'

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
ON
WHERE

EMPNO LASTNAME

WORKDEPT DEPTNAME

000010

A00

HAAS

SPIFFY COMPUTER SERVICE DIV.

Copyright IBM Corporation 2010, 2013

Figure 3-8. INNER JOIN example

CE1216.1

Notes:

pr

Ex

cl

There are two types of predicates that may be coded in a query, join predicates and local
predicates. When the JOIN (INNER JOIN) keyword is used in the FROM clause, the join
predicates must be specified the ON keyword extension to the FROM clause. Row
conditions (called local predicates) must be written in a WHERE clause which follows the
ON clause.

3-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

INNER and OUTER JOINs


INNER JOIN

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME


FROM EMPLOYEE INNER JOIN DEPARTMENT
ON WORKDEPT = DEPTNO

LEFT OUTER JOIN

SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME


FROM EMPLOYEE LEFT OUTER JOIN DEPARTMENT
RIGHT OUTER JOIN
ON WORKDEPT = DEPTNO
SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME
FROM EMPLOYEE RIGHT OUTER JOIN DEPARTMENT
ON WORKDEPT = DEPTNO

FULL OUTER JOIN

SELECT EMPNO, LASTNAME, WORKDEPT, DEPTNAME


FROM EMPLOYEE FULL OUTER JOIN DEPARTMENT
ON WORKDEPT = DEPTNO
Copyright IBM Corporation 2010, 2013

Figure 3-9. INNER and OUTER JOINs

CE1216.1

Notes:

Ex

cl

As with all the other examples, the INNER JOIN will retrieve all rows from the EMPLOYEE
table that have corresponding rows on the DEPARTMENT table. 'Corresponding rows'
means that an employee has a WORKDEPT that has a matching entry on DEPTNO. From
this, you can see that it is possible for not all employees to be retrieved - if an employee is
in a department that does not exist on the DEPARTMENT table, then it will not appear in
the result. OUTER JOINs address these rows as well.

pr

LEFT OUTER JOIN would retrieve all rows that are found on the EMPLOYEE
(left-hand) table whether or not they have a matching department. In fact, it combines
employees with no matching department with employees with matching departments
(the latter is an INNER JOIN).

RIGHT OUTER JOIN would retrieve all rows that are found on the DEPARTMENT
(right-hand) table whether or not there are any employees in that department. It
combines therefore departments with no matching employees with employees which do
have employees (the latter is again an INNER JOIN).

Copyright IBM Corp. 2013

Unit 3. Retrieving Data from Multiple Tables


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

3-11

Student Notebook

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

FULL OUTER JOIN is a combination of LEFT and RIGHT OUTER JOINs. It would
retrieve all rows that are found on the EMPLOYEE (left-hand) table whether or not they
have a matching department, plus it would retrieve all rows that are found on the
DEPARTMENT (right-hand) table whether or not there are any employees in that
department. It combines therefore employees with no matching department with
departments with no matching employees with all employees with matching
departments (the last is an INNER JOIN).

3-12 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

JOIN with three tables (1 of 2)


PROJECT
PROJNO

ADMIN SERVICES
GENERAL AD SYSTEMS
PAYROLL PROGRAMMING
PERSONNEL PROGRAMMING
ACCOUNT. PROGRAMMING
QUERY SERVICES

For department D21 list


PROJNO, DEPTNO,
DEPTNAME, MGRNO, and
LASTNAME.

D01
D21
D21
D21
D21
C01

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

AD3100
AD3110
AD3111
AD3112
AD3113
IF1000

DEPTNO . . .

PROJNAME

DEPARTMENT

MGRNO . . .

DEPTNO DEPTNAME
A00
B01
C01
D01
D11
D21
E01

SPIFFY COMPUTER SERVICE DIV. 000010


000020
PLANNING
000030
INFORMATION CENTER
-----DEVELOPMENT CENTER
000060
MANUFACTURING SYSTEMS
000070
ADMINISTRATION SYSTEMS
000050
SUPPORT SERVICES

EMPLOYEE

EMPNO FIRSTNME
000010
000020
000030
000050
000060
000070
000090
000100

CHRISTINE
MICHAEL
SALLY
JOHN
IRVING
EVA
EILEEN
THEODORE

MIDINIT LASTNAME
I
L
A
B
F
D
W
Q

...

HAAS
THOMPSON
KWAN
GEYER
STERN
PULASKI
HENDERSON
SPENSER

Copyright IBM Corporation 2010, 2013

Figure 3-10. JOIN with three tables (1 of 2)

CE1216.1

Notes:

cl

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 departments
manager. This requires joining together the PROJECT, DEPARTMENT and EMPLOYEE
tables.

pr

Ex

To find the name of the department that a project is assigned to, DB2 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 optimizer determines the sequence of the above steps, in order to ensure the
best performance for the query.

Copyright IBM Corp. 2013

Unit 3. Retrieving Data from Multiple Tables


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

3-13

Student Notebook

JOIN with three tables (2 of 2)


PROJNO, P.DEPTNO, DEPTNAME, MGRNO, LASTNAME
PROJECT P,
DEPARTMENT D,
EMPLOYEE E
P.DEPTNO = D.DEPTNO
-- join predicate
D.MGRNO = E.EMPNO
-- join predicate
D.DEPTNO = 'D21'
-- local predicate
PROJNO

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM

WHERE
AND
AND
ORDER BY

PROJNO

DEPTNO DEPTNAME

AD3110
AD3111
AD3112
AD3113

D21
D21
D21
D21

ADMINISTRATION
ADMINISTRATION
ADMINISTRATION
ADMINISTRATION

MGRNO LASTNAME

SYSTEMS
SYSTEMS
SYSTEMS
SYSTEMS

000070
000070
000070
000070

PULASKI
PULASKI
PULASKI
PULASKI

Copyright IBM Corporation 2010, 2013

Figure 3-11. JOIN with three tables (2 of 2)

CE1216.1

Notes:

With three tables being joined together, and the join conditions being on one column, we
need two join predicates (conditions)

pr

Ex

cl

If multiple tables are specified, but no JOIN predicate and no search condition is specified,
the intermediate result 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-14 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Checkpoint

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 3-12. Checkpoint

CE1216.1

Notes:

Please write your answers here:


1.

cl

2.

pr

Ex

3.

Copyright IBM Corp. 2013

Unit 3. Retrieving Data from Multiple Tables


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

3-15

Student Notebook

Unit summary

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 3-13. Unit summary

CE1216.1

pr

Ex

cl

Notes:

3-16 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit 4. Scalar Functions and Arithmetic


What this unit is about

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 and time 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


Checkpoint questions

pr

Ex

cl

Machine labs

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-1

Student Notebook

Unit objectives

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

Copyright IBM Corporation 2010, 2013

Figure 4-1. Unit objectives

CE1216.1

pr

Ex

cl

Notes:

4-2

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Selecting calculated values

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I need a list containing


EMPNO, SALARY, COMM,
and SALARY + COMM
for employees whose salary
is less than $20000,
ordered by employee number

SELECT

EMPNO, SALARY, COMM,


SALARY + COMM
FROM
EMPLOYEE
WHERE
SALARY < 20000
ORDER BY EMPNO;

EMPNO

SALARY

COMM

000210
000250
000260
000290
000300
000310
000320

18270.00
19180.00
17250.00
15340.00
17750.00
15900.00
19950.00

1462.00
1534.00
1380.00
1227.00
1420.00
1272.00
1596.00

19732.00
20714.00
18630.00
16567.00
19170.00
17172.00
21546.00

Copyright IBM Corporation 2010, 2013

Figure 4-2. Selecting calculated values

CE1216.1

Notes:

You can use the following arithmetic operators to calculate values:

cl

addition

subtraction

Ex

multiplication
division

pr

In the result set, notice that for a derived column, such as SALARY+COMM , DB2 does not
display a column name or other heading in the output. We will see how to address this in
the next visual.

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-3

Student Notebook

Naming result set columns


EMPNO, SALARY, COMM, SALARY + COMM AS INCOME
EMPLOYEE
SALARY < 20000
EMPNO;

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE
ORDER BY

EMPNO

SALARY

COMM

INCOME

000210
000250
000260
000290
000300
000310
000320

18270.00
19180.00
17250.00
15340.00
17750.00
15900.00
19950.00

1462.00
1534.00
1380.00
1227.00
1420.00
1272.00
1596.00

19732.00
20714.00
18630.00
16567.00
19170.00
17172.00
21546.00

Copyright IBM Corporation 2010, 2013

Figure 4-3. Naming result set columns

CE1216.1

Notes:

cl

When there is a literal, arithmetic expression or function in the SELECT clause, the result
of those is a derived column value. Derived columns ordinarily have no heading or have a
dummy value (such as EXPRESSION1) specified by the SQL tool used (SPUFI, QMF,
Command Editor, etc). If this is not desired, the AS clause can be used to specify a
column heading for these derived results.

Ex

The derived column name must follow the rules for DB2 names, as was discussed in the
slide entitled Names in unit 1 of this course.

pr

Because the SELECT clause is executed after the WHERE clause, the new column name
may only be used in the ORDER BY clause, and not in the WHERE clause itself.

4-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Substitution of NULL values

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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
ADMINISTRATION SYSTEMS
DEVELOPMENT CENTER
INFORMATION CENTER
MANUFACTURING SYSTEMS
OPERATIONS
PLANNING
SOFTWARE SUPPORT
SPIFFY COMPUTER SERVICE DIV.
SUPPORT SERVICES

MANAGER
000070
UNKNOWN
000030
000060
000090
000020
000100
000010
000050

Copyright IBM Corporation 2010, 2013

Figure 4-4. Substitution of NULL values

CE1216.1

Notes:

Here is a brief description of the COALESCE function:

cl

COALESCE allows multiple parameters:


COALESCE(expression_1, expression_2, expression_n, 'constant').

Ex

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, if MGRNO is NULL.

pr

Every expression must be of a compatible data type (if the first expression is numeric,
every expression must be numeric, and so on).

The COALESCE scalar function is equivalent to the VALUE scalar function. In other
words, you could use VALUE (MGRNO, UNKNOWN) in the SELECT statement above.

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-5

Student Notebook

Arithmetic with NULL values

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 + COMM
AS TOTAL_INCOME
FROM EMPLOYEE;

EMPNO
000210
000260
000290
000300
...

SALARY
18270.00
17250.00
15340.00
17750.00
...

COMM
TOTAL INCOME
1462.00
19732.00
1227.00
16567.00
...
...

SELECT EMPNO, SALARY, COMM,


SALARY +
COALESCE(COMM, 0)
AS TOTAL_INCOME
FROM EMPLOYEE;

EMPNO
000210
000260
000290
000300
...

SALARY
18270.00
17250.00
15340.00
17750.00
...

COMM
1462.00
1227.00
...

TOTAL INCOME
19732.00
17250.00
16567.00
17750.00
...

Copyright IBM Corporation 2010, 2013

Figure 4-5. Arithmetic with NULL values

CE1216.1

Notes:

pr

Ex

cl

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.

4-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Calculated values
EMPNO, SALARY, SALARY * 1.0375
EMPLOYEE
SALARY < 20000
EMPNO;

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE
ORDER BY

EMPNO
000210
000250
000260
000290
000300
000310
000320

SALARY
18270.00
19180.00
17250.00
15340.00
17750.00
15900.00
19950.00

18955.125000
19899.250000
17896.875000
15915.250000
18415.625000
16496.250000
20698.125000

Copyright IBM Corporation 2010, 2013

Figure 4-6. Calculated values

CE1216.1

Notes:

The above example shows multiplication using a constant. You can also use calculations
with multiple columns (for example, COL1 * COL2).

pr

Ex

cl

When performing multiplication or division of decimal numbers, or using the AVG column
function (discussed in Unit 5), the result usually contains more digits to the right of the
decimal point than we want to display. How can we clean that up?

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-7

Student Notebook

Rounding and Truncation

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT EMPNO, SALARY, DECIMAL(ROUND(SALARY * 1.0375, 2), 8, 2)


FROM EMPLOYEE
WHERE SALARY < 20000
ORDER BY EMPNO;

EMPNO

SALARY

000210
000250
000260
000290
000300
000310
000320

18270.00
19180.00
17250.00
15340.00
17750.00
15900.00
19950.00

18955.13
19899.25
17896.88
15915.25
18415.63
16496.25
20698.13

Copyright IBM Corporation 2010, 2013

Figure 4-7. Rounding and Truncation

CE1216.1

Notes:

cl

The ROUND function in DB2 will round your calculation to the appropriate number of
decimal points. You also need the DECIMAL function to specify the number of digits in the
result.

Ex

In DB2, the answer just using ROUND would still be to six decimal digits. DECIMAL
converts the answer, in this case, to a DECIMAL(8,2) format, that is, two decimal digits.
Why did we not use DECIMAL in the first place? Because it does not round the answer.
Therefore, in DB2, a combination of both DECIMAL and ROUND is required.

pr

In addition to the ROUND function, there is another function, TRUNC, that will also enable
you to choose the number of decimal points to display, but will not perform rounding. Like
ROUND, TRUNC also requires DECIMAL in DB2 to specify the number of digits in the final
output.

4-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Condition on calculated values


EMPNO, COMM, SALARY, (COMM/SALARY) * 100
EMPLOYEE
(COMM/SALARY) * 100 > 8
EMPNO;

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE
ORDER BY

EMPNO

COMM

SALARY

000140
000210
000240
000330

2274.00
1462.00
2301.00
2030.00

28420.00
18270.00
28760.00
25370.00

8.001400
8.002100
8.000600
8.001500

Copyright IBM Corporation 2010, 2013

Figure 4-8. Condition on calculated values

CE1216.1

Notes:

cl

Arithmetic expressions are most commonly used in the SELECT list, but can also be
included in the WHERE clause. The SQL statement above demonstrates that such
expressions can occur in the WHERE clause. The above SELECT returns rows for
employees with a commission that is higher than 8 percent of their salary.

pr

Ex

You may notice that the expression (COMM/SALARY) * 100 appears twice in the
statement. In the SELECT, it will return the calculated value in the result set row, just to the
right of the SALARY column value for each row in the result set. In the WHERE, the
expression is used to filer rows, so that only those employees whose COMMision is more
than 8% of their salary are returned in the result set.

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-9

Student Notebook

Upper and lower case


Henderson
ADAMSON
JEFFERsON
JOHNSOn

(Column values
in the DB2 table)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

000090
000150
000230
000260

SELECT EMPNO,LASTNAME
FROM EMPLOYEE
WHERE UPPER(LASTNAME) like '%SON% ;
SELECT EMPNO,LASTNAME
FROM EMPLOYEE
WHERE LOWER(LASTNAME) like '%son% ;
(Result set as
returned to the user)

000090
000150
000230
000260

Henderson
ADAMSON
JEFFERsON
JOHNSOn

Copyright IBM Corporation 2010, 2013

Figure 4-9. Upper and lower case

CE1216.1

Notes:

UPPER: Returns a string in which all the SBCS (Single-Byte Character Set) characters
have been converted to uppercase characters.

cl

LOWER: Returns a string in which all the SBCS characters have been converted to
lowercase characters.

pr

Ex

The SELECT statements above both perform the same function. The result set will be all
employee rows whose LASTNAME ends in the letters son, regardless of their case.
Therefore, it would not matter whether Johnson was initially stored as JOHNSON, johnson,
Johnson, jOHNSON or any other combination of upper and lower case letters.

4-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Substring of strings (1 of 2)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 4-10. Substring of strings (1 of 2)

CE1216.1

Notes:

If only a part of a character string needs to be selected, use the SUBSTR scalar function to
extract that portion. There are three arguments that are passed to the SUBSTR function.

cl

1. The expression to be searched

2. Where to start searching (the displacement, in bytes, into the first argument)

Ex

3. How much to retrieve (how many bytes to return)

pr

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

Unit 4. Scalar Functions and Arithmetic


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

4-11

Student Notebook

Concatenation of values
LASTNAME || ', ' || FIRSTNME AS NAME
EMPLOYEE
WORKDEPT = 'A00'
NAME;

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE
ORDER BY

NAME

HAAS, CHRISTINE
LUCCHESSI, VINCENZO
O'CONNELL, SEAN

Copyright IBM Corporation 2010, 2013

Figure 4-11. Concatenation of values

CE1216.1

Notes:

cl

The above example displays LASTNAME and FIRSTNME as a single result set column,
separated by a comma and a space. CONCAT combines character strings into a single
column.

Ex

The word CONCAT works in all environments. Double bars (||) can be often used to
represent concatenation, but you must ensure that in your specific environment (operating
system/platform, keyboard mapping, etc.) that the double bars actually invoke the
concatenation function.
Example:

pr

SELECT LASTNAME || ',' || FIRSTNME FROM EMPLOYEE

Check your environment's SQL documentation to see what additional concatenation


symbols may be supported.

4-12 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Order of precedence in predicate processing

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

1. Evaluation of contents within parentheses, beginning with


the innermost set of parentheses

2. All Boolean operator ANDs are processed before the ORs


3. Multiplication and division are performed before addition
and subtraction
4. Process from Left to Right

+ or

OR

* or

(..)

AND

Copyright IBM Corporation 2010, 2013

Figure 4-12. Order of precedence in predicate processing

CE1216.1

Notes:

cl

There are often multiple predicates in the WHERE clause, and it is important for the query
writer or application programmer to understand the order of precedence when DB2 applies
the selection criteria to the rows in the DB2 table.

Ex

Conditions within parentheses are evaluated first. If parentheses are nested, then DB2
evaluates the innermost set of parentheses, and then works its way towards the outermost
set.

pr

The Boolean ANDs are processed before the ORs. The third principle to remember is that
multiplication and division are performed before addition and subtraction. And the final
principle, after the other three have been applied, is to process the predicates from left to
right. In other words, operators at the same precedence level are applied from left to right
It is recommended that the coder use parentheses to clarify the SQL logic, even if it is not
absolutely necessary to retrieve the correct results.

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-13

Student Notebook

DB2 DATE, TIME and TIMESTAMP

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

DATE, TIME, and TIMESTAMP data are internally stored


in packed decimal format
Data Type

Internal Format

Internal Length

DATE

yyyymmdd

4 bytes

TIME

hhmmss

3 bytes

TIMESTAMP

yyyymmddhhmmssnnnnnn

10 bytes

The result set displays to the user in these formats:


Format

Time Format

Length

ISO

hh.mm.ss

8 bytes yyyy-mm-dd 10 bytes

USA

hh:mm AM

8 bytes mm/dd/yyyy

hh:mm PM

8 bytes

Date Format Length

10 bytes

EUR

hh.mm.ss

dd.mm.yyyy

JIS

hh:mm:ss

8 bytes yyyy-mm-dd 10 bytes

LOCAL

???

???

???

TIMESTAMP DATA: yyyy-mm-dd-hh.mm.ss.nnnnnn

10 bytes
???

26 bytes

Copyright IBM Corporation 2010, 2013

Figure 4-13. DB2 DATE, TIME and TIMESTAMP

CE1216.1

Notes:

cl

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.

Ex

DB2 accepts any of the formats (USA, ISO, EUR, JIS) in an SQL statement (character
string representation of dates, times, and timestamps). Thus, all three of the queries below
would execute successfully:
SELECT EMPNO, LASTNAME, BIRTHDATE
FROM EMPLOYEE

pr

WHERE BIRTHDATE = 1950-12-18 ;

SELECT EMPNO, LASTNAME, BIRTHDATE


FROM EMPLOYEE

WHERE BIRTHDATE = 12/18/1950 ;


SELECT EMPNO, LASTNAME, BIRTHDATE
4-14 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

FROM EMPLOYEE

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

WHERE BIRTHDATE = 18.12.1950 ;

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-15

Student Notebook

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

DB2: Different date formats

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 2010, 2013

Figure 4-14. DB2: Different date formats

CE1216.1

Notes:

pr

Ex

cl

The visual introduces the CHAR scalar function. In the example above, the CHAR function
is coded in order to convert a TIME column value into the desired external character
format. CHAR will work similarly with the DATE data type.

4-16 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

DB2 DATE comparison


EMPNO, LASTNAME, BIRTHDATE
EMPLOYEE
BIRTHDATE >= '1955-01-21'
BIRTHDATE;

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE
ORDER BY

EMPNO

LASTNAME

BIRTHDATE

000160
000100

PIANKA
SPENCER

1955-04-12
1956-12-18

Copyright IBM Corporation 2010, 2013

Figure 4-15. DB2 DATE comparison

CE1216.1

Notes:

pr

Ex

cl

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. In the sample
shown, all employees are retrieved that were born on or after January 21, 1955

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-17

Student Notebook

DB2 Special Registers

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

CURRENT DATE
CURRENT TIME
CURRENT TIMESTAMP

CURRENT_DATE
CURRENT_TIME
CURRENT_TIMESTAMP

Example, in ISO format:


CURRENT DATE
-----------2011-07-29

CURRENT TIME
-----------09.45.22

CURRENT TIMESTAMP
----------------2011-07-29-09.45.22.030000

Copyright IBM Corporation 2010, 2013

Figure 4-16. DB2 Special Registers

CE1216.1

Notes:

cl

CURRENT DATE, CURRENT TIME and CURRENT TIMESTAMP are referred to as


special registers. Notice that they may be coded with either a single underscore or a single
blank character after the word CURRENT.

Ex

DB2 can retrieve the current date, current time and current timestamp from the operating
system. These can be treated as normal date, time and timestamp values when selected.
That is to say:
they will come up in a default format

you can use the CHAR function to see them in different formats

pr

you can perform arithmetic

4-18 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

DB2 DATE / TIME scalar functions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

DAY, MONTH, YEAR, HOUR, MINUTE, SECOND,


MICROSECOND, DATE, TIME
Extract portions of a date, time, timestamp, or duration

DAYS - Converts any date to the number of days since


January 1st, 1 AD
DAYS(date_1) DAYS(date_2) gives the number of days
between date_1 and date_2
SELECT PROJNO, PRENDATE, DAY(PRENDATE) AS DAY,
MONTH(PRENDATE) AS MONTH,
YEAR(PRENDATE) AS YEAR
FROM PROJECT
WHERE PROJNO = 'PL2100;

PROJNO
-----PL2100

PRENDATE
-------09/15/2011

DAY
--15

MONTH
----09

YEAR
---2011

Copyright IBM Corporation 2010, 2013

Figure 4-17. DB2 DATE / TIME scalar functions

CE1216.1

Notes:

cl

DB2 offers the user all of the scalar functions mentioned in the visual above. Most of them
simply extract a component of a date, time or timestamp, and the example SELECT
statement and result set demonstrate their usefulness.

pr

Ex

The DAYS scalar function is different from the others. It converts any date value into the
number of days that have passed since January 1st , 1 AD (There was no year 0 AD .
Time passed from December 31, 1 BC to January 1, 1 AD). At first glance DAYS seems to
be of dubious value, but when you subtract one DAYS value from another DAYS value, the
result is a time duration in days, and that can prove very useful in business applications.

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-19

Student Notebook

DB2 subtraction of dates (1 of 2)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I need a listing containing the ages


of all employees 72 years old or
more, sorted by age in descending
sequence.

SELECT

FROM
WHERE
ORDER BY

EMPNO

LASTNAME

DIFFER

000130
000050
000340
000110
000310
000320

QUINTANA
GEYER
GOUNOT
LUCCHESSI
SETRIGHT
MEHTA

790727.
790727.
781126.
750607.
740021.
720901.

EMPNO, LASTNAME, CURRENT_DATE BIRTHDATE AS DIFFER


EMPLOYEE
CURRENT_DATE - BIRTHDATE >= 720000
DIFFER DESC;

Copyright IBM Corporation 2010, 2013

Figure 4-18. DB2 subtraction of dates (1 of 2)

CE1216.1

Notes:

cl

In above example, the values of two date columns are subtracted. The result of the
subtraction is presented in the format yyyymmdd, and if there are any leading zeros, those
are not displayed.

Ex

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

pr

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

4-20 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

DB2 subtraction of dates (2 of 2)


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

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT

PROJNO
PL2100
MA2113

DAYS
257
289

Copyright IBM Corporation 2010, 2013

Figure 4-19. DB2 subtraction of dates (2 of 2)

CE1216.1

Notes:

The example SELECT in the visual above shows the duration of projects in days.

Ex

cl

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. Perhaps the way to think
about is that future time is larger. Therefore, you would normally want to subtract the
earlier time from the later time in order to have a positive duration of time when using the
DAYS scalar function.
Note:

pr

When subtracting dates, the user may be inclined to code DAYS(PRENDATE


PRSTDATE), which would result in an SQL syntax error. The function must be coded as
DAYS(PRENDATE) DAYS(PRSTDATE).

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-21

Student Notebook

DB2 DATE arithmetic and labeled durations


PROJNO, PRENDATE,
PRENDATE + 2 MONTHS + 15 DAYS
PROJECT
PROJNO = 'AD3100'
PROJNO;

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE
ORDER BY

PROJNO

PRENDATE

AD3100

1983-02-01

1983-04-16

Copyright IBM Corporation 2010, 2013

Figure 4-20. DB2 DATE arithmetic and labeled durations

CE1216.1

Notes:

cl

Consider the situation in which the company expects a project to finish 2 months later
than the original estimate. The example SELECT shows the use of labeled durations by
adding 2 months and 15 days to the original end date for the project.
Please keep in mind the following points regarding labeled durations:

Ex

1. They cannot stand alone. Instead, they must be associated to a date, time or
timestamp column

2. They cannot be added to each other

pr

So the following would cause syntax errors:


SELECT 2 MONTHS, PRENDATE .

SELECT 2 MONTHS + 3 MONTHS, PRENDATE .

4-22 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Checkpoint

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

1. If you use SELECT ROUND(SALARY,-2) on a row in the


EMPLOYEE table, how far are you rounding the salary?

2. How would you find the duration of an activity in days, using


DB2?
3. Name as many of the scalar functions as you can
remember.

Copyright IBM Corporation 2010, 2013

Figure 4-21. Checkpoint

CE1216.1

Notes:

Please write your answers below:


1.

cl

2.

pr

Ex

3.

Copyright IBM Corp. 2013

Unit 4. Scalar Functions and Arithmetic


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

4-23

Student Notebook

Unit summary

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Having completed 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

Copyright IBM Corporation 2010, 2013

Figure 4-22. Unit summary

CE1216.1

pr

Ex

cl

Notes:

4-24 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit 5. Column Functions and Grouping


What this unit is about

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Practical Problems requiring column functions

What you should be able to do

After completing this unit, you should be able to:

Describe the difference between scalar and column functions


Introduce the commonly used DB2 column functions

Group rows into sets based on one or more columns

Limit the number of groups in the result set

How you will check your progress

pr

Ex

cl

Checkpoint

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-1

Student Notebook

Unit objectives

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

After completing this unit, you should be able to:


Describe the difference between scalar and column functions
Introduce the commonly used DB2 column functions
Group rows into sets based on one or more columns
Limit the number of groups in the result set

Copyright IBM Corporation 2010, 2013

Figure 5-1. Unit objectives

CE1216.1

pr

Ex

cl

Notes:

5-2

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

SQL functions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Function_name(f_argument)
Column
Functions
AVG(SALARY)
________
________
________
______
________
________

Scalar
Functions
YEAR(HIREDATE)
__________ _____
__________ _____
__________ _____
__________ _____
__________ _____

Copyright IBM Corporation 2010, 2013

Figure 5-2. SQL functions

CE1216.1

Notes:

There are two types of SQL functions:

Column functions (also known as summary functions)

cl

Scalar functions

Ex

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.

pr

For qualified rows column functions produce a summary value. AVG(SALARY) adds up the
non-null SALARYs and divides by the number of non-null SALARYs. Column functions tell
DB2 "Show me just the summary information, not the detail behind the summary."
Scalar functions, however, produce a value for every row in the set. In this example, we
are using the YEAR scalar function. For each row that met our WHERE clause criteria DB2
will extract the YEAR piece of the date in the HIREDATE column.

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-3

Student Notebook

Column functions
SUM(expression)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Compute Total
Calculate Average

AVG(expression)

Find Minimum Value

MIN(expression)

Find Maximum Value

MAX(expression)

Determine the number of rows


meeting the search condition

COUNT(*)

Determine the number of


unique non-null values in a
column

COUNT(DISTINCT col-name)

Copyright IBM Corporation 2010, 2013

Figure 5-3. Column functions

CE1216.1

Notes:

For the column functions SUM, AVG, MIN, MAX, COUNT(*) and COUNT(DISTINCT), the
following principles or rules apply:

cl

The basis for these column functions are values derived from one or more rows.

Ex

The data type of the input values for SUM and AVG must be numeric, whereas MIN and
MAX may be used with character data types.

Here is a sample SQL statement showing the use of the COUNT(*) function:
SELECT COUNT(*) FROM EMPLOYEE WHERE WORKDEPT = 'A00'

pr

The statement returns the number of rows having the value 'A00' in the WORKDEPT
column. In general, the argument for COUNT(*) is a set of rows. The result is the number
of rows in the set.

5-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Here is an example of the COUNT(DISTINCT column-name) function:


SELECT COUNT(DISTINCT WORKDEPT) FROM EMPLOYEE

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

This statement returns the number of unique non-null values in the WORKDEPT column.
The argument of this function can also be an expression.

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-5

Student Notebook

Sample column functions


SUM(SALARY) AS SUM,
AVG(SALARY) AS AVG,
MIN(SALARY )AS MIN,
MAX(SALARY) AS MAX,
COUNT(*)
AS COUNT,
COUNT (DISTINCT WORKDEPT) AS DEPT

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT

EMPLOYEE ;

FROM

SUM

873715.00

AVG

27303.59375000

MIN

MAX

15340.00

52750.00

COUNT DEPT
32

Copyright IBM Corporation 2010, 2013

Figure 5-4. Sample column functions

CE1216.1

Notes:

cl

The column functions in the SELECT statement above are applied to all rows of the
EMPLOYEE table, since there is no WHERE clause specifying selection criteria that must
be met. 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.

pr

Ex

In the result set, the SUM represents the total payroll, AVG is the average salary of all
employees, MIN and MAX display the lowest and highest salary values, COUNT indicates
that there are 32 employees (rows) in the table, and DEPT reveals that there are 8
departments in which the employees work.
Except for COUNT(*), expressions (for example, SALARY + COMM) can be used as an
argument for column functions.

5-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Beware of NULLs
SUM(SALARY)+SUM(BONUS)+SUM(COMM)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

VERSUS

SUM(SALARY+BONUS+COMM)

SALARY
1000
2000
2500
1500
-----7000
=====

BONUS
500
NULL
400
100
----1000
=====

COMM
100
300
NULL
400
---800
====

SALARY+BONUS+COMM
1600
NULL
NULL
2000
------------------> 8800
3600
====

-->

EMPNO
000010
000020
000030
000040
-----Sum:

Copyright IBM Corporation 2010, 2013

Figure 5-5. Beware of NULLs

CE1216.1

Notes:

If a null is part of row level arithmetic, the result is null. Nulls are ignored in column level
arithmetic.

Ex

cl

In the visual above, the individual SUMs of SALARY, BONUS and COMM are 7000, 1000
and 800 respectively, giving a grand total of 8800 for the expression SUM(SALARY) +
SUM(BONUS) + SUM(COMM). However, due to null values for employees 000020 and
000030, the total for the expression SUM(SALARY + BONUS + COMM) is only 3600.

pr

In situations like this, where nulls may invalidate or throw off the expected or desired
results, the query writer or application programmer should consider using the
COALESCE/VALUE/NVL scalar function to replace nulls with known values (such as 0 for
numeric columns).

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-7

Student Notebook

Column functions based on subset

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 5-6. Column functions based on subset

CE1216.1

Notes:

The result is derived from the set of rows for which the WHERE clause predicate is true.
The total payroll for the departments beginning with D is 373020.00.

Ex

cl

Notice that there are no commas separating the thousands from hundreds. The only
punctuation mark allowed in SQL syntax is the decimal. Be aware that in some parts of the
world (many European nations), the convention may be to use the comma as the decimal
point and the period as the delimiter separating thousands, millions, etc.

pr

The only punctuation mark allowed in numbers is the character designated as the decimal
point. There are no separator characters for thousands, millions, billions, etc.

5-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

GROUP BY

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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
FROM
WHERE
ORDER BY

WORKDEPT, SALARY
EMPLOYEE
WORKDEPT IN ('A00', 'B01', 'C01')
WORKDEPT ;

WORKDEPT

SELECT
FROM
WHERE
GROUP BY
ORDER BY

WORKDEPT, SUM(SALARY) AS SUM


EMPLOYEE
WORKDEPT IN ('A00', 'B01', 'C01')
WORKDEPT
WORKDEPT ;

SALARY

A00
A00
A00
B01

52750.00
46500.00
29250.00
41250.00

C01
C01
C01

38250.00
23800.00
28420.00

WORKDEPT
A00
B01
C01

SUM

128500.00
41250.00
90470.00

Copyright IBM Corporation 2010, 2013

Figure 5-7. GROUP BY

CE1216.1

Notes:

cl

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

Ex

A name defined by an AS clause cannot be used in GROUP BY.

When column names and one or more column functions are specified in the SELECT
clause, each column name must be referenced in the GROUP BY clause.

pr

The above two queries are somewhat similar. The query on the left displays the salaries of
the individual employees in the three departments. In the example on the right, the
GROUP BY aggregates the data and displays the total of the salaries in each of the three
departments. Since there are three different department values in the WHERE clause, the
result table consists of three rows.
GROUP BY does not guarantee a sorted result set. If an ordered result set is required,
then an ORDER BY clause must be specified.
Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-9

Student Notebook

GROUP BY more than one column

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Find out the average salary per education level for each department, for
education levels 18 and higher.
SELECT WORKDEPT, EDLEVEL,

DECIMAL(ROUND(AVG(SALARY),2),9,2) AS AVGSAL

FROM EMPLOYEE

WHERE EDLEVEL > = 18

GROUP BY WORKDEPT, EDLEVEL

ORDER BY WORKDEPT, EDLEVEL ;

WORKDEPT

EDLEVEL

AVGSAL

A00

18

52750.00

A00

19

46500.00

B01

18

41250.00

C01

18

28420.00

C01

20

38250.00

D11

18

29840.00

Copyright IBM Corporation 2010, 2013

Figure 5-8. GROUP BY more than one column

CE1216.1

Notes:

cl

Here we are grouping by two columns, the work department and then the education level. It
is possible to use more than two columns to group the data, depending upon the
requirements of the application.

pr

Ex

Note again that the ROUND function would need to be qualified by the DECIMAL function
in order to display only two decimal digits in the result (see Unit 4).

5-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

GROUP BY, HAVING (1 of 2)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Now, I just want to see


departments with total spent
for salaries higher than 50000.

SELECT
FROM
WHERE
GROUP BY
ORDER BY

WORKDEPT, SUM(SALARY) AS SUM


EMPLOYEE
WORKDEPT IN ('A00', 'B01', 'C01')
WORKDEPT
WORKDEPT;

WORKDEPT
A00
B01
C01

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

SUM
128500.00
41250.00
90470.00

WORKDEPT, SUM(SALARY) AS SUM


EMPLOYEE
WORKDEPT IN ('A00', 'B01', 'C01')
WORKDEPT
SUM(SALARY) > 50000
WORKDEPT ;

WORKDEPT
A00
C01

SUM
128500.00
90470.00

Copyright IBM Corporation 2010, 2013

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

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

Ex

cl

HAVING can 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. It may be helpful to think of the HAVING clause as being like a
WHERE clause, only applied to groups of rows, rather than to individual rows.

pr

In both queries above, the WHERE clause limits any results to departments A00, B01 and
C01. The results are grouped by department, and then the HAVING clause further limits
the result set. In the left-hand query above, DB2 returns the total payroll (sum of the
salaries for employees within a departement) for the three departments. In the right-hand
query, because of the HAVING clause, DB2 returns results for only those departments
whose sum of the salaries is greater than 50000.

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-11

Student Notebook

GROUP BY, HAVING (2 of 2)

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

By department, I need a listing of


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

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

WORKDEPT, JOB, AVG(SALARY) AS AVG


EMPLOYEE
JOB NOT IN ('MANAGER', 'DESIGNER', 'FIELDREP')
WORKDEPT, JOB
AVG(SALARY) > 25000
WORKDEPT, JOB ;

WORKDEPT JOB
A00
A00
A00
C01

CLERK
PRES
SALESREP
ANALYST

AVG

29250.00000000
52750.00000000
46500.00000000
26110.00000000

Copyright IBM Corporation 2010, 2013

Figure 5-10. GROUP BY, HAVING (2 of 2)

CE1216.1

Notes:

pr

Ex

cl

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 set row for each unique set (combination of WORKDEPT
and JOB) of values across the columns being grouped.

5-12 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Examples with HAVING

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Display the departments


with more than one employee.

SELECT

FROM
GROUP BY
ORDER BY

WORKDEPT,
COUNT(* ) AS NUMB
EMPLOYEE
WORKDEPT
NUMB, WORKDEPT ;

WORKDEPT
B01
E01
A00
C01
E21
E11
D21
D11

SELECT

FROM
GROUP BY
HAVING
ORDER BY

NUMB
1
1
3
3
4
5
6
9

WORKDEPT,
COUNT(*) AS NUMB
EMPLOYEE
WORKDEPT
COUNT(*) > 1
NUMB, WORKDEPT ;

WORKDEPT
A00
C01
E21
E11
D21
D11

NUMB
3
3
4
5
6
9

Copyright IBM Corporation 2010, 2013

Figure 5-11. Examples with HAVING

CE1216.1

Notes:

cl

The left SELECT is displayed to show the result without a HAVING clause all
departments are returned in the result set, displaying the number of employees therein.
The right SELECT determines the result set consisting of groups for which the search
condition of the HAVING clause is true. The condition COUNT(*) > 1 therefore filters out
any departments that do not have at least two employees.

pr

Ex

Again, it is fairly easy to understand when you think of a HAVING clause as a WHERE
clause, only for groups of rows.

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-13

Student Notebook

An important rule for column functions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

This applies to queries with COLUMN functions


in the SELECT Clause:

If a SELECT (or HAVING) clause has COLUMN functions


AND

it also includes columns not in COLUMN functions, then


ALL
columns not in COLUMN functions must be
included in the GROUP BY clause

Copyright IBM Corporation 2010, 2013

Figure 5-12. An important rule for column functions

CE1216.1

Notes:

cl

The rule above is one of the most difficult to remember. Perhaps the only mistake that is
more common in SQL is to omit the join predicate when SELECTing data from more than
one table, resulting in a Cartesian product.
Another way to state the rule above is:

Ex

If a SELECT clause contains a column function, then any columns in that SELECT
statement must also appear in a corresponding GROUP BY clause. This rule also applies
to column functions in a HAVING clause. We will discuss the HAVING clause very soon.

pr

The reverse of the rule is not true, that is, columns listed in the GROUP BY clause do not
have to have been selected.

5-14 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Restrictions
Column functions may be specified only in:

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
HAVING

SELECT can specify only:

Column functions
Columns (which must be specified in a GROUP BY)

HAVING can 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 2010, 2013

Figure 5-13. Restrictions

CE1216.1

Notes:

Be aware of the following items when using column functions:

cl

1. Column functions can be specified in the SELECT and HAVING clauses, but not in the
WHERE clause.

Ex

2. Any columns appearing in a SELECT that contains a column function must also be
included in the GROUP BY clause
3. The columns in the HAVING are independent of the SELECT

pr

4. Unlike the above mentioned restriction on column functions, scalar functions may be
nested (we have already seen, for example, DECIMAL(ROUND)).

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-15

Student Notebook

SELECT statement: Six clauses

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT WORKDEPT, JOB, AVG(SALARY)


FROM EMPLOYEE

WHERE JOB NOT LIKE 'M%'

GROUP BY WORKDEPT, JOB

HAVING AVG(SALARY) > 28000

ORDER BY 3 DESC ;

Copyright IBM Corporation 2010, 2013

Figure 5-14. SELECT statement: Six clauses

CE1216.1

Notes:

cl

The SQL statement above shows the six clauses that we have discussed in class so far.
This is not an exhaustive list, as there are other clauses and options, but for the purposes
of this introductory course, mastering these six clauses will enable the query writer or
application programmer to address many requirements when retrieving DB2 data.

Ex

The SELECT clause tells DB2 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 to produce a single summary row for a set of detail rows.
The FROM clause tells DB2 which table(s) contain the requested data.

pr

The WHERE clause specifies which row(s) of information are to be used based upon some
qualification criteria.
The GROUP BY clause tells DB2 which row(s) of information are to be grouped together
(that is, summarized) based upon values in columns.

5-16 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

The HAVING clause tells DB2 which groups of information are to be processed based upon
a group qualification criteria.

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

The ORDER BY clause specifies sequence of the result set rows in the final result set.

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-17

Student Notebook

Conceptual execution of a SELECT (1 of 2)


WHERE

GROUP BY

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

FROM
JOB
S
M
S
C
S
M
S
C
S
M
S
S
C
S
S

SALARY
31000
32000
30000
27000
33000
31000
32000
28000
30000
33000
31000
35000
27000
29000
29000

WORKDEPT
BLU
RED
BLU
GRE
GRE
BLU
RED
GRE
RED
GRE
RED
GRE
BLU
RED
BLU

JOB SALARY WORKDEPT


S
31000
BLU

JOB SALARY WORKDEPT


C
27000
BLU

S
C
S

30000
27000
33000

BLU
GRE
GRE

S
S
S

31000
29000
30000

BLU
BLU
BLU

S
C
S

32000
28000
30000

RED
GRE
RED

C
C

27000
28000

GRE
GRE

S
S
C
S
S

31000
35000
27000
29000
29000

RED
GRE
BLU
RED
BLU

S
S

33000
35000

GRE
GRE

S
S
S
S

32000
30000
31000
29000

RED
RED
RED
RED

Copyright IBM Corporation 2010, 2013

Figure 5-15. Conceptual execution of a SELECT (1 of 2)

CE1216.1

Notes:

cl

The previous visual shows the syntactical order in which the clauses in a SELECT must be
coded. However, the order of execution is different. Please note that for this example, the
data does not match that of the sample EMPLOYEE table.

Ex

In these two visuals, moving from left to right, we will walk through the execution of the
SELECT statement step by step, clause by clause.
The clauses are executed in the following sequence:
FROM

pr

WHERE

GROUP BY
HAVING

SELECT

ORDER BY

5-18 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

The FROM clause tells DB2 which table or tables to locate (EMPLOYEE), by searching the
DB2 catalog. At this point in time, all rows in the table are available.
The WHERE clause filters out rows of employees who are managers (JOB NOT LIKE
M%)

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

The GROUP BY clause groups the rows together by job within department (GROUP BY
WORKDEPT, JOB)

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-19

Student Notebook

Conceptual execution of a SELECT (2 of 2)

JOB

S
S
S

S
S
S
S
S
S

SELECT

ORDER BY

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

HAVING
WORKDEPT

WORKDEPT JOB

WORKDEPT JOB

31000 BLU
29000 BLU
30000 BLU

BLU

30000

33000 GRE
35000 GRE

GRE

34000

32000
30000
31000
29000

RED

30500

RED
RED
RED
RED

GRE
RED
BLU

S
S
S

34000
30500
30000

Copyright IBM Corporation 2010, 2013

Figure 5-16. Conceptual execution of a SELECT (2 of 2)

CE1216.1

Notes:

The HAVING clause filters out groups for which the average salary is less than 28000
(HAVING AVG(SALARY) < 28000)

cl

The SELECT retrieves the department, job and average salary for the qualified groups
(SELECT, WORKDEPT, JOB, AVG(SALARY))

pr

Ex

The ORDER BY clause sequences the rows into the desired sequence, in descending
order of average salary (ORDER BY 3 DESC)

5-20 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Checkpoint

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

1. True or False? A scalar function produces a summary row for a set of


rows.
2. True or False? A SELECT statement whose SELECT list includes a
column function (SUM, AVG, MIN, MAX, COUNT, and so forth) and three
columns not in column functions does not require a GROUP BY clause.
3. Which clause qualifies groups for further processing?
a.
b.
c.
d.
e.
f.

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

4. True or False? The following query is syntactically correct.


SELECT WORKDEPT, AVG(SALARY)
FROM EMPLOYEE
WHERE AVG(SALARY) > 20000
GROUP BY WORKDEPT
HAVING COUNT(*) > 3
ORDER BY 2 DESC ;

Copyright IBM Corporation 2010, 2013

Figure 5-17. Checkpoint

CE1216.1

Notes:

Please write your answers here:


1.

cl

2.

Ex

3.

pr

4.

Copyright IBM Corp. 2013

Unit 5. Column Functions and Grouping


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

5-21

Student Notebook

Unit summary

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Having completed this unit, you should be able to:


Describe the difference between scalar and column functions
Introduce the commonly used DB2 column functions
Group rows into sets based on one or more columns
Limit the number of groups in the result set

Copyright IBM Corporation 2010, 2013

Figure 5-18. Unit summary

CE1216.1

pr

Ex

cl

Notes:

5-22 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit 6. Union
What this unit is about

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

This unit describes the syntax of an SQL statement that will produce a
result set 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 set 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


Checkpoint questions

pr

Ex

cl

Machine labs

Copyright IBM Corp. 2013

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

6-1

Student Notebook

Unit objectives

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

After completing this unit, you should be able to:


Produce a single result set containing data from more than
one query
State the UNION rules
State the difference between UNION and UNION ALL

Copyright IBM Corporation 2010, 2013

Figure 6-1. Unit objectives

CE1216.1

pr

Ex

cl

Notes:

6-2

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Multiple queries: Multiple reports


DATA FROM QUERY 1

QUERY 2
SELECT some_columns
FROM some_table(s)
WHERE some_conditions

DATA FROM QUERY 2

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

QUERY 1
SELECT some_columns
FROM some_table(s)
WHERE some_conditions

Copyright IBM Corporation 2010, 2013

Figure 6-2. Multiple queries: Multiple reports

CE1216.1

Notes:

Back in unit 3 we introduced joins. A join is a query in which data from more than one table
is required in the result set. So a join combines data from multiple tables.

Ex

cl

Each time a query is executed a single result set is produced. Sometimes we may have a
requirement for data returned by one query to appear in a result set along with data from
additional queries.

pr

In contrast to a join, a union is when the result set from more than one query is required in
a single output report. So a union combines result sets from multiple queries.

Copyright IBM Corp. 2013

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

6-3

Student Notebook

UNIONing queries together: Single report

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

DATA FROM QUERY 1

UNION ALL

DATA FROM QUERY 2

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

Copyright IBM Corporation 2010, 2013

Figure 6-3. UNIONing queries together: Single report

CE1216.1

Notes:

Adding a UNION (or UNION ALL) clause between the queries combines the data from both
queries into a single report.

pr

Ex

cl

There is no limit on the number of queries whose data can be added to the report, so long
as each query conforms to the UNION RULES.

6-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

UNION rule number 1

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 6-4. UNION rule number 1

CE1216.1

Notes:

pr

Ex

cl

The multiple SELECT statements in a UNION operation are collectively referred to as


being a stack. If the first query in the stack returns x number of columns, then every
query in the stack must return x number of columns. Each query may be referencing
different tables, and the column names in one query can be different from the column
names in the next query. But there must be the same number of columns in each query.

Copyright IBM Corp. 2013

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

6-5

Student Notebook

UNION rule number 2

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 6-5. UNION rule number 2

CE1216.1

Notes:

cl

The data types of the corresponding columns in each query in the stack must be
compatible. That means that the data types must be in the same general category, such as
character or numeric. The data types do not need to match exactly.

Ex

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.

pr

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). If the precision and scale do
not match, the report column will carry the largest precision and scale of all data types in
the column.

6-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

UNION rule number 3

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 6-6. UNION rule number 3

CE1216.1

Notes:

Only one ORDER BY clause is allowed in a UNIONed query, and it must be coded in the
last query of the stack.

pr

Ex

cl

If the user wants to ORDER BY the nth column, and the nth column has the same column
name in every query in the stack (the AS clause can be used to provide a common
column name for the nth column), then that column name can appear in the ORDER BY
clause. Otherwise, the relative position number must be used.

Copyright IBM Corp. 2013

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

6-7

Student Notebook

UNION ALL
LASTNAME, EDLEVEL
EMPLOYEE
JOB = 'ANALYST'

LASTNAME
QUINTANA
NICHOLLS

EDLEVEL
16
18

SELECT
FROM
WHERE

LASTNAME, EDLEVEL
EMPLOYEE
EDLEVEL = 18

LASTNAME
HAAS
THOMPSON
NICHOLLS
LUTZ

EDLEVEL
18
18
18
18

SELECT
FROM
WHERE
UNION ALL
SELECT
FROM
WHERE

LASTNAME, EDLEVEL
EMPLOYEE
JOB = 'ANALYST'

LASTNAME
QUINTANA
NICHOLLS
HAAS
THOMPSON
NICHOLLS
LUTZ

EDLEVEL
16
18
18
18
18
18

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE

LASTNAME, EDLEVEL
EMPLOYEE
EDLEVEL = 18

Copyright IBM Corporation 2010, 2013

Figure 6-7. UNION ALL

CE1216.1

Notes:

UNION ALL does not eliminate duplicates in the result set. UNION ALL therefore typically
performs better than UNION. So the general recommendation is to use

cl

UNION ALL if the queries cannot return duplicate rows, or if the application or end user can
tolerate duplicates.

pr

Ex

Notice that in the example above, Nicholls appears twice in the UNION ALL output, since
he is both an analyst and has an education level of 18.

6-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

UNION
LASTNAME, EDLEVEL
EMPLOYEE
JOB = 'ANALYST'

LASTNAME
NICHOLLS
QUINTANA

EDLEVEL
18
16

SELECT
FROM
WHERE

LASTNAME, EDLEVEL
EMPLOYEE
EDLEVEL = 18

LASTNAME
HAAS
LUTZ
NICHOLLS
THOMPSON

EDLEVEL
18
18
18
18

SELECT
FROM
WHERE
UNION
SELECT
FROM
WHERE

LASTNAME, EDLEVEL
EMPLOYEE
JOB = 'ANALYST'

LASTNAME
HAAS
LUTZ
NICHOLLS
QUINTANA
THOMPSON

EDLEVEL
18
18
18
16
18

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT
FROM
WHERE

LASTNAME, EDLEVEL
EMPLOYEE
EDLEVEL = 18

Copyright IBM Corporation 2010, 2013

Figure 6-8. UNION

CE1216.1

Notes:

UNION combines two sets of rows and removes duplicates.

cl

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:

Ex

1. Each SELECT is evaluated separately


2. The results are merged and ordered

3. Duplicates are removed before presenting the final result set to the user or application

pr

In this example, Nicholls only appears once, because UNION (unlike UNION ALL)
eliminates duplicate rows from appearing in the final result set.

Copyright IBM Corp. 2013

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

6-9

Student Notebook

UNION ALL: Example 1

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

For workdepts C01 and A00 display


workdept, last name concatenated to
first name and in a GENDER column
print MALE or FEMALE where
appropriate.

SELECT WORKDEPT, LASTNAME || ', ' ||


FIRSTNME AS NAME,
'MALE' AS GENDER
FROM EMPLOYEE
WHERE SEX = 'M'
AND WORKDEPT IN ('A00', 'C01')

UNION ALL

SELECT WORKDEPT, LASTNAME || ', ' ||


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

WORKDEPT
A00
A00
A00
C01
C01
C01

NAME
HAAS, CHRISTINE
LUCCHESSI, VINCENZO
O'CONNELL, SEAN
KWAN, SALLY
QUINTANA, DOLORES
NICHOLLS, HEATHER

GENDER
FEMALE
MALE
MALE
FEMALE
FEMALE
FEMALE

Copyright IBM Corporation 2010, 2013

Figure 6-9. UNION ALL: Example 1

CE1216.1

Notes:

pr

Ex

cl

The above example of a UNION is one solution for 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.

6-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

UNION ALL: Example 2


SELECT
FROM
WHERE MGRNO
UNION ALL
SELECT

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

As sketched out below, use two lines


per department. On line one print
manager's information, on line two
print department information.

MGRNO , 'Dept.:',
DEPTNAME AS NAME
DEPARTMENT
IS NOT NULL

FROM
E
WHERE
ORDER BY

MGRNO
000010
000010
000020
000020
000030
000030
000050
000050

Mgr.:
Dept.:
Mgr.:
Dept.:
Mgr.:
Dept.:
Mgr.:
Dept.:

MGRNO, 'Mgr.:',
LASTNAME AS NAME
DEPARTMENT D, EMPLOYEE
D.MGRNO = E.EMPNO
1,2 DESC

NAME
HAAS
SPIFFY COMPUTER SERVICE DIV.
THOMPSON
PLANNING
KWAN
INFORMATION CENTER
GEYER
SUPPORT SERVICES

Copyright IBM Corporation 2010, 2013

Figure 6-10. UNION ALL: Example 2

CE1216.1

Notes:

In order to have a column heading appear in the result set of a UNION or UNION ALL, the
user must specify the SELECT statements with either:

cl

1. The same column name in each query in the stack, or

2. Repeat the AS class (with the exact same name) in each query of the stack

pr

Ex

In this example, the position number (2) must be used for the second column in the
ORDER BY clause because the column does not have a name in the result set.

Copyright IBM Corp. 2013

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

6-11

Student Notebook

UNION: Generation of fitting result set rows


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

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SELECT

EMPNO
000010
000010
000010
000010
000020
000020
000020
000020
.

LASTNAME

C.I

M.L

HAAS
BONUS
COMM
SUM:
THOMPSON
BONUS
COMM
SUM:

INCOME

52750.00
1000.00
4220.00
57970.00
41250.00
800.00
3300.00
45350.00
.

SORT
1
2
3
4
1
2
3
4.

Copyright IBM Corporation 2010, 2013

Figure 6-11. UNION: Generation of fitting result set rows

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

Ex

cl

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.

pr

EMPNO must be selected to order the result set. And then in order to get a four row
display for each employee in the desired order (1st salary, 2nd bonus, 3rd commission, 4th
sum), we need an additional sort column. That is the purpose of the artificial SORT
column named in each query in the stack.

6-12 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

The double exclamation points (!!), and double bars (||) (in environments where they are
supported), are equivalent to the CONCAT operator (which is supported in all
environments). Check the specifics of your environment (operating system, keyboard
mapping, etc.) to determine its supported operator concatenation operators.

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Uempty

Copyright IBM Corp. 2013

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

6-13

Student Notebook

Checkpoint

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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


combined by means of UNION and ordered to get a new
result set.
2. Why or when should you use UNION instead of UNION
ALL?

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 2010, 2013

Figure 6-12. Checkpoint

CE1216.1

Notes:

Please write your answers here:


1.

cl

2.

pr

Ex

3.

6-14 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit summary

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Having completed this unit, you should be able to:


Produce a single result set containing data from more than
one query
State the UNION rules
State the difference between UNION and UNION ALL

Copyright IBM Corporation 2010, 2013

Figure 6-13. Unit summary

CE1216.1

pr

Ex

cl

Notes:

Copyright IBM Corp. 2013

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

6-15

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Student Notebook

6-16 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit 7. Using Subqueries


What this unit is about

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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


Checkpoint

pr

Ex

cl

Machine labs

Copyright IBM Corp. 2013

Unit 7. Using Subqueries


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

7-1

Student Notebook

Unit objectives

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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.

Copyright IBM Corporation 2012, 2013

Figure 7-1. Unit objectives

CE1216.1

Notes:

pr

Ex

cl

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


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

V7.0
Student Notebook

Uempty

Result using separate SELECTs

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Whose salary is higher


than the average salary?

First SELECT:

SELECT
FROM

AVG(SALARY)
EMPLOYEE;

27303

Second SELECT:

SELECT
FROM
WHERE

EMPNO, LASTNAME
EMPLOYEE
SALARY > 27303;

Copyright IBM Corporation 2012, 2013

Figure 7-2. Result using separate SELECTs

CE1216.1

Notes:

Assume that you want to produce a report listing all of the employees whose salary is
higher than the average salary of all employees in the company.

cl

Without subqueries, you would have to do the following:

Evaluate the average salary of all employees (the first SELECT statement above)

Ex

Code a second SELECT using the result (27303) in the WHERE clause.

pr

Run the second query to find the employees whose salary is higher than the average
salary (27303).

Copyright IBM Corp. 2013

Unit 7. Using Subqueries


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

7-3

Student Notebook

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Same result using a subquery

SELECT

EMPNO, LASTNAME

FROM

EMPLOYEE

WHERE

SALARY > (SELECT AVG(SALARY)


FROM

EMPLOYEE);

Copyright IBM Corporation 2012, 2013

Figure 7-3. Same result using a subquery

CE1216.1

Notes:

cl

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.

Ex

The first SELECT is known as the outer (or main) query. The inner SELECT is referred to
as the subquery. So in the example above, the outer query is SELECT EMPNO,
LASTNAME FROM EMPLOYEE WHERE SALARY >, and the subquery is (SELECT
AVG(SALARY) FROM EMPLOYEE)

pr

The subquery runs first, and the result is used to evaluate the WHERE condition of the
main query. The output of the subquery are passed along to the outer query as an
intermediate result and is not directly visible to the user.
A subquery cannot contain an ORDER BY.

7-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Subquery with basic predicates


EMPNO

LASTNAME

000010
000070
000290

HAAS
PULASKI
PARKER

BONUS
1000
700
300

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Who earned the


lowest bonus?

SELECT EMPNO, LASTNAME, BONUS


FROM

EMPLOYEE

WHERE

BONUS = (SELECT MIN (BONUS)


FROM

EMPNO

LASTNAME

000290

PARKER

EMPLOYEE);

BONUS
300

Copyright IBM Corporation 2012, 2013

Figure 7-4. Subquery with basic predicates

CE1216.1

Notes:

cl

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. In this example, we look for the employee(s) who earned the lowest bonus.

Ex

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.

pr

It is possible that several people may earn the same bonus. If the minimum bonus for the
table is earned by multiple employees, the subquery would still return just that one value
but the outer query would return all people who made that bonus.

Copyright IBM Corp. 2013

Unit 7. Using Subqueries


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

7-5

Student Notebook

Subquery using IN
SELECT FIRSTNME, LASTNAME, EMPNO
FROM EMPLOYEE
WHERE EMPNO IN (SELECT MGRNO
FROM DEPARTMENT);

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

List the names and employee


numbers of employees who are
managers of a department.

Final result set

Result of
subquery

FIRSTNME

LASTNAME

EMPNO

000010

CHRISTINE

HAAS

000010

000020

MICHAEL

THOMPSON

000020

000030

SALLY

KWAN

000030

000050

JOHN

GEYER

000050

000060

IRVING

STERN

000060

000070

EVA

PULASKI

000070

000090

EILEEN

HENDERSON

000090

000100

THEODORE

SPENSER

000100

Copyright IBM Corporation 2012, 2013

Figure 7-5. Subquery using IN

CE1216.1

Notes:

cl

IN and NOT IN can be used to make comparisons 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.

pr

Ex

Remember that the intermediate results of the subquery (on the right-hand portion of the
visual above) are not visible to the query user. Only the final result set is displayed, as
seen in the center of the visual.

7-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Subquery using NOT IN


DEPARTMENT Table
DEPTNO

DEPTNAME

A00
B01
C01

SPIFFY COMPUTER SERVICE


PLANNING
INFORMATION CENTER

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Which departments
do not have projects
assigned to them?

...

SELECT
FROM
WHERE

...

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

Result of Subquery

Final Result set

B01
C01
D01
D11
D21
E01
E11
E21

DEPTNO DEPTNAME
A00

SPIFFY COMPUTER SERVICE

Copyright IBM Corporation 2012, 2013

Figure 7-6. Subquery using NOT IN

CE1216.1

Notes:

cl

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.

Ex

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.

pr

For an IN predicate, if any of the non-null values returned by the subquery match any of the
non-null values of the column being searched in the outer query, the rows in the outer
query that contain the matching value will appear in the final result set. Nulls in the
subquery result will never match nulls in the outer query result.
When the IN is prefaced with a NOT, as in the example, the subquery should be written to
return only non-null values. Then, all of the rows of the outer query that do not match any of
the values returned by the subquery will appear in the result set. If the NOT IN subquery
returns a null, the outer query will always produce an empty result set!
Copyright IBM Corp. 2013

Unit 7. Using Subqueries


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

7-7

Student Notebook

There are three methods available to ensure that the subquery does not return the null
value:
1. Defining the columns in the subquery as NOT NULL
2. Coding the WHERE IS NOT NULL predicate in the subquery

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

3. Using the COALESCE function

7-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Subquery within HAVING clause

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

I need a list of the departments whose


average salary for non-managers is higher
than the company-wide average for
non-managers. The department with the
highest average should be listed first.
SELECT
FROM
WHERE
GROUP BY
HAVING

ORDER BY

WORKDEPT, AVG(SALARY) AS AVG_WORKDEPT


EMPLOYEE
JOB <> 'MANAGER'
WORKDEPT
AVG(SALARY) > (SELECT AVG(SALARY)
FROM EMPLOYEE
WHERE JOB <> 'MANAGER')
AVG_WORKDEPT DESC;

Final Result
WORKDEPT
A00
C01

AVG_WORKDEPT
42833.33333333
26110.00000000

Result of Subquery
25188.80000000

Copyright IBM Corporation 2012, 2013

Figure 7-7. Subquery within HAVING clause

CE1216.1

Notes:

cl

Subqueries can be also used in a HAVING condition for placing conditions on the groups
that are included in the final result set. Remember that the HAVING clause is to groups of
rows, as the WHERE clause is to individual rows.

pr

Ex

In order to not make the query even more complex, the example above does not include
the ROUND and DECIMAL scalar functions, which would clean up the extra digits of
precision to the right of the decimal point. Whenever you invoke multiplication, division, or
the AVG column function, you will probably want to utilize the DECIMAL and ROUND
functions to make the result set more presentable.

Copyright IBM Corp. 2013

Unit 7. Using Subqueries


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

7-9

Student Notebook

Restrictions/Reminders
Subqueries

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

Copyright IBM Corporation 2012, 2013

Figure 7-8. Restrictions/Reminders

CE1216.1

Notes:

The outer query appears first (on the left), and then the subquery appears in the WHERE
(or HAVING) clause (on the right).

cl

Subqueries are always enclosed in parentheses.

pr

Ex

Subqueries can return either single or multiple values, but the number of values returned
must be compatible with the operator in the outer query (i.e. for the basic predicate
operators <, >,=, etc. the subquery must return no more than one value for an IN list, the
subquery may return multiple values)

7-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Checkpoint

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 might be coded:

a. WHERE SALARY > (SELECT SALARY FROM EMPLOYEE..)


b. WHERE SALARY = (SELECT MAX(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 2012, 2013

Figure 7-9. Checkpoint

CE1216.1

Notes:

Please write your answers here:


1.

cl

2.

pr

Ex

Copyright IBM Corp. 2013

Unit 7. Using Subqueries


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

7-11

Student Notebook

Unit summary

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Having completed 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.

Copyright IBM Corporation 2012, 2013

Figure 7-10. Unit summary

CE1216.1

pr

Ex

cl

Notes:

7-12 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit 8. Maintaining Data


What this unit is about

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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


Checkpoint questions

pr

Ex

cl

Machine labs

Copyright IBM Corp. 2013

Unit 8. Maintaining Data


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

8-1

Student Notebook

Unit objectives

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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.

Copyright IBM Corporation 2010, 2013

Figure 8-1. Unit objectives

CE1216.1

Notes:

pr

Ex

cl

Creating tables is normally done by database administrators. For testing 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. 2013


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

V7.0
Student Notebook

Uempty

TESTEMP table

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPNO LASTNAME WORKDEPT HIREDATE SALARY BONUS


000010
000020
000030
000050
000111

HAAS
THOMPSON
KWAN
GEYER
SMITH

A00
B01
C01
E01
C01

1965-01-01
1973-10-10
1975-04-04
1949-08-17
1998-06-25

52750.00
41250.00
38250.00
40175.00
25000.00

1000.00
800.00
800.00
800.00
-

Copyright IBM Corporation 2010, 2013

Figure 8-2. TESTEMP table

CE1216.1

Notes:

pr

Ex

cl

The visual shows the contents of the TESTEMP table. The TESTEMP table consists of just
a subset of the columns and a subset of the rows from the EMPLOYEE sample table. This
table will be the basis for the exercises of this unit.

Copyright IBM Corp. 2013

Unit 8. Maintaining Data


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

8-3

Student Notebook

CREATE TABLE TESTEMP

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

CREATE TABLE TESTEMP


(EMPNO
CHAR(6)
LASTNAME
VARCHAR(15)
WORKDEPT
CHAR(3)
HIREDATE
DATE
SALARY
DECIMAL(9,2)
BONUS
DECIMAL(9,2)

NOT NULL,
NOT NULL,
,
,
,

);

-- IN clause

Varies according to the DB2 platform, in


terms of requirements, defaults and syntax

Copyright IBM Corporation 2010, 2013

Figure 8-3. CREATE TABLE TESTEMP

CE1216.1

Notes:

cl

This CREATE TABLE statement creates the TESTEMP table. The syntax for CREATE
statements is CREATE object-type object-name. For tables, the column definitions then
follow the table-name, enclosed in parentheses. For each column the creator specifies a
column-name, data type (and optionally a length) and NULL attribute.

pr

Ex

In addition to the column definitions, an IN clause may be required. The format of the IN
clause depends on the environment. For more details about the IN clause, refer to the SQL
Reference manual for the environment in which you are operating.

8-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

CREATE VIEW PERSINFO


VIEW PERSINFO AS
EMPNO, LASTNAME,
SALARY AS YEAR_SAL
TESTEMP
WORKDEPT = C01 ;

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

CREATE
SELECT
FROM
WHERE

SELECT *
FROM PERSINFO ;

EMPNO LASTNAME YEAR_SAL

000030
000111

KWAN
SMITH

38250.00
25000.00

Copyright IBM Corporation 2010, 2013

Figure 8-4. CREATE VIEW PERSINFO

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

Ex

cl

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 syntax may be used for renaming columns in a view:

pr

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. Users who are authorized to use view PERSINFO

Copyright IBM Corp. 2013

Unit 8. Maintaining Data


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

8-5

Student Notebook

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

may retrieve the three listed columns for employees whose department number is C01. All
other data in the TESTEMP table is not visible or accessible via the PERSINFO view.

8-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Inserting rows into the table


INSERT INTO TESTEMP

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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

OR

INSERT INTO TESTEMP

(EMPNO, LASTNAME, WORKDEPT, HIREDATE, SALARY)

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

EMPNO
000111

LASTNAME
SMITH

WORKDEPT
C01

HIREDATE
1998-06-25

SALARY
25000.00

BONUS
-

Copyright IBM Corporation 2010, 2013

Figure 8-5. Inserting rows into the table

CE1216.1

Notes:

cl

You may use an INSERT statement to insert rows 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 in the base
table.

Ex

In the first example, the column list is omitted. In this case, a value for each column in the
table must be provided between each set of parenthesis in the VALUES clause, in the
order they are defined for the base table.

pr

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

Unit 8. Maintaining Data


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

8-7

Student Notebook

DB2 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),

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

('000114', 'THOMPSON', 'C01', '2001-06-25', 25000, NULL)

8-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

INSERT multiple rows

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

INSERT INTO TESTEMP


SELECT EMPNO,LASTNAME,WORKDEPT,HIREDATE,SALARY,BONUS
FROM
EMPLOYEE
WHERE
EMPNO <= 000050 ;

SELECT * FROM TESTEMP ;

EMPNO
000111
000010
000020
000030
000050

LASTNAME
SMITH
HAAS
THOMPSON
KWAN
GEYER

WORKDEPT
C01
A00
B01
C01
E01

HIREDATE
1998-06-25
1965-01-01
1973-10-10
1975-04-05
1949-08-17

SALARY
25000.00
52750.00
41250.00
38250.00
40175.00

BONUS
1000.00
800.00
800.00
800.00

Copyright IBM Corporation 2010, 2013

Figure 8-6. INSERT multiple rows

CE1216.1

Notes:

cl

Instead of the VALUES clause, include a SELECT statement in the INSERT statement to
tell DB2 that another table or view contains the data for the new rows. This is often referred
to as a mass INSERT. 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.

Ex

If a columns list for the target table is used, then all of that tables NOT NULL columns must
be included, since DB2 must always provide a value for any column defined as NOT NULL.

pr

In the example above, we assume that the row for SMITH 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. 2013

Unit 8. Maintaining Data


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

8-9

Student Notebook

UPDATE columns (1 of 2)
Before:
LASTNAME
SMITH
HAAS
THOMPSON
KWAN
GEYER

WORKDEPT
C01
A00
B01
C01
E01

HIREDATE
1998-06-25
1965-01-01
1973-10-10
1975-04-05
1949-08-17

SALARY
25000.00
52750.00
41250.00
38250.00
40175.00

BONUS
1000.00
800.00
800.00
800.00

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPNO
000111
000010
000020
000030
000050

UPDATE TESTEMP
SET BONUS = 500,
SALARY = 26000
WHERE EMPNO = 000111 ;

After:

EMPNO
000111
000010
000020
000030
000050

LASTNAME
SMITH
HAAS
THOMPSON
KWAN
GEYER

WORKDEPT
C01
A00
B01
C01
E01

HIREDATE
1998-06-25
1965-01-01
1973-10-10
1975-04-05
1949-08-17

SALARY
26000.00
52750.00
41250.00
38250.00
40175.00

BONUS
500.00
1000.00
800.00
800.00
800.00

Copyright IBM Corporation 2010, 2013

Figure 8-7. UPDATE columns (1 of 2)

CE1216.1

Notes:

The UPDATE statement updates the values of the specified columns for one ore more rows
of a table or view.

Ex

cl

Our new colleague, Mr. Smith (employee number 000111) receives at 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

pr

SET BONUS = NULL

WHERE EMPNO = '000111'

8-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

UPDATE columns (2 of 2)
Before:
LASTNAME
SMITH
HAAS
THOMPSON
KWAN
GEYER

WORKDEPT
C01
A00
B01
C01
E01

HIREDATE
1998-06-25
1965-01-01
1973-10-10
1975-04-05
1949-08-17

SALARY
26000.00
52750.00
41250.00
38250.00
40175.00

BONUS
500.00
1000.00
800.00
800.00
800.00

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPNO
000111
000010
000020
000030
000050

UPDATE TESTEMP
SET SALARY = SALARY + 1000
WHERE WORKDEPT = C01 ;

After:

EMPNO
000111
000010
000020
000030
000050

LASTNAME
SMITH
HAAS
THOMPSON
KWAN
GEYER

WORKDEPT
C01
A00
B01
C01
E01

HIREDATE
1998-06-25
1965-01-01
1973-10-10
1975-04-05
1949-08-17

SALARY
27000.00
52750.00
41250.00
39250.00
40175.00

BONUS
500.00
1000.00
800.00
800.00
800.00

Copyright IBM Corporation 2010, 2013

Figure 8-8. UPDATE columns (2 of 2)

CE1216.1

Notes:

Our department C01 has finished a project with great success. The salary of all employees
should be increased by 1,000.

pr

Ex

cl

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

Unit 8. Maintaining Data


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

8-11

Student Notebook

DELETE rows
Before:
LASTNAME
SMITH
HAAS
THOMPSON
KWAN
GEYER

WORKDEPT
C01
A00
B01
C01
E01

HIREDATE
1998-06-25
1965-01-01
1973-10-10
1975-04-05
1949-08-17

SALARY
27000.00
52750.00
41250.00
39250.00
40175.00

BONUS
500.00
1000.00
800.00
800.00
800.00

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

EMPNO
000111
000010
000020
000030
000050

DELETE FROM TESTEMP


WHERE EMPNO = 000111 ;

After:

EMPNO
000010
000020
000030
000050

LASTNAME
HAAS
THOMPSON
KWAN
GEYER

WORKDEPT
A00
B01
C01
E01

HIREDATE
1965-01-01
1973-10-10
1975-04-05
1949-08-17

SALARY
52750.00
41250.00
39250.00
40175.00

BONUS
1000.00
800.00
800.00
800.00

Copyright IBM Corporation 2010, 2013

Figure 8-9. DELETE rows

CE1216.1

Notes:

cl

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. In the example above, since Mr. Smith has left the company, we therefore need
to delete the row with employee number 000111.

Ex

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 .

pr

Because the WHERE clause is so important when changing existing table data (UPDATE,
DELETE), it is recommended that the statement be tested in such a way that does not
permanently change the data until it is determined that the statement is logically correct,
changing only the intended rows and columns, and changing them correctly.

8-12 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Prototyping Change SQL using a unit of work

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

SPUFI / CLP / GUI Command Editor will accommodate


unit of work processing
Prototyping an INSERT, UPDATE, DELETE
1.SELECT ... ;

2.INSERT ... ; (or UPDATE, DELETE)


3.SELECT ... ;

4.ROLLBACK ... ;

Copyright IBM Corporation 2010, 2013

Figure 8-10. Prototyping Change SQL using a unit of work

CE1216.1

Notes:

Let's take a minute to address the issue of change SQL statements i.e., INSERT,
UPDATE, and DELETE statements. These statements change the table data.

Ex

cl

In order to test whether or not our SQL statement is executing correctly, we first run several
SQL statements as a unit of work, which means that the work is not made permanent
unless all SQL statements finish successfully. If one statement fails, all work done by the
statements that completed up to that point will be undone. Semicolons are used to end a
query when multiple queries are stacked within a unit of work.

pr

Lets describe the statements above in a little more detail. The first SELECT statement
(known as the BEFORE SELECT) displays what the table data looks like before the
change SQL statement is executed. The second SELECT statement (known as the
AFTER SELECT) displays the table data as it is after INSERT, UPDATE or DELETE
statement has run. By comparing the result sets of the two SELECTs, the application
programmer should be able to determine if the effects of the SQL were what was expected.

Copyright IBM Corp. 2013

Unit 8. Maintaining Data


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

8-13

Student Notebook

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

The ROLLBACK statement will undo all of the changes to the data affected by the INSERT,
UPDATE or DELETE. Therefore, this unit of work approach is an effective technique for
testing the logic of change SQL statements, while at the same time preserving your data
in its original state.

8-14 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

DROP TABLE TESTEMP

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Now test table TESTEMP


is no longer needed.

DROP TABLE TESTEMP ;

VIEW PERSINFO is also


automatically dropped
Copyright IBM Corporation 2010, 2013

Figure 8-11. DROP TABLE TESTEMP

CE1216.1

Notes:

When executing the statement above - DROP TESTEMP, DB2 deletes the object, that is,
the table.

Ex

cl

It is very easy to remove a DB2 object (if you have the privilege to do so). The DROP
statement is issued in order to delete the definition of the table TESTEMP from the DB2
catalog. But is this all that happens?

There is a hierarchy of objects in DB2. Indexes, views and other objects can be based on
(and therefore dependent upon) DB2 tables. Therefore, when you DROP an object, there
may be other implications to consider.

pr

For example, here is what happens when the DROP TABLE TESTEMP statement is
executed:
1. The target object (TESTEMP table) is deleted.
2. Any objects dependent on TESTEMP are deleted (indexes, views, etc.).

3. The security/authorization scheme for both target and dependent objects is deleted.

Copyright IBM Corp. 2013

Unit 8. Maintaining Data


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

8-15

Student Notebook

4. All data in both the target and dependent objects is deleted.


5. Any DB2 programs (Plans, Packages) that reference either the target or dependent
objects are invalidated.

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Therefore, you want to be cautious with the use of the DROP statement. There is a
preventative measure that the DBA may choose in order to minimize the danger of
inadvertently deleting DB2 objects in the catalog. When you CREATE a table, after the
column specifications, the DBA can include the WITH RESTRICT ON DROP option. When
this option is in effect, DB2 disallows the DROPping of the table, and even disallows the
DROPping of the tablespace or database containing the protected table. This restriction
option can also be added to an already existing table, by issuing an ALTER TABLE
statement, with an ADD RESTRICT ON DROP clause.

pr

Ex

cl

In order to delete such a table, the DBA would first need to issue the statement ALTER
TABLE TESTEMP DROP RESTRICIT ON DROP. If that statement executed successfully,
then the DBA could issue a DROP TABLE TESTEMP, and DB2 would delete the table
definition and all dependent objects, as described above.

8-16 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Reminders

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

You must be authorized to execute statements which change table


content
You must be authorized to execute CREATE/DROP table statements
Inserting a row into a view actually inserts the row into the table on
which the view is based
Deleting a row of a view actually deletes the row of the table on which
the view is based
Updating a row of a view actually updates the row of the table on which
the view is based
Search conditions in the WHERE clause qualifies rows to be updated
or deleted
Omitting the WHERE clause of an UPDATE or DELETE statement
causes all rows of the table or view to be updated or deleted
Dropping a table has a number of other implications, such as dropping
dependent objects
Copyright IBM Corporation 2010, 2013

Figure 8-12. Reminders

CE1216.1

Notes:

pr

Ex

cl

Here are a number of review items for the unit regarding maintaining DB2 data. See your
Database Administrator (DBA) for appropriate authorizations.

Copyright IBM Corp. 2013

Unit 8. Maintaining Data


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

8-17

Student Notebook

Checkpoint

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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 2010, 2013

Figure 8-13. Checkpoint

CE1216.1

Notes:

Please write down your answers below:


1.

pr

Ex

cl

2.

8-18 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0
Student Notebook

Uempty

Unit summary

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Having completed 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.

Copyright IBM Corporation 2010, 2013

Figure 8-14. Unit summary

CE1216.1

pr

Ex

cl

Notes:

Copyright IBM Corp. 2013

Unit 8. Maintaining Data


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

8-19

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Student Notebook

8-20 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0.1
Student Notebook

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Appendix A. Checkpoint Solutions

pr

Ex

AP

Copyright IBM Corp. 2013

Appendix A. Checkpoint Solutions


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

A-1

Student Notebook

Unit 1

Checkpoint solutions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

1. True

2. Automatic verification of correctness


Date arithmetic
Date, time, timestamp sorting
Extraction of components
3.

CHAR (fixed length)

VARCHAR (variable length)


SMALLINT
INTEGER
BIGINT

DECIMAL(p,s)

4. SELECT

INSERT

UPDATE
DELETE

pr

Ex

cl

Copyright IBM Corporation 2010, 2013

A-2

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0.1
Student Notebook

Unit 2

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Checkpoint solutions
1. False
2. c

3. SELECT, FROM

4. Apostrophes (or single quotes)

5. False.They are joined by AND or OR.

cl

Copyright IBM Corporation 2010, 2013

pr

Ex

AP

Copyright IBM Corp. 2013

Appendix A. Checkpoint Solutions


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

A-3

Student Notebook

Unit 3

Checkpoint solutions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

1. True

2. This is a tricky question. The correct answer is a, if you


are using the newer syntax, and the answer is b if you are
using the older syntax.
3. Correlation names provide a way of giving an abbreviated
name for a table, and make qualifying column names
easier.

pr

Ex

cl

Copyright IBM Corporation 2010, 2013

A-4

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0.1
Student Notebook

Unit 4

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Checkpoint solutions
1. To the nearest 100.

2. SELECT DAYS(EMSTDATE) - DAYS(EMENDATE)

3. DECIMAL, ROUND, UPPER, LOWER, SUBSTR, CHAR,


YEAR, MONTH, DAY, DAYS, HOUR, MINUTE, SECOND,
COALESCE, CONCAT

cl

Copyright IBM Corporation 2010, 2013

pr

Ex

AP

Copyright IBM Corp. 2013

Appendix A. Checkpoint Solutions


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

A-5

Student Notebook

Unit 5

Checkpoint solutions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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.

pr

Ex

cl

Copyright IBM Corporation 2010, 2013

A-6

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0.1
Student Notebook

Unit 6

Checkpoint solutions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

1. False. The SELECTs must follow very strict UNION rules.


2. a
3. Equal number of columns.
Compatible data types.
ORDER BY must be the last clause.
(In the ORDER BY clause, numbers must be used when
the column being sorted does not have the same name in
all SELECTs)

cl

Copyright IBM Corporation 2010, 2013

pr

Ex

AP

Copyright IBM Corp. 2013

Appendix A. Checkpoint Solutions


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

A-7

Student Notebook

Unit 7

Checkpoint solutions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

1. True
2. b

3. IN

pr

Ex

cl

Copyright IBM Corporation 2012, 2013

A-8

DB2 SQL Workshop

Copyright IBM Corp. 2013


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

V7.0.1
Student Notebook

Unit 8

Checkpoint solutions

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

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


2. a, b

cl

Copyright IBM Corporation 2010, 2013

pr

Ex

AP

Copyright IBM Corp. 2013

Appendix A. Checkpoint Solutions


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

A-9

pr

Ex

cl

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

Student Notebook

A-10 DB2 SQL Workshop

Copyright IBM Corp. 2013


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

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

backpg

pr

cl

Ex
V7.0.1

Back page

pr

u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.

cl

Ex

CONTACTO
Telfono
91 761 21 78
Pngase en contacto con nuestro equipo y le
informaremos de cualquier duda o cuestin
que pueda surgirle.

Email
formacion@arrowecs.es
Mndenos un email y le atenderemos
enseguida.

Online
@Arrow_Edu_ES
O bien puede contactarnos a travs de
nuestro perfil en Twitter.

Vistenos
Arrow ECS Education Services
Avenida de Europa 21,
Parque Empresarial La Moraleja
28108 Alcobendas, Madrid

EDUCATION
S

Вам также может понравиться