Академический Документы
Профессиональный Документы
Культура Документы
Intelligence
Data
Centre
Cloud
Mobility
Student Manual
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
Student Notebook
pr
Ex
cl
ERC 6.1
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.
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
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.
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
cl
pr
Ex
TOC
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
.
cl
pr
Ex
iv
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
.
cl
pr
Ex
TOC
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
.
pr
Ex
cl
vi
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.
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
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
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
Audience
Prerequisites
pr
Ex
cl
Objectives
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
.
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
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
V7.0
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Uempty
cl
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
pr
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
.
CE1216.1
pr
Ex
cl
Notes:
0-2
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
CE1216.1
pr
Ex
cl
Notes:
0-3
Student Notebook
Introductions
Name
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Company
CE1216.1
pr
Ex
cl
Notes:
0-4
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
.
pr
Ex
cl
Checkpoint questions
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
.
CE1216.1
pr
Ex
cl
Notes:
1-2
V7.0
Student Notebook
pr
Ex
cl
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Uempty
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
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
D21
AD3111
PAYROLL PROGRAMMING
D21
AD3112
AD3113
ACCOUNT PROGRAMMING
D21
IF1000
QUERY SERVICES
C01
...
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
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
V7.0
Student Notebook
Uempty
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
CE1216.1
Notes:
Human language
Tables
Ex
cl
Data requestor
pr
A medium for communication - phone, notes, etc. The medium depends on the
environment. The medium could be a program, a query tool, etc.
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
.
COMMIT
ROLLBACK
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
V7.0
Student Notebook
Uempty
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.
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
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Seattle
PARTS
Chicago
Atlanta
PROD. PARTS
ATLANTA.PROD. PARTS
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, _
Table name
unique to
owner/schema
Column
names
unique to
table
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
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Data Type
SMALLINT
INTEGER
BIGINT
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.
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
.
Data Type
Comment
CHAR(n) or
CHARACTER(n)
VARCHAR(n)
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Data Type
DATE
YYYYMMDD
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
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
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.
V7.0
Student Notebook
Uempty
TIME
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
YYYYMMDDHHMMSSXXXXXX
yyyy-mm-dd-hh.mm.ss.xxxxxx
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
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
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.
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)
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
Ex
Data type (and length, if required based upon the data type)
pr
NULL characteristic
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
NOT NULL
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
"nullable"
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 WITH DEFAULT Column must always have a value - if we don't supply
one, DB2 does.
pr
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.
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.
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
.
DEPARTMENT
PROJECT
EMPLOYEE
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.
V7.0
Student Notebook
pr
Ex
cl
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Uempty
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
.
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
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
pr
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).
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
.
CE1216.1
Notes:
cl
2.
Ex
3.
pr
4.
V7.0
Student Notebook
Uempty
Unit summary
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
pr
Ex
cl
Machine Labs
2-1
Student Notebook
Unit objectives
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
2-2
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
------
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
Employee number
FIRSTNME
First name
MIDINIT
Middle initial
LASTNAME
Last name
WORKDEPT
Department number
PHONENO
Phone number
HIREDATE
Hire date
pr
Ex
EMPNO
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
------
CE1216.1
Notes:
EMPNO*
cl
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
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
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
--------
CE1216.1
Notes:
Department number
DEPTNAME
Department name
MGRNO
Ex
cl
DEPTNO
ADMRDEPT
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
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
CE1216.1
Notes:
Project number
PROJNAME
DEPTNO
Responsible department
Project name
RESPEMP
PRSTAFF
PRSTDATE
pr
Ex
cl
PROJNO
PRENDATE
MAJPROJ
2-6
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
Notes:
Employee number
PROJNO
Project number
ACTNO
Activity number
Ex
cl
EMPNO
EMSTDATE
EMENDATE
pr
EMPTIME
2-7
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
Column names
Arithmetic expressions
Column functions
Concatenation
FROM
WHERE
ORDER BY
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
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT *
FROM DEPARTMENT;
DEPTNO DEPTNAME
A00
B01
C01
D01
D11
D21
E01
E11
E21
000010
000020
000030
000060
000070
000050
000090
000100
A00
A00
A00
A00
D01
D01
A00
E01
E01
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.
2-9
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
DB2:
DEPTNO
A00
B01
C01
D01
D11
DEPTNAME
SPIFFY COMPUTER SERVICE DIV.
PLANNING
INFORMATION CENTER
DEVELOPMENT CENTER
MANUFACTURING SYSTEMS
MGRNO
000010
000020
000030
000060
ADMRDEPT
A00
A00
A00
A00
D01
LOCATION
-
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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.
2-11
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
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
CE1216.1
Notes:
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:
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
.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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.
2-15
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
.
.
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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.
2-17
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
DEPTNO
A00
B01
C01
D01
E01
DEPTNO, ADMRDEPT
DEPARTMENT
ADMRDEPT = 'A00;
ADMRDEPT
A00
A00
A00
A00
A00
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.
V7.0
Student Notebook
Uempty
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.
2-19
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
LASTNAME
KWAN
LUCCHESSI
LASTNAME, EDLEVEL
EMPLOYEE
EDLEVEL >= 19;
EDLEVEL
20
19
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).
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:
OR
OR
SALARY >
OR
OR
SALARY <
OR
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.
2-21
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Y
Y
Y
Y
Y
Y
Yellow OR Oval
Y
Y
Y
Y
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
AND
EMPNO
000130
JOB
ANALYST
EDLEVEL
16
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.
2-23
Student Notebook
Multiple conditions: OR
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
OR
ORDER BY
EMPNO
000130
000140
000030
JOB
ANALYST
ANALYST
MANAGER
EDLEVEL
16
18
20
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
AND
OR
ORDER BY
EMPNO
000130
000140
000220
000020
000010
JOB
ANALYST
ANALYST
DESIGNER
MANAGER
PRES
EDLEVEL
16
18
18
18
18
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.
2-25
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
AND
OR
EMPNO
000130
000140
JOB
ANALYST
ANALYST
EDLEVEL
16
18
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
V7.0
Student Notebook
Uempty
SELECT with IN
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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
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
2-27
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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
pr
is equivalent to
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
DEPTNO
D01
DEPTNAME
DEVELOPMENT CENTER
MGRNO
-
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.
2-29
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
LASTNAME
EMPLOYEE
LASTNAME LIKE 'G% ;
LASTNAME
GEYER
GOUNOT
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'.
V7.0
Student Notebook
Uempty
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
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.
2-31
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
LASTNAME
EMPLOYEE
LASTNAME LIKE '_C% ;
LASTNAME
SCOUTTEN
SCHNEIDER
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.
V7.0
Student Notebook
Uempty
Negation
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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
2-33
Student Notebook
Checkpoint
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
Notes:
cl
2.
Ex
3.
4.
pr
5.
V7.0
Student Notebook
Uempty
Unit summary
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
2-35
pr
Ex
cl
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Student Notebook
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
pr
Ex
cl
Machine labs
3-1
Student Notebook
Unit objectives
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
3-2
V7.0
Student Notebook
Uempty
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
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.
3-3
Student Notebook
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
...
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
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
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
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
3-5
Student Notebook
Correlation names
SELECT
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
...
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
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
.
DEPARTMENT
MGRNO . . .
DEPTNO DEPTNAME
A00
B01
C01
D01
D11
D21
E01
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
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.
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
WHERE
DEPTNAME
MGRNO
LASTNAME
ADMINISTRATION SYSTEMS
000070
PULASKI
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
V7.0
Student Notebook
Uempty
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
DEPTNAME
000010
HAAS
A00
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.
3-9
Student Notebook
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
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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).
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).
V7.0
Student Notebook
Uempty
ADMIN SERVICES
GENERAL AD SYSTEMS
PAYROLL PROGRAMMING
PERSONNEL PROGRAMMING
ACCOUNT. PROGRAMMING
QUERY SERVICES
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
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
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.
3-13
Student Notebook
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
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.
V7.0
Student Notebook
Uempty
Checkpoint
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
Notes:
cl
2.
pr
Ex
3.
3-15
Student Notebook
Unit summary
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
pr
Ex
cl
Machine labs
4-1
Student Notebook
Unit objectives
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
4-2
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
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
CE1216.1
Notes:
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.
4-3
Student Notebook
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
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
CE1216.1
Notes:
cl
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.
4-5
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
...
...
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
...
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
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
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?
4-7
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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
V7.0
Student Notebook
Uempty
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
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.
4-9
Student Notebook
(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
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.
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
SQL
B AS I CS
SQL
A DV A NCED
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
2. Where to start searching (the displacement, in bytes, into the first argument)
Ex
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.
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
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
+ or
OR
* or
(..)
AND
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.
4-13
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Internal Format
Internal Length
DATE
yyyymmdd
4 bytes
TIME
hhmmss
3 bytes
TIMESTAMP
yyyymmddhhmmssnnnnnn
10 bytes
Time Format
Length
ISO
hh.mm.ss
USA
hh:mm AM
8 bytes mm/dd/yyyy
hh:mm PM
8 bytes
10 bytes
EUR
hh.mm.ss
dd.mm.yyyy
JIS
hh:mm:ss
LOCAL
???
???
???
10 bytes
???
26 bytes
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
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
.
4-15
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
03:30 PM
15.30.00
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.
V7.0
Student Notebook
Uempty
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
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
4-17
Student Notebook
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
CURRENT TIME
-----------09.45.22
CURRENT TIMESTAMP
----------------2011-07-29-09.45.22.030000
CE1216.1
Notes:
cl
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
PROJNO
-----PL2100
PRENDATE
-------09/15/2011
DAY
--15
MONTH
----09
YEAR
---2011
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.
4-19
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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.
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).
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
PROJNO
PL2100
MA2113
DAYS
257
289
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
4-21
Student Notebook
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
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
pr
V7.0
Student Notebook
Uempty
Checkpoint
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
Notes:
cl
2.
pr
Ex
3.
4-23
Student Notebook
Unit summary
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
pr
Ex
cl
Checkpoint
5-1
Student Notebook
Unit objectives
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
5-2
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)
__________ _____
__________ _____
__________ _____
__________ _____
__________ _____
CE1216.1
Notes:
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.
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)
MIN(expression)
MAX(expression)
COUNT(*)
COUNT(DISTINCT col-name)
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
V7.0
Student Notebook
Uempty
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.
5-5
Student Notebook
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
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
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:
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).
5-7
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
SUM(SALARY) AS SUM
FROM
EMPLOYEE
WHERE
WORKDEPT LIKE D% ;
SUM
373020.00
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
V7.0
Student Notebook
Uempty
GROUP BY
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
ORDER BY
WORKDEPT, SALARY
EMPLOYEE
WORKDEPT IN ('A00', 'B01', 'C01')
WORKDEPT ;
WORKDEPT
SELECT
FROM
WHERE
GROUP BY
ORDER BY
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
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
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
5-9
Student Notebook
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
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
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).
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
GROUP BY
ORDER BY
WORKDEPT
A00
B01
C01
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
SUM
128500.00
41250.00
90470.00
WORKDEPT
A00
C01
SUM
128500.00
90470.00
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.
5-11
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
WORKDEPT JOB
A00
A00
A00
C01
CLERK
PRES
SALESREP
ANALYST
AVG
29250.00000000
52750.00000000
46500.00000000
26110.00000000
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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.
5-13
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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.
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
Column functions
Columns (which must be specified in a GROUP BY)
CE1216.1
Notes:
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)).
5-15
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
ORDER BY 3 DESC ;
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.
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.
5-17
Student Notebook
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
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
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
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)
5-19
Student Notebook
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
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)
V7.0
Student Notebook
Uempty
Checkpoint
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY
CE1216.1
Notes:
cl
2.
Ex
3.
pr
4.
5-21
Student Notebook
Unit summary
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
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.
Produce a single result set containing data from more than one
query
pr
Ex
cl
Machine labs
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
.
CE1216.1
pr
Ex
cl
Notes:
6-2
V7.0
Student Notebook
Uempty
QUERY 2
SELECT some_columns
FROM some_table(s)
WHERE some_conditions
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
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.
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
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
UNION ALL
-- QUERY 2
SELECT some_columns
FROM some_table(s)
WHERE some_conditions
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
Notes:
pr
Ex
cl
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
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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.
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
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
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
CE1216.1
Notes:
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
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.
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
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
UNION ALL
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
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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
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.
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
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.
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.
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
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
.
CE1216.1
Notes:
cl
2.
pr
Ex
3.
V7.0
Student Notebook
Uempty
Unit summary
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
pr
Ex
cl
Machine labs
7-1
Student Notebook
Unit objectives
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
First SELECT:
SELECT
FROM
AVG(SALARY)
EMPLOYEE;
27303
Second SELECT:
SELECT
FROM
WHERE
EMPNO, LASTNAME
EMPLOYEE
SALARY > 27303;
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
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).
7-3
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
SELECT
EMPNO, LASTNAME
FROM
EMPLOYEE
WHERE
EMPLOYEE);
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
V7.0
Student Notebook
Uempty
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
.
EMPLOYEE
WHERE
EMPNO
LASTNAME
000290
PARKER
EMPLOYEE);
BONUS
300
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.
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
.
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
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
V7.0
Student Notebook
Uempty
DEPTNAME
A00
B01
C01
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
B01
C01
D01
D11
D21
E01
E11
E21
DEPTNO DEPTNAME
A00
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
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
.
7-8
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
ORDER BY
Final Result
WORKDEPT
A00
C01
AVG_WORKDEPT
42833.33333333
26110.00000000
Result of Subquery
25188.80000000
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.
7-9
Student Notebook
Restrictions/Reminders
Subqueries
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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)
V7.0
Student Notebook
Uempty
Checkpoint
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
Notes:
cl
2.
pr
Ex
7-11
Student Notebook
Unit summary
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
pr
Ex
cl
Machine labs
8-1
Student Notebook
Unit objectives
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
V7.0
Student Notebook
Uempty
TESTEMP table
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
-
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.
8-3
Student Notebook
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
NOT NULL,
NOT NULL,
,
,
,
);
-- IN clause
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CREATE
SELECT
FROM
WHERE
SELECT *
FROM PERSINFO ;
000030
000111
KWAN
SMITH
38250.00
25000.00
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
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
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
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
OR
EMPNO
000111
LASTNAME
SMITH
WORKDEPT
C01
HIREDATE
1998-06-25
SALARY
25000.00
BONUS
-
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.
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
.
8-8
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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
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.
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
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
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
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.
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
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
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
4.ROLLBACK ... ;
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.
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.
V7.0
Student Notebook
Uempty
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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.
8-15
Student Notebook
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.
V7.0
Student Notebook
Uempty
Reminders
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
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.
8-17
Student Notebook
Checkpoint
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
Notes:
pr
Ex
cl
2.
V7.0
Student Notebook
Uempty
Unit summary
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
CE1216.1
pr
Ex
cl
Notes:
8-19
pr
Ex
cl
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Student Notebook
V7.0.1
Student Notebook
cl
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
pr
Ex
AP
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
DECIMAL(p,s)
4. SELECT
INSERT
UPDATE
DELETE
pr
Ex
cl
A-2
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
cl
pr
Ex
AP
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
pr
Ex
cl
A-4
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.
cl
pr
Ex
AP
A-5
Student Notebook
Unit 5
Checkpoint solutions
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
pr
Ex
cl
A-6
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
.
cl
pr
Ex
AP
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
A-8
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
.
cl
pr
Ex
AP
A-9
pr
Ex
cl
u
oy si
ec vo
to fo
C rm
.F a
.T ci
.I. n
C
.
Student Notebook
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