Database Fundamentals TH

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 257

Database Fundamentals

A book for the community by the community

: Neeraj Sharma, Liviu Perniu, Raul F. Chong, Abhishek Iyer, Adi-Cristina Mitea,
Chaitali Nandan, Mallarswami Nonvinkere, Mirela Danubianu

: .

1 ( 2555)
Copyright IBM Corporation 2010. All rights reserved.

IBM Canada

8200 Warden Avenue


Markham, ON
L6G 1C7
Canada

IBM DB2 Express-C 9.7 Linux, UNIX


Windows.

IBM Database Fundamentals










IBM Director of Licensing
IBM Corporation
North Castle Drive
Armonk, NY 10504-1785
U.S.A.
Double-byte character set (DBCS)
:
Intellectual Property Licensing
Legal and Intellectual Property Law
IBM Japan, Ltd.
3-2-12, Roppongi, Minato-ku, Tokyo 106-8711

INTERNATIONAL BUSINESS MACHINES CORPORATION







//

ibm.com International Business Machines Corp.



"Copyright
and trademark information" www.ibm.com/legal/us/en/copytrade.shtml
Java Java Sun Microsystems,
Inc.
Microsoft Windows Microsoft Corporation

Linux Linus Torvalds

UNIX The Open Group


1 14
5 15
1 - 2 20
1.1 ............................................................................................ 20
1.2 ....................................................................... 21

1.2.1 ......................................................... 21
1.3 (Information Models) (Data Models)2 23
1.4 .................................................................................. 24
1.4.1 (Network model)2 25

1.4.2 (Hierarchical Model)5 25


1.4.3 (Relational model)2 26
1.4.4 2 27
1.4.5 (Object-relational model)2 28
1.4.6 2 28
1.5 2 28

1.5.1 (Data Architect)....................................................... 28


1.5.2 (Database Architect).......................................... 29
1.5.3 (Database Administrator: DBA).................................. 29
1.5.4 (Application Developer)..................................... 30

1.6 .............................................................................................................. 31
1.7 ..................................................................................................... 31
1.8 3 31
2 3 34
2.1 3 34
2.2 3 36
2.2.1 (Attributes)............................................................................. 36
2.2.2 (Domains)....................................................................................... 37
2.2.3 (Tuples)........................................................................................... 37
2.2.4 (Relations)...................................................................................... 38
2.2.5 (Schemas)................................................................................... 38
2.2.6 (Keys)................................................................................................. 39

2.3 4 41
2.3.1 ..................................................................... 41
2.3.2 (Referential integrity)..................... 42
2.3.3 (Semantic integrity constraints)............... 43

2.4 .......................................................................................... 45
2.4.1 Union........................................................................................................ 45
2.4.2 Intersection.............................................................................................. 46
2.4.3 Difference................................................................................................ 46
2.4.4 Cartesian product.................................................................................... 47
2.4.5 Selection.................................................................................................. 48
2.4.6 Projection................................................................................................. 49
2.4.7 Join.......................................................................................................... 50
2.4.8 Division..................................................................................................... 52
2.5 ......................................................................................... 52
2.5.1 (Tuple-oriented relational calculus).................. 53

2.5.2 (Domain-oriented relational calculus).................. 54


2.6 .............................................................................................................. 55
2.7 ..................................................................................................... 55
2.8 5 57
3 6 60
3.1 6 60
3.2 ?6 62
3.2.1 6 62
3.2.2 6 62
3.2.3 6 63
3.3 - 1 3......................... 72
3.3.1 (Conceptual model)7 72
3.4 .......................................................................................................... 78
3.5 ..................................................................................................... 79
3.6 7 79
4 . ............................................................. 82
4.1 8 82
4.1.1 .............................................................. 83
4.1.2 .................................................................. 83
4.1.3 (Update Anomalies).......................... 83
4.2. (Decompositions).................................................... 84
4.3. Functional Dependencies............................................................................ 85
4.4 Functional Dependencies......................................................... 86
4.4.1 Armstrongs Axioms................................................................................. 87
4.4.2 closure set of attributes............................................................. 87
4.4.3 (Entailment).......................................................... 88
4.5 (Normal Forms)....................................................................... 88

4.5.1 1 (First Normal Form (1NF))..................................... 88


4.5.2 2 (Second Normal Form (2NF))................................ 90
4.5.3 3 (Third Normal Form (3NF)).................................... 91
4.5.4 Boyce-Codd Normal Form (BCNF)................................. 92
4.6 Decompositions....................................................................... 93
4.6.1 Lossless and Lossy Decompositions........................................................ 93
4.6.2 Dependency-Preserving.................................... 94

4.7 Minimal Cover9 95


4.8 Synthesis of 3NF schemas.......................................................................... 97
4.9 3NF decomposition............................................ 97
4.10 The Fourth Normal Form (4NF)................................................................. 98
4.10.1 Multi-valued dependencies..................................................................... 98
4.11 ............................................................................... 99
4.12 Library Management System - Part 2 of 3.............. 99
4.13 ..........................................................................................................102
4.14 .................................................................................................103
4.15 0103
5 - SQL ................................................................................106
5.1 SQL............................................................................................106
5.2 SQL1107
5.2.1 (Data Types).................................................................107
5.2.2 (Create Table)..................................................................108
5.2.3 (Schema)...........................................................................112
5.2.4 (View)....................................................................................113
5.2.5 ..................................................................113
5.2.6 ...........................113

5.2.7 ..................................................................113
5.3 SQL1114
5.3.1 (Select)..............................................................................114
5.3.2 (Insert)............................................................................115
5.3.3 (Delete)...............................................................................116
5.3.4 (Update).......................................................................116
5.4 (Table Joins)..................................117
5.4.1 Inner Join...........................................117
5.4.2 Outer Joins.......................................118
5.5 Union, Intersection, Difference.......................................121
5.5.1 Union......................................................................................................121
5.5.2 Intersection............................................................................................122

10

5.5.3 Difference (Except)................................................................................122


5.6 (Relational Operators)1123
5.6.1 (Grouping Operators)1123
5.6.2 Aggregation1124
5.6.3 HAVING1124
5.7 (Sub-queries)..................................................................................125
5.7.1 .................................................................125
5.7.2 ....................................................................125
5.7.3 Correlated Sub-query.............................................................................126
5.7.4 FROM Select1126
5.8 . ................................126

5.9 3................................................127
5.10 ..........................................................................................................132
5.11 .................................................................................................132
5.12 1133
6 Stored Procedure ...............................................................136
6.1 IBM Data Studio......................................................................136

6.2 Stored Procedures1138


6.2.1 Procedures............................................................................139
6.2.2 Stored Procedure......................................................................140
6.2.3 Stored Procedure............................................................143
6.3 1143
6.3.1 ....................................................................................143
6.3.2 .........................................................................................144

6.3.3 ................................................................................145
6.3.4 ..........................................................................146
6.4 ........................................................................................................146
6.5 ...................................................................................................146
6.6 1147
7 SQL ..................................................150

7.1 SQL ...............................................150


7.2 Transaction ?................................................................................151
7.3 Embedded SQL..........................................................................................151

7.3.1 Static SQL..............................................................................................152


7.3.2 SQL Dynamic1157
7.3.3 Static dynamic SQL...........................................161
7.4 Application Programming Interface (APIs) 1161

7.4.1 ODBC IBM Data Server CLI driver.....................................................162

11

7.4.2 JDBC.......................................................................................................163

7.5 pureQuery................................................................................................164
7.5.1 IBM pureQuery Client Optimizer............................................................166
7.6 ........................................................................................................167
7.7 ...................................................................................................168
7.8 1168
8 XML1170

8.1 XML..........................................................................................170
8.1.1 XML element ..........................................................171
8.1.2 XML (XML attribute).........................................................172
8.1.3 Namespaces...........................................................................................173
8.1.4 (Document Type Definition: DTD)1173

8.1.5 XML Schema...........................................................................................174


8.2 XML Schema............................................................................176
8.2.1 (simple types)............................................................176
8.2.2 (complex types)...........................................178
8.2.3 Integrity Constraints..............................................................................179
8.2.4 XML Schema....................................................................179
8.3 XPath........................................................................................................180
8.3.1 XPath (XPath data model - XDM)8181
8.3.2 Document node......................................................................................181
8.3.3 Path Expressions....................................................................................182
8.3.4 Advanced Navigation in XPath...............................................................182

8.3.5 XPath Semantics....................................................................................183


8.3.6 XPath Queries.........................................................................................185
8.4 XQuery.....................................................................................................185
8.4.1 XQuery .........................................................................................186
8.4.2 FLWOR expressions................................................................................187
8.4.3 Joins XQuery...............................................................................188
8.4.4 (User-defined functions)1188
8.4.5 XQuery XML Schema.......................................................................189
8.4.6 (Grouping and aggregation)...............................189
8.4.7 Quantification........................................................................................190
8.5 XSLT..........................................................................................................190
8.6 SQL/XML...................................................................................................192
8.6.1 XML Document................................................192
8.6.2 XML...............................................................193
8.6.3 SQL / XML...................................................................................193

12

8.7 XML ..................................197


8.8 XML...............................................................197
8.8.1 XMLPARSE..............................................................................................197
8.8.2 XMLSERIALIZE.........................................................................................198
8.8.3 TRANSFORM expression.........................................................................198

8.9 ........................................................................................................199
8.10 .................................................................................................199
8.11 2200
9 ...................................................................204
9.1 . .........................................................204
9.1.1 0206
9.1.2 (Access Control)......................................................207
9.1.3 .......................................207
9.1.4 (Views)..............................................................................................212
9.1.5 (Integrity Control)...............................................212
9.1.6 .......................................................................................212
9.2 .............................................212
9.2.1 ..............................................................................212
9.2.2 ..............................................................................213
9.3 ............................................................................................................213
9.4 ...................................................................................................214
9.5 2214
10 - . ............................................................216
10.1 (Cloud computing) ?..............................216
10.1.1 Cloud..............................................................................217
10.1.2 Cloud computing...................................................217
10.1.3 Cloud....................................................................................218
10.1.4 Cloud............................................................221
10.1.5 Cloud...............................................................................222
10.2 ..........................................................223
10.2.1 2224
10.2.2 2225
10.2.3 .................................................................225
10.2.4 ....................................................226
10.2.5 2 226
10.2.6 DB2 .......................................................................................227
10.3 (Business intelligence and appliances)..............................227
10.4 db2university.com: Cloud ()..........227

13

10.4.1 Moodle...................................228
10.4.2 openID .................................................230
10.4.3 Cloud Amazon2231
10.4.4 Android .................................233
10.5 ......................................................................................................234

2236
1........................................................................................................236
2........................................................................................................237
3........................................................................................................237
4........................................................................................................238
5........................................................................................................238
6........................................................................................................238
7........................................................................................................239
8........................................................................................................239
9........................................................................................................239
DB22242
.1 DB2..........................................................................................242
.2.1 DB2..........................................................................................243
.2.2 DB2 .........................................................................244
.3 DB2..............................................................................................245
.3.1 Windows...............................................................................245
.3.2 DB2 Linux............................................................................245
.4 DB2.........................................................................................246
.4.1 Control Center........................................................................................246
.4.2 Command Line..........................................................................247
.5 DB2..................................................................................249
.6 DB2.........................................................................................250
.7 . ...............................................................................251
.8 ...........................................................................................252
.9 DB2.....................................................................................253
. ....................................................................................................254
........................................................................................................255

14

Database Fundamentals

Database Fundamentals
.


SQL XML

.
Database Fundamentals

15

16

DB2 on Campus Book Series

?



?

1
2 3 4
5, 6 7 SQL 8
XML SQL XQuery 9
10

A

()


db2univ@ca.ibm.com
"Database fundamentals book feedback"


SQL

NULL dir
SQL
SELECT flight

CREATE TABLE table_name

Getting started with DB2 Express-C


Getting started with InfoSphere Data Architect
Getting started with data warehousing
Getting started with DB2 application development

17

DB2 on Campus book series


www.bigdatauniversity.com

Textbooks **
Programming
Fundamentals

Cloud
Computing
IBM Data Studio

Database
Fundamentals
Software
Engineering &
Database
** Good for University/
College Courses

DB2
Express-C
DB2 App
Development

Ten steps to
career success
A career in
databases
**No software tought

Data
Warehouse

Eclipse

WAS CE

Java

pureQuery*

JNet
C/C++
Web 2.0
Open source
development

Career books **

InfoSphere
Data
Architect***

Adobe Flex
Ruby on Rails
PHP

SOA

Perl

Mobile App.
development

Python

* Some software is only available as a trial

Mac

The DB2 on Campus book series


Neeraj Sharma
Dynamic Warehousing Center of
Competency
Proof of
Concept (POC)
Liviu Perniu Automation Department at Transilvania University of Brasov

IBM 2006 Faculty Award Eclipse Innovation
Awards
Raul F. Chong DB2 on Campus IBM Toronto Laboratory
DB2 DB2 Raul
IBM 1997
DB2 IBM
DB2 Raul DB2 OS/390,
z/OS, Linux, UNIX DB2
DB2 Raul DB2
Understanding DB2 - Learning Visually with Examples 2nd Edition (ISBN-10:
0131580183) DB2 SQL PL Essential Guide
for DB2 UDB on Linux, UNIX, Windows, i5/OS, and z/OS (ISBN 0131477005)
DB2 on Campus

18

Abhishek Iyer Warehousing Center of Competency



Abhishek

Chaitali Nandan DB2 Advanced Technical Support


DB2
Chaitali
Adi-Cristina Mitea Hermann Oberth
Lucian Blaga University of Sibiu
distributed systems, parallel and distributed algorithms, fault tolerant systems
Adi-Cristina

Mallarswami Nonvinkere pureXML


DB2 pureXML
pureXML XML
Mallarswami IDUG Australasia, IDUG India,
IMTC
Mirela Danubianu Stefan cel Mare University of Suceava, Faculty of Electrical
Engineering and Computer Science Mirela
Craiova (1985 Automatizations and Computers) Stefan cel Mare
University of Suceava, (2009 - Management) Stefan
cel Mare University of Suceava (2006 -
)
Mirela
7 25 15

Agatha Colangelo

ION Designs, Inc

Data Modeler

Cuneyt Goksu

VBT Vizyon BilgiTeknolojileri

DB2 SME and IBM Gold


Consultant

Marcus Graham

IBM US

Software developer

Amna Iqbal

IBM Toronto Lab

Quality Assurance -Lotus Foundations

Leon Katsnelson

IBM Toronto Lab

Program Director, IBM


Data Servers

Jeff (J.Y.) Luo

IBM Toronto Lab

Fraser McArthur

IBM Toronto Lab

Technical Enablement
Specialist
Information Management Evangelist

10

5 7

10
7

19

Danna Nicholson

IBM US

Rulesh Rebello

IBM India

STG ISV Enablement,


Web Services
Advisory Manager IBM Software Group
Client Support

Suresh Sane

DST Systems, Inc

Database Architect

Nadim Sayed

IBM Toronto Lab

Ramona Truta

University of Toronto

User-Centered Design
Specialist
Lecturer

SQL
1

Natasha Tolub

Susan Visser

Raul F. Chong DB2 IBM Toronto Lab


10

1 -

(Database System Software)

1.1


(Relational database)

(Tree) (Hierarchical database)


(Network database)

1 - 21

1.2
(DataBase Management System: DBMS)

(Database server)

(Interface)


(Relational DataBase Management System: RDBMS)



1.2.1
.. 1960

mainframe

(Physical)

(Logical)

E.F. Codd San Jose 1970

A relational model of data for large shared data banks [1.1]

1.1

22

Self-describing data

Integration
Federation

Heterogeneous data

Extensibility
Distribution
Optimization
Data Dependence

Extending functionality
Scalability, parallellism

High performance
Logical Data Model

1.1
1.1

System R Codd
System R SQL/DS DB2

SQL

DB2 database server

Oracle, Microsoft SQL Server, INGRES, PostgreSQL, MySQL


dBASE

(Query)

DB2 DB2s optimizer DB2s op-

timizer SQL DB2s optimizer


CPU

DB2s optimizer
(Costbased)

DB2

Linux, UNIX Windows (Database Partitioning

Feature) DB2 Shared Nothing


Architecture CPU
(Parallelized)

1 - 23

SQL

.. 1970 SQL

SQL DB2
store procedure

DB2
Universal DB2 Universal Database (DB2 UDB)

Universal


DB2

(Data

Integration)

eXtensible Markup Language


(XML) XML

XML Web 2.0 Service-Oriented Architecture (SOA) XML

pureXML DB2 DB2

XML XML DB2 Engine


XQuery XML

pureXML DB2 XML


Cloud Computing

Cloud DB2 images Amazon EC2 Smart Business Development Cloud DB2
Cloud

cluster Data rebalancing


DB2

1.3 (Information Models) (Data Models)


(Information

Models)

(entity) (properties) (relationship)

(Real-world problem)

(Unified Modeling Language - UML) (Entity Relationship


Models : E-R model) XML schemas

24

(Conceptual level)


1.1
Information Model

Data Model

Data Model

Data Model

Conceptual/Apstract Model
for designer and operator
Concrete/detailed model
for implementor

1.1

1.4
9

1970 - Network (CODASYL)


1960s 1970 - Hierarchical (IMS)
1970 1980 - Relational
1970 - Entity-Relationship
1980 - Extended Relational
1970 1980 - Semantic
1980 1990 - Object-oriented
1980 1990 - Object-relational
1990 - Semi-structured (XML)

1 - 25

1.4.1 (Network model)


1969 CODASYL (Committee on Data Systems Languages)

1971 1973
(record-at-a-time) 1.2
Next

Parent

Prior

Direct

Child

Parent

Prior

Next

Child

Prior

Next

Direct

Direct

Next

Next

Child

Prior

...

Child

1.2 -

CODASYL CODASYL
(child) (parent)

1.4.2 (Hierarchical Model)

(root)


1.3
President

VP
Marketing

Social Media
Manager

VP
Finance

Direct Maketing
Manager

VP
Sales

Americas Sales
Manager

Asia Sales
Manager

1.3 -

IMS (Information Management System)

.. 1968

26

IMS

1.4.3 (Relational model)

IMS

Codd IMS
Codd 3

()
(set-at-a-time) (data manipulation language)

(Physical Data) IMS CODASY


1.4 (Entity-Relationship diagram) ()

STUDENT_MASTER

TIMETABLE

ENROLLMENT_NO
ATTENDENCE_RECORD
ENROLLMENT_NO [FK]
RESOURCE_ID [FK]

RESOURCE_ID

START_TIME [FK]
END_TIME
RESOURCE_ID
FACILITATOR_ID

TIMESTAMP
RESOURCES

SUBJECT_ID [FK]

FACILITATOR_MASTER
SUBJECT_ID
FACILITATOR_ID
FACILITATOR_NAME
TIMESTAMP

1.4

1 - 27

1.4.4
1970 Peter Chen

CODASYL Peter Chen

(1 to 1) (1 to
many) (many to many)
1.5

name
rec_num PK
lname
fname
bdate
anniv
email
child1
child2
child3

address
id_num PK
rec_num FK
street
city
state
zipcode
PK = Primary Key
FK = Foreign Key

Voice

vce_num PK
rec_num FK
vce-type

fax

fax_num PK
rec_num FK
oper_from
oper_till

modem
mdm_num PK
rec_num FK
b9600
b14400
b2800

1.5
1.5 name, address, voice, fax,

modem voice
vce_num rec_num vce-type PK FK

Chen

third normal form third normal form (normalization theory)

: IBM

InfoSphere Data Architect eBook Getting

started with InfoSphere Data Architect DB2 Campus book


series

28

1.4.5 (Object-relational model)


1.4.6

(semi-

structured) (Semantic) (object oriented


data models) XML

XML Web 2.0 (Service-Oriented Architecture: SOA)

object-relational mapping (ORM)


object-oriented

1.5

1.5.1 (Data Architect)



()

1 - 29



1.5.2 (Database Architect)

(Service Level Agreements: SLAs)


(High Availability) /


(Multi-tier Component Architecture)


(detailed designs)
(implementation details)

1.5.3 (Database Administrator: DBA)


(DBA)

30







(Procedures)
(data dictionary)

1.5.4 (Application Developer)

(Integrated database application Development Environments: IDEs)


SQL (Structure Query Language)

1 - 31

IDE IBM Data Studio

DB2 (stored procedures)

(Debug)

SQL XQuery WebSphere


DB2 Microsoft Visual Studio

DB2 ( ) .NET

1.6

1.7
1. DB2 Express-C
DB2 ibm.com/db2/express

2. IDEs IBM Data Studio


ibm.com/db2/express

1.8
1.
2.
3.
4.
5. DBA
6.
A. pureXML
B.
C.
D.
E.

32

7. Optimization
A. (High availability)
B. (Security)
C. (Performance)
D. (Scalability)
E.

8.
A. (Distribution)
B. (Data Independence)
C. (Integration)
D. (Federation)
E.

9. pureXML
A.
B. (Extensibility)
C. (Optimization)
D.
E.

10. DB2 Cloud


A. Spatial Extender
B. Database Partitioning Feature
C. pureXML
D.
E.

1 - 33

(relation) (domains) (schema) (key)


(constraints) (algebra)

4 SQL

2.1
(Information Models)

(framework)

2 35

2.1

entity integrity

referential integrity se-

mantic constraints


union
intersection
difference
cartesian product
selection
projection
join
division

2.1

36

Information Models

The Hierarchical

The Relational Data Model


Concepts
Attributes
Tuples
Relations
Domains
Schemas
Keys

Constraints
Entity
integrity

Data Model

Relation
Algeba

The Network

Relation
Calculas

The ObjectRelational
Data Model

Data Model

Referencial
integrity
Semantics
constraints

2.1

2.2

(candidate key) (primary key) (foreign
key)

2.2.1 (Attributes)

2.2 Type, Producer, Model, FabricationYear, Color,


Fuel

2 37

CARS Relations
Header

Body

TYPE

Attribute

PRODUCER MODEL

FABRICATION COLOR FUEL


YEAR

LIMOUSINE BMV

740

2008BLACK GAS

VAN

TRANSPORTER

2007RED

VW

Tuple

DIESEL

LIMOUSINE MERCEDES 320

2008WHITE GAS

LIMOUSINE AUDI

ALLROAD

2009BLUE DIESEL

LIMOUSINE BMW

525

2007GREY DIESEL

Value
2.2 ()

2.2.2 (Domains)
(atomic value)

(value)
BMW Mercedes Audi VW Producer

atomic value Producer



dimension (

) Fuel 2 GAS DIESEL


(Value)

Color_Character

2.2.3 (Tuples)

2.2

38

(row)

2.2.4 (Relations)
[2.1]

D1, D2, , Dn (heading) (body)


A1, A2, , An
Ai Di (i=1, 2, , n)

(Ai:vi) (i=1, 2, , n) Ai (Ai:vi)


vi Di Ai

2.2 CARS 6

Type, Producer, Model, Fabrication, Year, Color, Fuel

(5 2.2
) 6

(relation degree) 2.2

6 1 unary 2
binary 3 ternary n nary

(relation cardinality)

2.2 5

(relation instance)
4


()
()
Atomic

2.2.5 (Schemas)

3 (Concep-

2 39

tual data modeling) 4 (Relational database design)


2.2.6 (Keys)

(DBMS)

2.2.6.1 (Candidate Keys)



1 ()
1 C. J. Data [2.2]

R A1, A2, , An K=(Ai, Aj, , Ak) R


2
(Uniqueness)
2 R Ai,Aj,Ak
(Minimality)
Ai,Aj,Ak K
K

()

CAR 2.2 K=(Type, Producer, Model, FabricationYear, Color, Fuel)

CAR SerialNumber ()
IdentificationNumber () 3

40

Candidate Keys

TYPE

PRODUCER MODEL

FABRICATION
YEAR

COLOR FUEL

SERIAL
NUMBER

IDENTIFI
CATION
NUMBER

LIMOUSINE BMV

740

2008BLACK GAS

WBADL9105
GW65796

SB24MEA

VAN

TRANSPORTER

2007RED

QASMD8209
NF37590

AB08DGF

2008WHITE GAS

XEFAR2096
WM19875

SB06GHX
SB52MAG
AB02AMR

VW

LIMOUSINE MERCEDES 320

DIESEL

LIMOUSINE AUDI

ALLROAD

2009BLUE

DIESEL

AKLMD8064
MW79580

LIMOUSINE BMW

525

2007GREY

DIESEL

QMXAS4390
WQ21998

2.3 CARS

(unique key)

(DDL) UNIQUE

(primary key) (alternate keys)


:

2.2.6.2 (Primary Key)


(DBMS) ()

(DDL) PRIMARY KEY


CAR 2.3 IdentificationNumber
(NOT NULL)

2.2


ID ID

(surrogate key)
(artificial key) (surrogate key)

2 41

( 1)
2.2.6.3 (Foreign keys)
R2

R1 R1 R2

2.4 OWNERS CARS

Primary key

TYPE

Foriegn key

PRODUCER MODEL

FABRICATION
YEAR

COLOR FUEL

SERIAL
NUMBER

IDENTIFI
CATION
NUMBER

LIMOUSINE BMV

740

2008BLACK GAS

WBADL9105
GW65796

SB24MEA

VAN

TRANSPORTER

2007RED

QASMD8209
NF37590

AB08DGF

VW

DIESEL

LIMOUSINE MERCEDES 320

2008WHITE GAS

XEFAR2096
WM19875

SB06GHX

LIMOUSINE AUDI

ALLROAD

2009BLUE

DIESEL

AKLMD8064
MW79580

SB52MAG

LIMOUSINE BMW

525

2007GREY

DIESEL

QMXAS4390
WQ21998

AB02AMR

2.4 OWNERS
IdentificationNumber OWNERS IdentificationNumber

CARS

(Foreign-to-primary-key)

(DDL) FOREIGN KEY

2.3
(integrity rules)
(constraint)
(schema level)

2.3.1 (Entity integrity constraints)


42

(null values) Null (property inapplicable)

(information unknown) Null

CAR

2.3.2 (Referential integrity)


R2 FK PK R1 FK

R2 PK R1 ( FK )

t2 R2 t1 R1 t1

OWNERS IdentificationNumber

CARS

1. (Null Value)

2.
3

CASCADE cascades
()

RESTRICT restricted (
)

NULLIFIES

2 43

()
IdentificationNumber OWNERS
3. (update)
CASCADE cascades
()

identification

number identification number OWNER

RESTRICT restricted

() identification number
CARS

NULLIFIES

()

IdentificationNumber IdentificationNumber
OWNERS

2.3.3 (Semantic integrity constraints)

OWNERS

(system catalog dictionary)


(domain constraint) (Null constraint)

(unique constraint) (check constraint)

2.3.3.1 (Domain constraint)

Street OWNERS CHAR(20)


Number NUMERIC

(namely format)

(range)

44

IdentificationNumber XX99XXX
X 9
FabricationYear 1950 2010
2.3.3.2 (Null value)

FirstName LastName

NOT NULL NOT

NULL WITH DEFAULT

WITH DEFAULT (integer decimal


float ) (date time timestamp) character
(Data Definition Language: DDL)
2.3.3.3 (Unique constraint)

CARS
SerialNumber
2

UNIQUE

SQL unknown
SQL

(IS NULL) (IS NOT NULL)

(Unknown)
SQL
A

A OR B

A AND B

A=B

True

True

True

True

True

True

False

True

False

False

True

True

True

Unknown

True

Unknown

Unknown

True

False

False

True

True

False

False

True

Unknown

False

False

False

False

False

False

Unknown

Unknown

False

False

Unknown

True

True

Unknown

Unknown

Unknown

False

Unknown

False

False

Unknown

Unknown

Unknown

Unknown

Unknown

2.3.3.4 (Check constraint)

2 45

(predicate)



20
CARS fabrication year (

) current year ()

CHECK

(trigger)

2.4

[2.3] 8 2 4

Codd

Union, Intersection, Difference, Cartesian product


Select , Project, Join, Divide

2.4.1 Union
Union 2 R1 UNION R2 t

R1 R2 union (union-compatible)

Union U
Union

2.5 Union R1 R2 R3
5

46

R1

R2

Name

Age

Sex

Name Age Sex

20

20

21

20

21

21

R3 = R1 U R2
Name

Age

Sex

20

21

21

20

21

2.5 UNION : R1 R2
2.4.2 Intersection
Intersection R1 INTERSECT R2

t R1 R2 intersect
intersect

2.6 INTERSECT R1 R2
R3 1

R1

R2

Name

Age

Sex

Name Age Sex

20

20

21

20

21

21

R3 = R1 R2
Name

Age

Sex

20

2.6 INTERSECT R1 R2

2.4.3 Difference
Difference R1 MINUS R2 R1

2 47

R2 difference
Difference
2.7 DIFFERENCE R1 R2
R3 2 R1 - R2 R2 - R1

R1

R2

Name

Age

Sex

20

20

21

20

21

21

R3 = R1 - R2

R3 = R2 - R1

Name Age Sex

Name

Age

Sex

21

21

Name

Age

Sex

20

21

2.7 DIFFERENCE R1 R2

2.4.4 Cartesian product


Cartesian product R1 R2 R1 TIMES R2 t

t r R1 s R2 r =
(r1, r2, , rm) s = (sm+1, sm+2, , sm+n) t = (r1, r2, , rm, sm+1, sm+2, , sm+n)

R1 R2 ( union )
Cartesian product

R1 n N1 R2 m N2
R3 n-m N1*N2* 2.8

48

R1

R2

Name

Age

Sex

Name Age Sex

20

20

21

21

R3 = R1 X R2
Name

Age

Sex

Name

Age

Sex

20

20

21

20

20

21

21

21

2.8 CARTESIAN PRODUCT 2

2.4.5 Selection
select (subset)

select
<select condition> (<relation>)
<select condition>

<attribute> <comparison operator> <constant value>/<attribute>[AND/OR/NOT] <attribute> <comparison operator> <constant value>/<attribute>]

<, >, <=, >=, =, <>

Selection
2.9 select R Age

= 20 R1 (Sex = M) AND (Age >19)


R2

2 49

R1= (Age=20)(R)

R
Name

Age

Sex

20

21

20

19

20

21

21

Name

Age

Sex

20

20

20

R2= (Sex=M AND Age>19))(R)


Name

Age

Sex

20

21

2.9 SELECT ( Select )

2.4.6 Projection
Project


project
<attribute list> (<relation>)

<attribute list>
<attribute list>

Projection
2.10 project R 2

projection Name Sex R1 2 projection


Age Sex R2

50

R1= (Name, Sex)(R)

R
Name

Age

Sex

Name

Sex

20

21

20

19

20

21

21

Age

Sex

20

21

R2= (Age, Sex)(R) 20


19

F
M

2.10 PROJECT ()

2.4.7 Join
Join (join condition or predi-

cate) 1
join join
join
R <join condition> S
<join condition>
<attribute from R> <comparison operator> < <attribute from S>
<, >, <=, >=, =, <>

R A1, A2, ,An S B1, B2,., Bm

Ai Bj join R
S join Ai Bj T t

r R s S join
join theta-join join

join

2 1

join natural join


join equijoin =
join R S

2 51

join outer join


outer join 3 left outer join R
right outer join S full outer join
R S

2.11 R1 R2 join LastName

R1 LastName R2 R3

R1

R2

First
Name

Last
Name

Last Sex
Name

Mary

Ann

John

John

Ann

Mary

Bill

R3=R1(Last Name=Last Name) R2


First
Name

Last
Name

Mary

John

Ann

2.11 JOIN
2.12 join natural join R1 R2
right outer join

Natural Join
First
Name

Last Sex
Name

Mary

John

First
Name

Last Last
Sex
Name Name

Ann

Mary

Mary

John

John

Ann

Ann

NULL

NULL

Bill

Right Outer Join

2.12 NATURAL JOIN RIGHT OUTER JOIN

52

2.4.8 Division
Division R1 (n + m)

R2 m n (n+i)

R1 i R2 division
R1 R2 R2
R1

2.13 Division R1 R2

R1

R1= R1 R2

Name

Sex

Name

Sex

R2

F
2.13 DIVISION

2.5

(Relational algebra)

union, intersect, difference, select, project, join

Join OWNERS CARS IdentificationNumber


Colour = RED
Project FirstName, LastName City

FirstName, LastName City OWNERS


IdentificationNumber (OWNERS CARS)

2 53

RED CARS

(mathematical logic)

Predicate Calculus ( First-Order Logic) Kuhns [2.4] Predicate Calculus

Codd

Predicate Calculus [2.3]

Codd [2.5] data sublanguage ALPHA


QUEL INGRES data sublanguage ALPHA Codd
reduction algorithm Codd
2

1. Tuple-oriented relational calculus


2. Domain-oriented relational calculus

2.5.1 (Tuple-oriented relational calculus)


(tuple variable)

T
T t R

tuple variable
RANGE OF T IS X1; X2; ; Xn
T tuple variable X1; X2; ; Xn tuple calculus expressions

R1, R2, , Rn R1, R2, , Rn

tuple variable T (union of rela-

tions) tuple calculus expressions R () tuple variable T

(Free

variable) (Bound variable) T.A


A T

the existential quantifier the universal quantifier

54

tuple calculus expression


T.A, U.B, , V.C WHERE f
T, U, , V tuple variables A, B, , C f
relational calculus formula T, U, , V (Free variable)

projection Cartesian product TUV ( T, U, , V

) f (true) WHERE f projection Cartesian


product

FirstName, LastName City (

OWNERS) ( CARS) IdentificationNumber



RANGE OF OWNERS IS
OWNERS.FirstName, OWNERS.LastName, OWNERS.City WHERE
CARS(CARS.IdentificationNumber=OWNERS.IdentificationNumber
AND CARS.Color=RED)

tuple calculus
QUEL INGRES tuple-oriented relational calculus

2.5.2 (Domain-oriented relational calculus)


Lacroix Pirotte [2.6]

(domain calculus) (tuple variables) (domain


variables)

the universal quantifier the existential quantifier

(membership conditions)

R (term, term, )
R term A:v A R v

(true) R

OWNERS (IdentificationNumber: SB24MEA, City: SIBIU) mem-

bership condition OWNERS

IdentificationNumber SB24MEA City SIBIU

2 55

R (A:AX, B:BX, )
R A AX (
) B BX ()

FirstName, LastName City (

OWNERS) ( CARS) IdentificationNumber

FirstNameX, LastNameX, CityX WHERE IdentificationNumberX


(OWNERS (IdentificationNumber:IdentificationNumberX,
FirstName:FirstNameX, LastName:LastNameX, City:CityX)

AND CARS(IdentificationNumber:IdentificationNumberX, Color:RED)

ILL Lacroix Pirotte [2.7]

Query-By-Example (QBE)

2.6

(alternate keys)

union intersection difference Cartesian

product

selection

projection

join

division

2.7

56

DEPARTMENTS
EMPLOYEES
DEPARTMENTS DeptNo DepName Manager Address Budget

EMPLOYEES ID EmpName Job Salary BirthDate DepNo


DEPARTMENTS
DepNo
Numeric(2,0)
DepName Character(20)
Manager
Numeric(3,0)
Address
Character(50)
Budget
Numeric(10,2)

EMPLOYEES
ID
EmpName
Job
Salary
BirthDate
DepNo

Numeric(3,0)
Character(30)
Character(10)
Numeric(7,2)
Date
Numeric(2,0)

DEPARTMENTS DepNo Manager


DepNo
Manager EMPLOYEE ID

ID
(NOT NULL)

DB2
CREATE TABLE Departments (

DepNo Numeric(2,0) NOT NULL PRIMARY KEY,

DepName Char(20) NOT NULL,

Manager Numeric(3,0) NOT NULL,

Address Char(50),

Budget Numeric(10,2) );
CREATE TABLE Employees (

ID Numeric(3,0) NOT NULL PRIMARY KEY,

EmpName Char(30) NOT NULL,

Job Char(10) NOT NULL,

Salary Numeric(7,2),

BirthDate Date NOT NULL,

2 57

DepNo Numeric(2,0));
DEPARTMENTS EMPLOYEES 1 1

DepNo EMPLOYEES
DepNo DEPARTMENTS

DB2 (referential integrity constraint)


ALTER TABLE Employees ADD FOREIGN KEY (DepNo)


REFERENCES Departments (DepNo)
ON DELETE RESTRICT
ON UPDATE RESTRICT
ENFORCED ENABLE QUERY OPTIMIZATION;

EMPLOYEES DEPARTMENTS 2.14

DEPARTMENTS Relation
DepNo DepName

Manager Address

Budget

Software

211

Bucharest

2,000,000.00

Accounting 422

Bucharest

500,000.00

Hardware

Bucharest

4,000,000.00

Salary

BirthDate

DepNo

111

EMPLOYEES Relation
ID

EmpName

Job

211

John Smith Engineer

Bucharest

04/05/1966

123

Ann Adams Accoutant

Bucharest

11/05/1975

311

Bill Johns

Bucharest

09/03/1980

Programmer

2.14 DEPARTMENT EMPLOYEE

2.8
1. supplier 4 Id - supplier
(unique,not null) Name - Supplier (not null) Addess - supplier Discount - supplier 0%-50% ( not null, values
between 0 % and 50 %)

2. 5 union difference, Cartesian prod-

uct, selection projection


intersection, join division 5

58

3. 1 supplier New York


5% (relational algebra operations)

4. 3 (tuple-oriented relational calculus)

5. 3 (domain-oriented relational calculus)

6.
A.
B. (atomic values)
C. (data characteristic)
D. (an ordered set of values that describe
data characteristics)

E.

6.
F.
G.
H. (atomic values)
I.
J.

7.
A. (domain)
B. (instance)
C. (value)
D. (degree)
E.

8.
A. (candidate)
B.

59

C.
D. (alternate key)
E.

9. (options)

A. Restrict
B. (Null)
C. Delete
D. Cascade
E.



(business rules)
(logical)

3.1
(Conceptual modeling)

(Logical modeling) (Physical modeling)


(Conceptual

design)

( 4)
( 5)

(User requirement)

3 61

IBMs Rational RequisitePro


IBMs InfoSphere Data Architect 3.1

Data modeling lifecycle

Example of IBM tools

Practice for Database Modeling


planning

RUP, Relational Model Composer

Requirement analysis

Rational RequisitePro, Rational


Requirement Composer

Conceptual model - entities and


relationships

InfoSphere Data Architect

Logical model - attributes and


identifiers

InfoSphere Data Architect

Physical model - keys, storage


requirements

InfoSphere Data Architect

Deployment - Data Definition


Language

InfoSphere Data Architect, DB2

Test and maintenance - reverse


engineering

InfoSphere Data Architect, DB2,


IBM Data Studio

3.1 -

(information)
data
data information

3.2

62

Data

Input

Information system
Process/transformation

Output

Information

Feedback

3.2

3.2 (data)

(information)

3.2 ?
(abstraction)

3.2.1

Connolly [3]

3.2.2
(metadata)

(data description)

(data relationships) (data semantics) (data constraints)


(database schema)

(External data model)

(Records-based Logical
Model)

(Conceptual data model)


(Object-based Logical Model)

3 63

(Internal data model)

(conceptual)

(Physical data model)

(Entity-Relationship model)


(Structural component)

(Manipulation component)
( )

(Data Integrity component)

3.2.3

(Entity-Relationship Diagram)

(Constraint)



M:N

(recursive relationships)

1 1

3.2.3.1 (Entity-Relationship Model)


1 E-R (E-R model)

Entity Relationship Diagram (ERD)

64

(Entity-Relationship model)

(Entity set)
(Attribute)
(Relationship set)
(Constraint)
(Domain)
(Extension)
(Intension)
3.2.3.2

Teacher, Student
Grade
Exam
3.3

Entities

Chess Set

Entity sets

Serving Folks

3.3 -

(TEACHER)
(STUDENT)
PERSON

TEACHER PROFES-

SOR, ASSOCIATE PROFESSOR, ASSISTANT PROFESSOR

3 65

:
(tuples)

PERSON : NAME
ADDRESS PERSON=(NAME, ADDRESS)

3.2.3.3

(value) (numbers) (charac-

ter) (string) (dates) (images) (sounds)

()

(simple atomic attribute)


Gender

(composite

attribute)

(Name) (last Name)


(first Name)

(single-valued attribute)
Title teacher

(multi-valued attribute)

(derived attribute)

(unstable attributes)

(stable attributes)
(mandatory attributes)

(Name)

66

:
InfoSphere Data Architecture required
Attributes properties

(EntityRelationship Diagram) 3.4

3.4 -

(optional attribute) -
(null value)

(unique identifier) -


(Student Id)

(Key)

(candidate key)

(primary key) (candidate key)


Stable - (null value)


Age

Minimal -

3 67

(alternate key)

- (surrogate key)

EMPLOYEE


InfoSphere Data Architecture

3.5.

3.5 -

Simple Key
Composite Key
(Foreign Key)

3.2.3.4

(verb)

(
-recursive relationship)

: R

68

E1, E2 Ek R R(E1,
E2,, EK) R E1, E2 Ek R
3.2.3.5 (Constraints)

TEACHER
MENT

DEPART-

Cardinalities

R E () F (
) R

(1:1) - E F


(1:M) - E F


(M:M) - E F

1:M

3 69

Participation Cardinalities

Participation cardinalities

Total or mandatory
compulsory

Partial or Optional
non-compulsory

3.6 cardinality optionality

Optionality = must or may ?


Cardinality = how many ?
relationship alwayshas two sides?
Examples
1. Each children may team from one or more TEACHERs
2. Each TEACHER may educate one or more STUDENTs
3. An EMPLOYEE may manage one or more EMPLOYEEs
4. An EMPLOYEE must be managed by one EMPLOYEE
3.6 - Cardinality optionality


(Parent)
(Child)

(parent-

child relationship)

(hierarchical structure)

parent-child PERSON

STUDENT TEACHER 3.7

70
PERSON
ID
FirstName
LastName

STUDENT

TEACHER
ID [FK]

ID [FK]
StartDate

Function

FinishDate

Salary

3.7- PERSON STUDENT TEACHER

(hierarchy)

Principle, Assistant principle Teacher 3.8

Principle
Assistant Principle
Teacher
3.8 -

(Unary relationship set) -

recursive relationship
set

Assistant teacher Teacher

Teacher

3.9

(roles)
(Teacher) (Assistant principal)

3 71
TEACHER

manager of

TID
TID1 [FK]
Function

managed by

3.9 unary

(physical data model) CHECK


: check eBook
Getting Started with InfoSphere Data Architect
eBook

3.10

STUDENT
is given

SID
SFirstName
SLastName

having

StartDate
FinishDate

3.10 -

GRADE
Course
SID
Grade
Class

72

3.2.3.6 (Domain)

: InfoSphere Data Architect

CHECK SQL

CHECK

3.2.3.7 (Extension)


3.2.3.8 (Intension)

(schema)

3.3 - 1 3

3.3.1 (Conceptual model)

1 -

()

3 73


books, authors, name, address, e-mail, loaner, client, borrowers, name, address, e-mail,
phone, loan date, return date, loan days, fine

dencies)

(depen-

name, address, e-mail authors


name, address, e-mail phone borrowers

BOOK, AUTHOR, BORROWER, CLIENT LOANER


No.

LIBRARY,

Entity set
1

LIBRARY

BOOKS

AUTHORS

BORROWERS

CLIENTS

LOANERS

2 -

borrowers, loaners clients


borrowers

library

weak strong

weak
strong


No.

Entity set

Type

BOOK

Strong

AUTHOR

Strong

BORROWER

Strong

74

3 -

AUTHOR?

PHONE

BORROWER entity set


Attribute name

Type

Domain

Optional

BORROWER_ID

Unique identifier

Text

No

NAME

Composite attribute

Text

No

EMAIL

Single valued attribute

Text

Yes

PHONE

Multi-valued attribute

Text

Yes

ADDRESS

Composite attribute

Text

Yes

BOOK_ID

Single valued attribute

Text

No

LOAN_DATE

Single valued attribute

Text

No

DUE_DATE

Derived attribute

Text

No

RETURN_DATE

Derived attribute

Text

No

AUTHOR entity set


Attribute name

Type

Domain

Optional

AUTHOR_ID

Unique identifier

Text

No

NAME

Composite attribute

Text

No

EMAIL

Single valued attribute

Text

Yes

PHONE

Multi-valued attribute

Text

Yes

ADDRESS

Composite attribute

Text

Yes

BOOK entity set


Attribute name

Type

Domain

Optional

BOOK_ID

Unique identifier

Text

No

TITLE

Single valued attribute

Text

No

EDITION

Single valued attribute

Numeric

Yes

YEAR

Single valued attribute

Numeric

Yes

PRICE

Single valued attribute

Numeric

Yes

ISBN

Single valued attribute

Text

Yes

3 75
PAGES

Single valued attribute

Numeric

Yes

AISLE

Single valued attribute

Text

Yes

DECRIPTION

Single attribute

Text

Yes

3.2.3.3 :

(Composite attribute)

NAME FIRST_NAME LAST_NAME

(Multi-value attribute)


(Multi-value) (Single value)

DUE_DATE LOAN_DATE

10
DUE_DATE LOAN_DATE + 10


BORROWER entity set
Attribute name

Type

Domain

Optional

BORROWER_ID

Unique identifier

Text

No

FIRST_NAME

Single valued attribute

Text

No

LAST_NAME

Single valued attribute

Text

No

EMAIL

Single valued attribute

Text

Yes

PHONE

Single valued attribute

Text

Yes

ADDRESS

Composite attribute

Text

Yes

BOOK_ID

Single valued attribute

Text

No

LOAN_DATE

Single valued attribute

Text

No

RETURN_DATE

Single valued attribute

Text

No

AUTHOR entity set


Attribute name

Type

Domain

Optional

AUTHOR_ID

Unique identifier

Text

No

FIRST_NAME

Single valued attribute

Text

No

LAST_NAME

Single valued attribute

Text

No

EMAIL

Single valued attribute

Text

Yes

PHONE

Single valued attribute

Text

Yes

ADDRESS

Composite attribute

Text

Yes

76

BOOK entity set


Attribute name

Type

Domain

Optional

BOOK_ID

Unique identifier

Text

No

TITLE

Single valued attribute

Text

No

EDITION

Single valued attribute

Numeric

Yes

YEAR

Single valued attribute

Numeric

Yes

PRICE

Single valued attribute

Numeric

Yes

ISBN

Single valued attribute

Text

Yes

PAGES

Single valued attribute

Numeric

Yes

AISLE

Single valued attribute

Text

Yes

DECRIPTION

Single valued attribute

Text

Yes

4 (identifier)

BOOK BOOK_ID ISBN

BOOK_ID ISBN

5 -

(BOOK) (PERSON)
(BOOK) / (PERSON)
ally)

(cardinality) (mandatory) (option

strong weak weak

strong weak strong


strong

InfoSphere Data Architect

identifying non-identifying

identifying child non-identifying

(scenarios) :
Relationship set
1
2
3

BORROWER ->
BOOK
AUTHOR - >
BOOK
AUTHOR - >
BOOK

Identifying

Left
verb

No

Right verb

Cardinality

Borrows

Be borrowed

No

Write

Is written

No

Borrows

Be
borrowed

Many-tomany
Many-tomany
Many-tomany

Optionality
May
May
May

3 77

(many to many)

(decompose)
(one to many)
1. BORROWER -> BOOK

COPY BORROWER BOOK


COPY entity set
Attribute name

Type

Domain

Optional

COPY_ID

Unique identifier

Text

No

STATUS

Single valued attribute

Text

No

2. AUTHOR -> BOOK


AUTHOR_LIST - AUTHOR
BOOK :
AUTHOR_LIST entity set
Attribute name

Type

Domain

Optional

ROLE

Single valued attribute

Text

No

:
Left
verb

Right verb

No

Has

AUTHOR - > AUTHOR_LIST

No

Appear

AUTHOR_LIST - > BOOK

No

Relationship set

Identifying

BORROWER - > COPY

No

BOOK - > COPY

Borrows

Is created

Cardinality

Optionality

One-to-many

May

Is created

One-to-many

May

Has

One-to-many

May

Be borrowed

Many-tomany

Has

May

3. AUTHOR -> BOOK


Relationship set

Identifying

Left verb

Right verb

Cardinality

Optionality

AUTHOR - >
BOOK

No

Borrows

Be borrowed

Many-to-many

May

AUTHORS BORROWERS

PERSONS
AUTHORS BORROWERS

PERSONS

78

( pedagogical
)

6 - (business rules)
:

0.1%

3.4

InfoSphere Data Architect

ebook InfoSphere Data Architect

3 79

ER
InfoSphere Data Architect

3.5
(university):
Faculty
Teacher
Function
Course
Student

InfoSphere Data Architect


eBook: InfoSphere Data Architect

3.6
1.
A.
B.
C.
D.
E.

2.
A.
B.
C.
D.
E.

3. M:M
A. (optional) Many
B. (mandatory) One

80

C. Many
D. Many
E. (Recursive) One

4.
A.
B. (Conceptual model)

C.
D.
E.

5.
A.
B.
C.
D.
E.

6.
A.
B.
C. (should be read in double sense)
D.
E.

7.
A.
B.
C.

81

D.
E.

8.
A. Constraint
B. Cardinality
C. Superset
D. Subset
E.

9. SQL
A. Relationship
B. Primary Key
C. Check
D. Constraint
E.

10.


A. Intension
B. Extension
C. Schema
D. Instance
E.

4.1

4.1

COLLEGE COLLEGE_LEVEL COLLEGE_LEVEL


1 George Smith Will Brown

4 83
STUDENT_ID

STUDENT

RANK

COLLEGE

COLLEGE_LEVEL

0001

Ria Sinha

Fergusson

0002

Vivek Kaul

15

PICT

0003

George Smith 9

IIT

0004

Will Brown

IIT

4.1 (Student schema)


: 4.1 STUDENT_ID
primary key student schema

4.1.1

Record

COLLEGE_LEVEL

STUDENT_ID

STUDENT

0005

Susan Fuller

RANK

COLLEGE

10

Fergusson

COLLEGE_LEVEL

4.2

COLLEGE_LEVEL

4.1.2

Record (Row)

COLLEGE COLLEGE COLLEGE_


LEVEL COLLEGE 4.3

COLLEGE IIT George Smith Will Brown

STUDENT_ID

STUDENT

RANK

COLLEGE

COLLEGE_LEVEL

0003

George Smith

IIT

0004

Will Brown

IIT

4.3

4.1.3 (Update Anomalies)


84

COLLEGE_LEVEL = 1 STUDENT_ID = 0003 Fergusson


COLLEGE_LEVEL 1 4
STUDENT_ID

STUDENT

RANK

COLLEGE

COLLEGE_LEVEL

0001

Ria Sinha

Fergusson

0003

George Smith

Fergusson

4.4

4.2. (Decompositions)
(Shcema)

student
schema 4.1
STUDENT_ID

STUDENT

RANK

COLLEGE

COLLEGE_LEVEL

0001

Ria Sinha

Fergusson

0002

Vivek Kaul

15

PICT

0003

George Smith 9

IIT

0004

Will Brown

IIT

(a) Student - College Relation


COLLEGE

COLLEGE_LEVEL

STUDENT_ID

STUDENT

RANK

COLLEGE

Fergusson

0001

Ria Sinha

Fergusson

PICT

0002

Vivek Kaul

15

PICT

IIT

0003

George Smith 9

IIT

IIT

0004

Will Brown

IIT

(b) College Relation

(c) Student Relation

4.1
4.1 student (a)
college student (b)
(c) COLLEGE_LEVEL (Record)
COLLEGE COLLEGE student
student relation COLLEGE

COLLEGE

COLLEGE_LEVEL

STUDENT_ID

STUDENT

RANK

4 85


college student

COLLEGE

COLLEGE_LEVEL

STUDENT_ID

STUDENT_ID

STUDENT

RANK

COLLEGE_LEVEL
(Schema)
Functional dependencies

4.3. Functional Dependencies


Functional Dependencies (FD)
Super key subset
functional dependency

: schema R subset A B functional


dependency AB A B r
R

FD generalizes Super Key

A B R

AB B A functionally
FD A B
FD R r R
r FD

r FD AB (A B A B
)

Functional Dependency A B, B A A B

AB

A1 B1 , A2 B2, A3 B3 An Bn,
A1 A2 A3. An B1 B2 B3 Bn

R (A, B, C, D) AD
A

a1

b1

c1

d1

a2

b2

c2

d1

a3

b3

c3

d1

a4

b3

c4

d2

4.5 Functional Dependency

86

FDs 4.5 AD D A DA

D A (a1, b1,
c1, d1) (a2, b2, c2, d1)

Student schema 4.7 FD, STUDENT_ID COLLEGE Student


schema STUDENT_ID FD, STUDENTCOLLEGE
COLLEGE
STUDENT_ID

STUDENT

RANK

COLLEGE

0001

Ria Sinha

Fergusson

0002

Vivek Kaul

15

PICT

0003

George Smith

IIT

0004

Will Brown

IIT

4.7 Functional Dependency


FDs
{ STUDENT_ID COLLEGE , STUDENT_ID STUDENT,
STUDENT_ID STUDENT COLLEGE
STUDENT_ID STUDENT RANK }
Trivial

Functional

Dependencies

FD trivial

functional

dependency

(First-name, last-name) first-name

functional dependency AB B subset A B

A ()

non-trivial

FDs

trivial FDs

4.4 Functional Dependencies


functional dependencies
FD Closure Set of functional dependencies
Closure Set of Functional Dependencies - functional dependencies
functional dependencies S Closure Set of Function Dependency, S+.

r FD, S clo-

sure set FD, S+.


cies.

closure set of functional dependen-

4 87

4.4.1 Armstrongs Axioms


Armstrongs Axioms Inference Rules

functional dependencies FDs

Inference Rules 3
1. Reflexivity B subset A AB ( trivial FD )
2. Augmentation AB C ACBC reflexivity
ACB

3. Transitivity AB BC AC
axioms 3

closure FD FD
1. Union: AB AC ABC
2. Decomposition: ABC AB AC

Armstrongs Axioms FDs closure set

FD, S+ FDs S+.

4.4.2 closure set of attributes


closure set functional dependencies FD

Super key

Closure set A R
A FDs

: closure (A), A+ R
A Super key R

R closure set A, closure (A) :

1. closure (A) = A
2. FD AB B closure (A), closure (A) U B
3. A, ( C A), AC ( trivial FD) CD
D A D closure (A)
4. 3 closure (A)

R (A, B, C, D, E) FDs AB, BDE DC

88

1 Closure (A) = A
2 AB, closure (A) = A U B AB
3
1st Iteration: BDE B closure (A), closure (A) = ABDE
2nd Iteration: ADC, D closure (A) C closure (A),
closure(A), A+ = ABDEC

closure (B), B+= BDEC


Closure (C), C+ = C
Closure (D), D+= DC
Closure (E), E+= E

4.4.3 (Entailment)
Functional Dependencies (FDs)

functional dependencies

functional dependencies closure set functional dependencies dependencies

Armstrongs Axioms Clo-

sure functional dependencies


closure set FDs Super key
functional dependency XY closure set functional dependency

4.5 (Normal Forms)


Normalization

Normal forms Normalization

step-wise normal form


normal form normal form

4.5.1 1 (First Normal Form (1NF))


First Normal Form


4 89

C. J. Dates [4.8], table 1NF 5





( row IDs , object IDs
timestamps )

Relatives of a family

Movie {Movie_Title, Year}

candidate key
Movie_Title

Year

Type

Notting Hill

1999 Romantic

Lagaan

2000 Drama

Director

Director_DOB

Yr releases
Actors
cnt

Roger M

05/06/1956

30

Hugh G
Rhys I

Ashutosh G 15/02/1968

50

Aamir K
Gracy S

4.8 Movie normal form

1NF

Actors
1NF Movie Table Cast Table 4.2

90

Movie_Title

Year

Type

Notting Hill

1999 Romantic

Lagaan

2000 Drama

Director

Director_DOB

Yr releases
cnt

Roger M

05/06/1956

30

Ashutosh G 15/02/1968

50

Movie Table
Movie_Title

Year

Actors

Notting Hill

1999 Hugh G

Notting Hill

1999 Rhys I

Lagaan

2000 Aamir K

Lagaan

2000 Gracy S

Cast Table
4.2 First Normal Form 1NF

4.2

1NF
Actors

4.5.2 2 (Second Normal Form (2NF))


Second Normal Form 1NF non-

key attribute candidate key candidate key


candidate key 2NF

movie 1NF 2NF

candidate key Yr_releases_cnt Year


Year Yr_releases_cnt candidate key {Movie_Title, Year}

2NF Movie relation, Yearly releases relation Cast relation 4.3.

4 91

Movie_Title

Year

Type

Notting Hill

1999 Romantic

Lagaan

2000 Drama

Director

Director_DOB

Roger M

05/06/1956

Ashutosh G 15/02/1968

(a) Movie Relation


Movie_Title

Year

Notting Hill

1999 Hugh G

2000 50

Notting Hill

1999 Rhys I

(b) Year Relrease Relation

Lagaan

2000 Aamir K

Lagaan

2000 Gracy S

Year

Yr releases cnt

1999 30

Actors

(c) Cast Relation


4.3 Second Normal Form
4.3 nonkey candidate key

2NF

4.5.3 3 (Third Normal Form (3NF))


Third Normal Form 2NF non-

key attribute candidate transitively key primary key

transitive relation Z non-key attribute Y Y primary key X


Transitivity XY YZ XZ
3NF non-key

2NF movie 3NF

transitive dependency non-prime attribute primary key 4.3, Director_DOB


Director Director Director_DOB

candidate key {Movie_Title, Year } {Movie_Title, Year } Direc-

tor Director Director_DOB transitive dependency

3NF Movie relation, Director Relation,

Yearly releases relation Cast relation 4.4.

92

Movie_Title

Year

Type

Notting Hill

1999 Romantic

Lagaan

2000 Drama

Director

Director_DOB

Roger M

05/06/1956

Ashutosh G 15/02/1968

(a) Movie Relation


Director

Director_DOB

Movie_Title

Year

Roger M

05/06/1956

Notting Hill

1999 Hugh G

Ashutosh G

15/02/1968

Notting Hill

1999 Rhys I

Lagaan

2000 Aamir K

Lagaan

2000 Gracy S

(b) Director Relation


Year

year_release_cnt

1999

30

2000

50

Actors

(d) Cast Relation

(c) Movie Relation

4.4 Third Normal Form


nonkey candidate key

decomposition
3NF

4.5.4 Boyce-Codd Normal Form (BCNF)


Boyce-Codd Normal Form (BCNF) 3NF
overlapping candidate keys BoyceCodd normal form 3NF non-trivial FD candidate key
X Y, X candidate key

Guest Lecture relation college 4.9

Candidate Keys: {Subject, Lecture_Day}, {Lecture_Day, Teacher}

4 93

Subject

Lecture_Day

Teacher

Graphics

Monday

Dr. Arindham Singh

Databases

Monday

Dr. Emily Jose

Java

Wednesday

Dr. Prasad

Graphics

Tuesday

Dr. Arindham Singh

Java

Thursday

Dr. George White

4.9 - Guest Lecture relation


4.9

1NF 2NF 3NF FD

TeacherSubject

Teacher BCNF BCNF


decompose Subject area experts Lecture timetable 4.5.
Subject

Teacher

Subject

Graphics

Dr.Arindham Singh

Graphics

Monday

Dr.Arindham Singh

Databases Dr. Emily Jose

Databases

Monday

Dr. Emily Jose

Java

Dr.Prasad

Java

Wednesday Dr.Prasad

Java

Dr.George White

Graphics

Tuesday

Dr.Arindham Singh

Java

Thursday

Dr.George White

(a) Subject area experts' relation

Teacher

(b) Lecture timetable


4.5 Boyce-Codd Normal Form

4.9

BCNF

nontrivial

FD

TeacherSubject Teacher 4.5 (a) Subject area experts relation

4.6 Decompositions
Decomposition
relational schema

4.6.1 Lossless and Lossy Decompositions


R X Y
lossless
Normalization

94

R
lossy

R functional dependency F R1 R2

lossless FDs decomposed relations R1 R2 : R1 R2R1 R1


R2R2

common attributes R1 R2 (R1 R2) super key R1 R2


R lossless decomposition R1 R2

lossless join

lossless decomposed relation X Y R


join X Y R

employee :
EMP_ID

EMP_NAME

WORK_EXP

DEPT_ID

DEPT_NAME

lossless decomposition :
DEPT_ID

DEPT_NAME EMP_NAME

EMP_ID

Department relation

EMP_NAME

WORK_EXP

Employee relation

(Department) (Employee) = DEPT_ID and DEPT_ID { DEPT_ID , DEPT_

NAME} DEPT_ID super key Department relation decomposition


lossles
lossy decomposition :
DEPT_ID

DEPT_NAME

Department relation

EMP_ID

EMP_NAME

WORK_EXP

DEPT_ID

Employee relation

(Department) (Employee) = EMP_NAME super key de-

partment employee table decomposition lossy

EMP_NAME

4.6.2 Dependency-Preserving
R relation X Y

Dependency FDs X Y FDs Dependency F+ R

FD relation R, F X FDs

C->D C D X Fx

relation R X Y

Dependency union FDs X Y Depen-

4 95

dency F+ R Fx U Fy F+ Fx FDs F+
X Fy FDs Y

constraints decomposed

Dependency

Dependency

4.7 Minimal Cover


Minimal Cover, Fc dependencies dependencies

Minimal Cover FDs F relation R F+=Fc+

Minimal Cover constraint

RDBMS constraint relation Minimal Cover FDs


relation constraint Minimal Cover
Minimal Cover Fc F :
1. RHS FD Minimal Cover
2. LHS FD,
3. FD Minimal Cover Minimal Cover
Minimal Cover FDs unique

F FDs

A Fc (Fc {}) U ({A})


B Fc (Fc {}) U ( { B} )
Minimal Cover Fc
1. Armstrongs FD RHS
2. LHS FD Fc
3. Armstrongs FDs Minimal Cover
F+ = Fc+

relation R: R (A, B, C, D) FDs F:

96

ABC,
BC,
AB,
ABC,
ACD
minimal cover Fc
:

1: FD RHS
(: XYZ XY XZ)
AB, AC,
BC,
AB,
ABC,
ACD
2: LHS BC ABC A

ABC BC FD AC ACD C
ACD AD
:
AB, AC,
BC,
AB,
BC,
AD
3: FDs
ABC B relation
AC,
:
AB,
BC,
AD
Minimal Cover Fc= {AB, BC, AD}

4 97

4.8 Synthesis of 3NF schemas


Synthesis of 3NF schemas lossless join dependency

preserving decompositions relation 3NF Synthesis

minimum set FDs schemas


decompositions 3NF

FDs schema decomposed schema


list 3NF

schemas minimal cover FDs relation

R schema lossless join decomposition schema


candidate key lossless join decomposition 3NF
Synthesis of 3NF schemas R R1,R2,R3.....,Rn :

1. FD Minimal Cover Fc schemas R1,R2,R3.....,Rn contains


, schema Ri = (, ).

2. Ri R1,R2,R3.....,Rn relation contains a candidate key R. relation


schemas Rn + 1 Rn + 1 candidate key R

4.9 3NF decomposition


3NF decomposition

normalization 3NF
Dependency
4.5.3

3NF

Dependency

Book (book_name, author, auth_dob, sales, rating) FDs:


(book_name author ) sales
author auth_dob
sales rating
and candidate key { book_name, author }

Book schema
3NF :

1: minimal cover FDs


2: FD relation

98

( book_name, author, sales )


( author, auth_dob )
( sales, rating )

3: (book_name, author, sales) contains candidate key


relations schemas
3NF :
( book_name, author, sales )
( author, auth_dob )
( sales, rating )

4.10 The Fourth Normal Form (4NF)


fourth normal form dependencies

4NF relational schema Multi-valued dependencies


relational

4.10.1 Multi-valued dependencies


A multi- determines B A B
Multi-valued Dependency (MVD) AB. A multi- determines B,
B multi-dependent A AB.

4 NF MVDs relation multi-valued

relation R(A,B,C) 4NF MVDs


AB AC B C relation

relation ice cream 4.10.


Vendor

I_Type

I_Flavour

Amul

Scoop

Vanilla

Amul

Softy

Vanilla

Amul

Scoop

Chocolate

Amul

Softy

Chocolate

Baskin Robbins

Scoop

Chocolate

Baskin Robbins

Sundae

Chocolate

Baskin Robbins

Scoop

Strawberry

4 99

Baskin Robbins

Sundae

Strawberry

Baskin Robbins

Scoop

Butterscotch

Baskin Robbins

Sundae

Butterscotch

4.10 ice cream relation in BCNF


BCNF candidate key
The following MVDs exist
Vendor I_Type

Vendor I_Flavour
update anomalies

relation 4NF 4.6


Vendor

I_Type

Vendor

I_Flavour

Amul

Scoop

Amul

Vanilla

Amul

Softy

Amul

Chocolate

Baskin Robbins

Scoop

Baskin Robbins

Chocolate

Baskin Robbins

Sundae

Baskin Robbins

Strawberry

Baskin Robbins

Butterscotch

Ice cream type relation


4.6 - 4NF

Ice cream flavour relation

4.6 4NF MVD

4.11
fifth normal form [4.10], domain key normal form

(DKNF) [4.11] sixth normal form [4.12, 4.13].


4.12 Library Management System - Part 2 of 3


logical model based conceptual

model logical model conceptual model normalization

normal forms conceptual model

100

conceptual model the logical model:


Conceptual modeling
concept

Logical modeling
concept

Name of entity set

Relation variable, R

Entity set

Relation

Entity

Tuple

Attribute
Relationship set
Unique identifier

Attribute, A1, A2,


etc.
A pair of primary
key foreign key
Primary key

conceptual model logical model schema


( primary key):
BORROWER = {BORROWER_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE, ADDRESS, BOOK_
ID, LOAN_DATE, RETURN_DATE}
AUTHOR = {AUTHOR_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE, ADDRESS)
BOOK = {BOOK_ID, TITLE, EDITION, YEAR, PRICE, ISBN, PAGES, AISLE, DECRIPTION}
COPY = {COPY_ID, STATUS}
AUTHOR_LIST = {ROLE}
data integrity data

loss foreign keys foreign key):

BORROWER = {BORROWER_ID, COPY_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE,


ADDRESS, BOOK_ID, LOAN_DATE, RETURN_DATE}
AUTHOR = {AUTHOR_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE, ADDRESS)
BOOK = {BOOK_ID, TITLE, EDITION, YEAR, PRICE, ISBN, PAGES, AISLE, DECRIPTION}
COPY = {COPY_ID, BORROWER_ID, BOOK_ID, STATUS}
AUTHOR_LIST = {AUTHOR_ID, BOOK_ID, ROLE}
borrower

BORROWER primary key a composite key : {BORROWER_ID,


COPY_ID, LOAN_DATE }

relation normal forms

4 101

relation first normal forms

ADDRESS BORROWER AUTHORS


{ADDRESS, CITY, COUNTRY}

BORROWER borrower
BORROWER BORROWER LOAN relations :

BORROWER = {BORROWER_ID, FIRST_NAME, LAST_NAME, EMAIL, PHONE, ADDRESS}


LOAN = {BORROWER_ID, COPY_ID, LOAN_DATE, RETURN_DATE}
first normal form
2nd normal form 2nd normal form

primary key
2nd normal form

composite key {LOAN_DATE, RETURN_DATE} BORROWER_ID


COPY_ID AUTHOR_ID BOOK_ID 2nd normal form
3rd normal form 3rd normal form


3rd normal form

: Loan entity
foreign keys entity
InfoSphere Data Architect (IDA)
IDA final logical model:

102

AUTHOR
AUTHOR_ID
LASTNAME
FIRSTNAME
EMAIL
CITY
COUNTRY

BOOK
BOOK_ID

BORROWER
BROROWER_ID

TITLE

LASTNAME

EDITION

FIRSTNAME

YEAR

EMAIL

PRICE

PHONE

ISBN

ADDRESS

PAGES

CITY

AISLE

COUNTRY

DESCRIPTION

AUTHOR_LIST
AUTHOR_ID [FK]
BOOK_ID [FK]
ROLE

LOAN
COPY

COPY_ID [FK]

COPY_ID

BORROWER_ID [FK]

BOOK_ID [FK]

LOAN_DTAE

STATUS

RETURN_DATE

4.7
final logical model final logical model

1 conceptual model
specifying primary keys proceed normalize model
final logical model

3 5 3 logical
model physical model

4.13
model real-world objects

relational database
relate tables

relational database
relational schema

4 103

normal forms relational tables normalization

relational database normal form normal form

normal form higher normal


forms

Functional table guide

function dependencies: Armstrongs Axioms Closure set

functional dependencies
relations
- lossless dependency

relational database

4.14
1.

Closure

R(A,B,C,D,E) FDs {ABC, ADE, BD, AB, EC}


super key

2.
Order ( product_id, customer_id , price, quantity, order_type )
( product_id, customer_id ) order_type

luxury price > 1000$ regular price <1000$


3 (3NF)

3. minimal cover relation R (A, B, C, D) FDs


ABC, BC, ACD

4. Library Book ( Book_id, bookname, author, subject )


3NF

5. Closure Functional Dependencies F+ R(A,B,C,D,E)


FDs {ABC, ADE, BD, AB, EC}

4.15

1. lossless-join wedding organizer:

Order (customer_id, bride, groom, budget)


Wedding Category (budget, wedding_type)

104

2. Cell phone :
mobile

brand

head_office

N93

Nokia

New Delhi

Diamond

HTC

Hyderabad

N97

Nokia

New Delhi

MotoSlim

Motorola

Mumbai

3315

Nokia

New Delhi

ZN50

Motorola

Mumbai

Cell phone relation


update statement update anomaly

A. UPDATE cellphone set mobile = 6600 where mobile = N97


B. UPDATE cellphone set brand = Samsung where mobile = ZN50
C. UPDATE cellphone set head_office = Bangalore where mobile = N97
D. UPDATE cellphone set brand = Samsung , mobile = X210 where mobile = MotoSlim

E.

3. normal form library - book relation :


Library Book ( Book_id, bookname, author, subject )
A. First Normal Form

B. Second Normal Form


C. Third Normal Form
D. Boyce - Codd Normal Form
E. Fourth Normal Form

4. Functional
A. Closure set of functional dependencies, F+
B. Decomposition is lossless
C. X Y belongs to F+
D. Super key
E.

5 - SQL 105

5. BCNF (MVDs) Multi-valued


4NF

A. MVDs
B. MVDs
C. Candidate key MVDs
D. Candidate keys
E.

6.
A. Lossless
B. Functional integrity constraints
C. Dependency preserving implies lossless join and vice-versa
D. BCNF
E.

5 - SQL

Structured Query Language (SQL) --

SQL

SQL SQL

SQL 3 :

DDL (Data Definition Language)


DML (Data Manipulation Language)


DCL (Data Control Language)

SQL

SQL (Create)
(Read) (Update) (Delete) CRUD

5.1 SQL
1970s Don Chamberlin Ray Boyce SQL

System R
Codd

Structured English Query Language SEQUEL

5 - SQL 107

SQL SEQUEL
(United Kingdom)

SQL

1986 American National Standards Institute (ANSI)

International Standards Organization (ISO) 1987 SQL 6


.. 2008
SQL:2008

SQL

5.2 SQL

( Physical Data Model ) SQL


ANSI ISO SQL

DB2 Express-C IBM DB2


Server

SQL

5.2.1 (Data Types)

(data type) (data type)


(data type)
(integer) (float) (char) (date) (time) (blob)

(data type)

User-Defined Data Type UDT

UDT
address, country, phone number, social security number, postal zip code
5.2.1.1 (Date and Time)
(date and time)

DB2

Date (YYYY-MM-DD)

108

Time (HH:MM:SS)
Timestamp (YYYY-MM-DD-HH:MM:SS:ssssss)
ssssss (microseconds)

Year
Month
Day
Dayname
Hour
Minute
Second
Microsecond
5.2.2 (Create Table)
(Table) (Rows)

(Column)

(Entities)

SQL

create table myTable (col1 integer)

myTable col1


NULL NULL
5.2.2.1 (Default Values)

Users ( Default)
Student

CREATE TABLE USERS


(NAME
CHAR(20),
AGE
INTEGER,

PROFESSION VARCHAR(30) with default Student)

(DEPTNO)

5 - SQL 109

CREATE TABLE DEPT


(DEPTNO
SMALLINT
NOT NULL
GENERATED ALWAYS AS IDENTITY
(START WITH 500, INCREMENT BY 1),
DEPTNAME VARCHAR(36) NOT NULL,
MGRNO
CHAR(6),
ADMRDEPT SMALLINT
NOT NULL,
LOCATION CHAR(30))

SQL DEPT DEPTNO GENERATED ALWAYS AS IDENTITY 500 1


DEPTNO
5.2.2.2 (NULL Values)
NULL Values Unknown

NULL

(country) NOT NULL


country

create table myTable (name varchar(30), country varchar(20) NOT NULL)


5.2.2.3 (Constraints)
(Constraints)

A UNIQUE UNIQUE

(unique indexes) UNIQUE


NULL UNIQUE

A PRIMARY KEY

UNIQUE
(unique indexes)

A REFERENTIAL referential

integrity

A CHECK

110

CHECK

CHECK PRIMARY KEY

CREATE TABLE EMPLOYEE


(ID
INTEGER
NOT NULL PRIMARY KEY,
NAME
VARCHAR(9),
DEPT
SMALLINT CHECK (DEPT BETWEEN 10 AND 100),
JOB
CHAR(5)
CHECK (JOB IN (Sales,Mgr,Clerk)),
HIREDATE
DATE,
SALARY
DECIMAL(7,2),
CONSTRAINT YEARSAL CHECK ( YEAR(HIREDATE) > 1986
OR SALARY > 40500 )
)

4 (constrains)

PRIMARY KEY ID

nulls

CHECK DEPT BETWEEN 10 AND 100 DEPT

10 100

CHECK JOB IN (Sales,Mgr,Clerk) JOB

Sales, Mgr Clerk

CHECK YEAR(HIREDATE) > 1986 OR SALARY > 40500

HIREDATE 1986
SALARY 40500

5.2.2.4 (Referential Integrity)


2 refer-

ential integrity
(Primary Key) (Foreign Key)

referential
integrity

(de-

pendant) (child table)

(base) (parent table) (primary key)


(unique)
(referential integrity)

5 - SQL 111

(Syntax 1-3)
Syntax 1:
CREATE TABLE DEPENDANT_TABLE
(ID
INTEGER REFERENCES BASE_TABLE(UNIQUE_OR_PRIMARY_KEY),
NAME
VARCHAR(9),
:
:
:
);
Syntax 2:
CREATE TABLE DEPENDANT_TABLE
(ID
INTEGER,
NAME
VARCHAR(9),
:
:
:,
CONSTRAINT constraint_name FOREIGN KEY (ID)
REFERENCES BASE_TABLE(UNIQUE_OR_PRIMARY_KEY)
);
Syntax 3:
CREATE TABLE DEPENDANT_TABLE
(ID
INTEGER,
NAME
VARCHAR(9),
:
:
:
);
ALTER TABLE DEPENDANT_TABLE
ADD CONSTRAINT constraint_name FOREIGN KEY (ID)

REFERENCES BASE_TABLE(UNIQUE_OR_PRIMARY_KEY);
SQL (constraint name) DB2

15 CC1288717696656

2 (delete)

(update)

CASCADE
CASECADE

112

SET NULL
SET NULL
NULL

NO ACTION

NO

ACTION

RESTRICT
RESTRICT

ALTER TABLE DEPENDANT_TABLE


ADD CONSTRAINT constraint_name
FOREIGN KEY column_name
ON DELETE <delete_action_type>
ON UPDATE <update_action_type>
;
CASCADE, SET NULL, NO ACTION RE-

STRICT NO ACTION RESTRICT

5.2.3 (Schema)

DB2
(schema) (database objects)
DB2 2 1) 2)

create schema mySchema



create table mySchema.myTable (col1 integer)
DB2 (user ID)

DB2 (implicit schema)

john john
SCHEMA
set current schema = myschema

5 - SQL 113

5.2.4 (View)
(View)

Select
MYVIEW
CREATE VIEW MYVIEW AS

SELECT LASTNAME, HIREDATE FROM EMPLOYEE

MYVIEW

MYVIEW select
SELECT * FROM MYVIEW

5.2.5

(CREATE

TABLE)

(Database Objects)

(index) (function) (procedure) (trigger)


DB2 9.7 Information Center

5.2.6

SQL ALTER
NULLs
SQL

alter table myTable alter column col1 set not null

ALTER ALTER

5.2.7
RENAME SQL

RENAME <object type> <object name> to <new name>

114

(table)

(table space) (index)


Drop

ALTER RENAME

ALTER TABLE <table name> RENAME COLUMN <column name> TO <new name>

5.3 SQL

Data Manipulation Language DML


SQL

5.3.1 (Select)
SQL (retrieve)

select
myTable
select * from myTable
* myTable

select col1, col2 from myTable


col1 col2 myTable

5.3.1.1 (Order)
select

select

ORDER BY SQL col1

SELECT col1 FROM myTable ORDER BY col1 ASC


ASC (ascending)

DESC (decending)

SELECT col1 FROM myTable ORDER BY col1 DESC

5 - SQL 115

5.3.1.2 (Cursor)
(Cursor) select

DECLARE <cursor name> CURSOR [WITH RETURN <return target>]



<SELECT statement>;
OPEN <cursor name>;
FETCH <cursor name> INTO <variables>;
CLOSE <cursor name>;

select

FETCH
(loop)
(logic)

...
DECLARE p_sum INTEGER;
DECLARE p_sal INTEGER;
DECLARE c CURSOR FOR
SELECT SALARY FROM EMPLOYEE;
DECLARE SQLSTATE CHAR(5) DEFAULT 00000;
SET p_sum = 0;
OPEN c;
FETCH FROM c INTO p_sal;
WHILE(SQLSTATE = 00000) DO
SET p_sum = p_sum + p_sal;
FETCH FROM c INTO p_sal;
END WHILE;
CLOSE c;
...

FETCH

5.3.2 (Insert)
INSERT SQL

INSERT SELECT

myTable
insert into myTable values (1);

116

insert into myTable values (1, myName, 2010-01-01);


( 3 ) myTable.
insert into myTable values (1),(2),(3);
insert into myTable values (1, myName1,2010-01-01),
(2, myName2,2010-02-01),
(3, myName3,2010-03-01);
myTable2
sub-query select * from myTable2 myTable
insert into myTable (select * from myTable2)

5.3.3 (Delete)

delete

where delete delete col1


1000

DELETE FROM myTable WHERE col1 > 1000


delete where

where

5.3.4 (Update)

UPDATE


where UPDATE

UPDATE myTable SET col1 = -1 WHERE col2 < 0 ;


UPDATE myTable SET col1 = -1, col2 = a, col3 = 2010-01-01
WHERE col4 = 0;
update

where where

5 - SQL 117

5.4 (Table Joins)


Select SQL

select

2 SQL

1. (Inner Join)
2. (Outer Join)

5.4.1 Inner Join


(Inner Join)

SQL 3

Equi-join
Natural join
Cross join
5.4.1.1 Equi-join
Equi-join

SELECT *
FROM student, enrollment
WHERE student.enrollment_no=enrollment.enrollment_no
OR
SELECT *
FROM student
INNER JOIN enrollment
ON student.enrollment_no=enrollment.enrollment_no
student enrollment enrollment_no
5.4.1.2 Natural Join
Natural equi-join

DB2

118

Natural

Natural

SELECT *
FROM STUDENT
NATURAL JOIN ENROLLMENT

Natural

Natural Join
5.4.1.3 Cross Join

Cross

(Cartesian Product)
SELECT *

FROM STUDENT, ENROLLMENT

5.4.2 Outer Joins


Outer Join SQL

FROM SQL
(LEFT table) (RIGHT table)
Outer Join 3

Left outer join -


Right outer join
Full outer join

5.1 Outer join 3

5 - SQL 119

Left outer join

11111111

11221122

11331133

Right outer join

11111111

11221122

11331133

Full outer join

11111111

11221122

11331133

5.1 Outer join


Outer

Student Enrollment 5.2

Student Table
Name

Year

Enrollment no

John Smith

11221122

Raul Chong

11331133

Enrollment table Table


Name

SubjectID

Enrollment no

Physics

100

11221122

Mathemethics

200

11111111

5.2 Outer Join

120

5.4.2.1 Left outer joins


(Union) equi-join


5.3.

SELECT *
FROM STUDENT
LEFT OUTER JOIN ENROLLMENT
ON STUDENT.ENROLLMENT_NO = ENROLLMENT_NO

Left outer join


Name

Year

Enrollment no

Name

SubjectID

John Smith

11221122

Physics

100

Raul Chong

11331133

5.3 Left outer join


5.4.2.2 Right outer join
(Union) equi-join


5.4.

SELECT *
FROM STUDENT
RIGHT OUTER JOIN ENROLLMENT
ON STUDENT.ENROLLMENT_NO = ENROLLMENT_NO
Right outer join
Name

Year

Enrollment no

Name

SubjectID

John Smith

11221122

Physics

100

11111111

Mathematics

200

5.4 Right outer join


5.4.2.3 Full outer join
(Union) equi-join


5.5.
SELECT *
FROM STUDENT
FULL OUTER JOIN ENROLLMENT

ON STUDENT.ENROLLMENT_NO = ENROLLMENT_NO

5 - SQL 121

Full outer join


Name

Year

Enrollment no

Name

SubjectID

John Smith

11221122

Physics

100

Raul Chong

11331133

11111111

Mathematics

200

5.5 Full outer join

Outer Join

(Business Requirement)


Left Outer Join

5.5 Union, Intersection, Difference


ence

SQL SET OPERATORS Union, Intersection, Differ-

5.5.1 Union

Union

Union
5.6
SELECT * FROM student_table_a
UNION

SELECT * FROM student_table_b


Student Table A
Name

Year

Enrollment no

John Smith

11221122

Raul Chong

11331133

Student Table B
Name

Year

Enrollment no

John Smith

11221122

Alan Doster

44556677

A Union B
Name

Year

Enrollment no

John Smith

11221122

Raul Chong

11331133

Alan Doster

44556677

5.6 - Union
5.6 Union

UNION ALL UNION

122

SELECT * FROM student_table_a


UNION ALL

SELECT * FROM student_table_b


5.7 Union all
A Union All B
Name

Year

Enrollment no

John Smith

11221122

Raul Chong

11331133

John Smith

11221122

Alan Doster

44556677

5.7 Union all

5.5.2 Intersection
intersaction

select * from student_table_a


INTERSECT
select * from student_table_b
5.8
A Intersect B
Name

Year

Enrollment no

John Smith

11221122

5.8 INTERSECT
intersect

A B

A B INTERSECT ALL

select * from student_table_a


INTERSECT ALL
select * from student_table_b

5.5.3 Difference (Except)


Difference (EXCEPT)

A EXCEPT B = A MINUS [A INTERSECT B]

5 - SQL 123

select * from student_table_a


EXCEPT

select * from student_table_b


5.9.
A Except B
Name

Alan Doster

Year
2

Enrollment no
44556677

5.9 EXCEPT
EXCEPT A B

A
EXCEPT ALL
select * from student_table_a
EXCEPT ALL
select * from student_table_b

5.6 (Relational Operators)


(Relational Operators)

+, -, * /
AND, OR NOT
CONCATENATE, LENGTH

SUBSTRING

=, <, >, > =, < = ! =


(grouping) (aggregate)
DISTINCT

5.6.1 (Grouping Operators)


124

select count(*) from students_enrollment



Group by

select course_enrolled, count(*)
from students_enrollment
group by course_enrolled
------------------------------COURSE_ENROLLED
STUDENT_COUNT
----------------------------------- ----------------------English

10
Mathematics

30
Physics

60

5.6.2 Aggregation

Aggregation

Aggregation

(Scalar result set)


COUNT, SUM, AVERAGE, MINIMUM, MAXIMUM
GROUP BY SQL

5.6.3 HAVING
HAVING GROUP BY

HAVING

5
SELECT course_enrolled, count(*)
FROM students_enrollment
GROUP BY course_enrolled
HAVING count(*) < 5

WHERE WHERE

5 - SQL 125

5.7 (Sub-queries)
SQL

Select (Query) (Main Query Parent Query)

(Sub-query)

Inner Query

NULL

5.7.1
(Scalar)



SELECT name FROM students_enrollment
WHERE age = ( SELECT min(age) FROM students )

(min)

5.7.2


(Vector)

SELECT name FROM students


WHERE course_enrolled IN
(
SELECT distinct course_name
FROM courses
WHERE department_name = Computer Science
)

SQL
SQL

126

5.7.3 Correlated Sub-query


correlated

sub-query

SELECT dept, name, marks


FROM final_result a WHERE marks = (SELECT max(marks) FROM final_result WHERE
dept = a.dept)


final_result

max(marks)

5.7.4 FROM Select

FROM

FROM
Select

SELECT dept, max_marks, min_marks, avg_marks


FROM
(
SELECT dept,
max(marks) as max_marks,
min(marks) as min_marks,
avg(marks) as avg_marks
FROM final_result GROUP BY dept
)
WHERE (max_marks min_marks) > 50 and avg_marks < 50
from


WHERE

5.8 (Object-oriented concept)


(Relational concept)

(Object-oriented programming languages)

5 - SQL 127

Object-oriented concept - Class elements

Relational database concept

Name

Table name

Attribute

Column name

Method

Stored procedure

Constructor/Destructor

Triggers

Object identifier

Primary Key

5.1
(Object-relational mapping - ORM)

(object-oriented) (relational)
pureQuery

Java pureQuery eBook


Getting started with pureQuery

5.9 3

DB2

(conceptual) (logical) (physical)


Conceptual modeling
concept

Logical modeling concept

Physical modeling
concept

Name of entity set

Relation variable, R

Table name

Entity set

Relation

Table

Entity

Tuple

Row

Attribute

Attribute, A1, A2, etc.

Relationship set

A pair of primary key foreign


Constraint
key

Unique identifier

Primary key

Column

Primary key

128

(sub domain)
(constraint)

PRIMARY KEY: pk_


UNIQUE: uq_
DEFAULT: df_
CHECK: ck_
FOREIGN KEY: fk_
(sub domain) (constraint)

BORROWER
Attribute name

Domain

Sub-domain

Optional

Constraints

BORROWER_ID

Text

CHAR(5)

No

Pk_

FIRST_NAME

Text

VARCHAR(30)

No

LAST_NAME

Text

VARCHAR(30)

No

EMAIL

Text

VARCHAR(40)

Yes

PHONE

Text

VARCHAR(15)

Yes

ADDRESS

Text

VARCHAR(75)

Yes

CITY

Text

CHAR(3)

No

COUNTRY

Text

DATE

No

AUTHOR
Attribute name Domain

Sub-domain

Optional

Constraints

AUTHOR_ID

CHAR(5)

No

Pk_

Text

FIRST_NAME

Text

VARCHAR(30)

No

LAST_NAME

Text

VARCHAR(30)

No

EMAIL

Text

VARCHAR(40)

Yes

5 - SQL 129

PHONE

Text

VARCHAR(15)

Yes

ADDRESS

Text

VARCHAR(75)

Yes

CITY

Text

VARCHAR(40)

Yes

COUNTRY

Text

VARCHAR(40)

Yes

Attribute name Domain

Sub-domain

Optional

Constraints

BOOK_ID

Text

CHAR(5)

No

Pk_

TITLE

Text

VARCHAR(40)

No

EDITION

Numeric

INTEGER

Yes

YEAR

Numeric

INTEGER

Yes

PRICE

Numeric

DECIMAL(7,2)

Yes

ISBN

Text

VARCHAR(20)

Yes

PAGES

Numeric

INTEGER

Yes

AISLE

Text

VARCHAR(10)

Yes

DECRIPTION

Text

VARCHAR(100) Yes

BOOK

LOAN
Attribute name

Domain

Sub-domain

Optional Constraints

BORROWER_ID

Text

CHAR(5)

No

Pk_, fk_

COPY_ID

Text

VARCHAR(30)

No

Pk_, fk_

LOAN_DATE

Text

DATE

No

< RETURN_DATE

RETURN_DATE

Text

DATE

No

130

COPY
Attribute name Domain

Sub-domain

Optional

Constraints

COPY_ID

Text

CHAR(5)

No

Pk_

BOOK_ID

Text

VARCHAR(30)

No

Fk_

STATUS

Text

VARCHAR(30)

No

Attribute name Domain

Sub-domain

Optional

Constraints

AUTHOR_ID

Text

CHAR(5)

No

Pk_, fk_

BOOK_ID

Text

VARCHAR(30)

No

Pk_, fk_

ROLE

Text

VARCHAR(30)

No

AUTHOR_LIST

SQL
CREATE TABLE AUTHOR

(

AUTHOR_ID CHAR(5) CONSTRAINT AUTHOR_PK PRIMARY KEY(AUTHOR_ID)
NOT NULL,

LASTNAME VARCHAR(15) NOT NULL,

FIRSTNAME VARCHAR(15) NOT NULL,

EMAIL VARCHAR(40),

CITY VARCHAR(15),

COUNTRY CHAR(2)

)
CREATE TABLE AUTHOR_LIST

(
AUTHOR_ID CHAR(5) NOT NULL CONSTRAINT AUTHOR_LIST_AUTHOR_FK
FOREIGN
KEY(AUTHOR_ID) REFERENCES AUTHOR ( AUTHOR_ID),

BOOK_ID CHAR(5) NOT NULL,
ROLE VARCHAR(15) CONSTRAINT AUTHOR_LIST_PK PRIMARY KEY
(AUTHOR_ID,BOOK_ID) NOT NULL

5 - SQL 131

CREATE TABLE BOOK


(
BOOK_ID CHAR(3) CONSTRAINT BOOK_PK PRIMARY KEY(BOOK_ID) CONSTRAINT AUTHOR_LIST_BOOK_FK FOREIGN KEY(BOOK_ID) REFERENCES
BOOK (BOOK_ID) NOT NULL,

TITLE VARCHAR(40) NOT NULL,

EDITION INTEGER,

YEAR INTEGER,

PRICE DECIMAL(7 , 2),

ISBN VARCHAR(20),

PAGES INTEGER,

AISLE VARCHAR(10),

DESCRIPTION VARCHAR(100)

)
CREATE TABLE COPY

(

COPY_ID CHAR(5) CONSTRAINT COPY_PK PRIMARY KEY(COPY_ID) NOT
NULL,
BOOK_ID CHAR(5) CONSTRAINT COPY_BOOK_FK FOREIGN KEY(BOOK_ID)
REFERENCES
BOOK(BOOK_ID) NOT NULL,

STATUS VARCHAR(10)

CREATE TABLE LOAN


(
COPY_ID CHAR(5) CONSTRAINT LOAN_COPY_FK FOREIGN KEY(COPY_ID)
REFERENCES
COPY(COPY_ID) NOT NULL,
BORROWER_ID CHAR(5) CONSTRAINT LOAN_BORROWER_FK FOREIGN
KEY(BORROWER_ID) REFERENCES BORROWER
(BORROWER_ID)
NOT
NULL,

LOAN_DATE DATE NOT NULL,

LOAN_DAYS INTEGER NOT NULL,


RETURN_DATE DATE CONSTRAINT LOAN_PK PRIMARY KEY(COPY_ID, BORROWER_ID)

132

CREATE TABLE BORROWER


(

KEY

BORROWER_ID CHAR(5) NOT NULL CONSTRAINT BORROWER_PK PRIMARY


(BORROWER_ID),

LASTNAME VARCHAR(15) NOT NULL,

FIRSTNAME VARCHAR(15) NOT NULL,

EMAIL VARCHAR(40),

PHONE VARCHAR(15),

ADDRESS VARCHAR(60),

CITY VARCHAR(15),

COUNTRY CHAR(2)

InfoSphere Data Architect

SQL
DDL

5.10

SQL

SQL

/
SQL
SQL Reference Guide [5.3]

5.11
1.
(default value)

2. 10 SQL
3. SQL
4. SQL correlated sub-query GROUP BY
5. SQL (aggregate function) WHERE,

5 - SQL 133

HAVING
6. SQL ORDER BY

5.12
1. SQL
A. (Data definition)
B. (Data modification)
C. (Data control)
D.
E.

2. SQL
A. Raymond F. Boyce
B. E. F. Codd
C. Donald D. Chamberlin
D. A C
E.

3. SQL
A. American National Standards Institute
B. Bureau of International Standards
C. International Standards Organizations
D.
E.

4.
A. Name Table Name
B. Attribute Column name
C. Method Stored procedure
D.
E.

134

5.
A. Year
B. Dayname
C. Second
D.
E.

6. SQL
A. (Ascending)
B. (Descending)
C. (Random)
D.
E.

7. INSERT
A.
B.

8.
A. Equi-join
B. Natural-join
C. Cross-join
D.
E.

9.
A. Left outer join
B. Right outer join

135

C. Full outer join


D.
E.

10. Union
A.
B.

6 Stored Procedure

Stored Procedure (Function)

SQL

IBM Data Studio Stored Procedure


SQL
Stored Procedure

6.1 IBM Data Studio


IBM Data Studio User-Defined Functions (UDFs)
Stored Procedure IBM Data Studio
Eclipse
DB2
2
IDE: Eclipse
(shell sharing) InfoSphere Data Architect
Rational Data Web Services
Stand-Alone: IDE
Data Web Services
Eclipse (shell sharing)
()
: IBM Data Studio
eBook Getting started with IBM Data Studio for DB2
DB2 on Campus free book

6 Stored Procedure 137

Stand-Alone ibm.com/db2/express
6.1 IBM Data Studio 2.2

6.1 IBM Data Studio 2.2


Data Project Explorer
6.1
6.1.1
Stored Procedure UDFs Data Studio
Data Studio File -> New -> Project
Data Development Project 6.2

6.2 Data Development Project

138

New Select Connection 6.3

6.3
6.3 DB2 for Linux, UNIX and Windows (DB2 LUW) Select a database
manager JDBC driver deault DB2 (LUW) JDBC
type 4 IBM Data Server Driver for JDBC and SQLJ (JDBC 4.0) Default
Host
IBM Data Studio DB2
localhost Host
Test Connection
Finish
Finish
Data Project Explorer +
PL/SQL packages, SQL scripts, Stored Procedures

6.2 Stored Procedures


Stored Procedure SQL

6.2 Stored Procedures

6 Stored Procedure 139


Client Application

Server

SQL #1
SQL #2
SQL #3
Network
myproc
SQL #1
CALL myproc

SQL #2
SQL #3

6.2 Stored Procedures


6.2 SQL

SQL

Stored Procedure myproc SQL
() Call
Stored Procedure
Stored Procedure

Stored Procedures
Stored Procedures

Stored Procedures

6.2.1 Procedures
Stored Procedures : SQL Procedures External Procedures SQL Procedures SQL External Procedures host language

SQL Procedures External Procedures Procedure (procedure definition) Procedure SQL Procedure External Procedure

Procedure
Procedure
Procedure SQL Procedure SQL
Procedure runtime options Procedure
Procedure

SQL Procedure
CREATE PROCEDURE UPDATESALARY

(IN EMPNUMBR CHAR(10),

(1)
(2)

140

IN RATE DECIMAL(6,2))
LANGUAGE SQL

UPDATE EMP

SET SALARY = SALARY * RATE
WHERE EMPNO = EMPNUMBR

(3)
(4)

(1) Procedure UPDATESALARY

(2) EMPNUMBR CHAR(10) RATE DECIMAL(6,2)

(3) LANGUAGE SQL Procedure SQL Procedure

(4) (procedure body) UPDATE SQL


employee
External Stored Procedure
COBOL Stored Procedure
UPDSAL
CREATE PROCEDURE UPDATESALARY

(IN EMPNUMBR CHAR(10),


IN RATE DECIMAL(6,2))
LANGUAGE COBOL

EXTERNAL NAME UPDSAL;

(1)
(2)
(3)
(4)

(1) Procedure UPDATESALARY

(2) EMPNUMBR CHAR(10) RATE DECIMAL(6,2)

(3) LANGUAGE COBOL Procedure External Procedure

Procedure COBOL COBOL

(4) COBOL UPDSAL

6.2.2 Stored Procedure


Stored Procedure Java, PL/SQL SQL PL Data Studio
Stored Procedures Data Studio
Stored Procedure SQL SQL PL
Stored Procedure Java PL/SQL
1: Stored Procedure
Stored Procedure Stored Procedures New ->
Stored Procedure Stored Procedure
Stored Procedure SQL Procedure Data Studio
SQL default Finish Stored Procedure
(template code) SQL 6.3

6 Stored Procedure 141

6.3 Stored Procedure


6.3 Stored Procedure MYPROCEDURE


Stored Procedure
2: Stored Procedure
Stored Procedure Stored
Procedure Data Project Explorer Deploy Deploy
CREATE PROCEDURE compile Stored Procedure
6.4

6.4 Stored Procedure

142

Deploy default Finish


4: Stored Procedure
Stored Procedure
Stored Procedure Run Results
Data Studio 6.5

6.5 Stored Procedure


Stored Procedure DB2 Command Window Command Editor CALL < Procedure>
Store Procedure 6.6
C:\Program Files\IBM\SQLLIB\BIN\db2 connect to sample

Database Connection Information


Database server
SQL authorization ID
Local database alias

= DB2/NT 9.7.0
= ARFCHONG
= SAMPLE

C:\Program Files\IBM\SQLLIB\BIN\db2 call myprocedure


Result set 1
---------------------PROCSCHEMA
PROCNAME
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------SYSPROC
ADMIN_CMD
SYSPROC
ADMIN_COPY_SCHEMA
SYSPROC
ADMIN_DROP_SCHEMA

6.6 Stored Procedure DB2 Command Window

6 Stored Procedure 143

Stored Procedure Java, C, Visual Basic


DB2 Command Window

6.2.3 Stored Procedure


Stored Procedure :
1. Procedure

2. CREATE OR REPLACE PROCEDURE CREATE PROCEDURE


ALTER PROCEDURE
Procedure
Procedure Procedure (fully qualified name)
DROP PROCEDURE
drop procedure myschema.EMPLOYEE_COUNT
Procedure CREATE OR REPLACE PROCEDURE Procedure Procedure
Procedure CREATE OR REPLACE PROCEDURE

6.3
SQL

,
User-Defined Functions Functions Library

6.3.1
:

Scalar ()
- Aggregate ()
- String ()
Table ()

(UDFs) UDF SQL


host language User-Defined Function
SQL SQL
DB2 Scalar Table UDFs SQL PL, PL/SQL, C/C++, Java, CLR (Common Language Runtime) OLE (Object Linking and Embedding)
6.3.1.1 (Scalar Function)

SQL SQL INSERT, UPDATE


DELETE LENGTH

SELECT length(Mary)
FROM sysIBM.sysdummy1
SQL DB2

144

4 Mary
SQL SELECT-LIST
FROM
SELECT EMPNO, LASTNAME, YEAR(CURRENT DATE - BIRTHDATE)
FROM EMPLOYEE
WHERE WORKDEPT = D01
YEAR CURRENT
DATE BIRTHDATE

SQL
where clause (predicates) (query)

(Aggregate functions)

AVG(COL_NAME) COL_NAME

(Strings functions)

SUBSTR(abcdefghi,3,4)
(, , )
cdef
(Table functions)
FROM
INSERT, UPDATE
DELETE SQL DB2 SNAPSHOT_DYN_SQL()
MQREADALL() (Views)
(INSERT, UPDATE, DELETE)

CREATE FUNCTION getEnumEmployee(p_dept VARCHAR(3))


RETURNS TABLE
(empno CHAR(6),
lastname VARCHAR(15),
firstnme VARCHAR(12))
SPECIFIC getEnumEmployee
RETURN
SELECT e.empno, e.lastname, e.firstnme
FROM employee e
WHERE e.workdept=p_dept

6.3.2
Stored Procedure IBM Data Studio
User-Defined Function user-defined functions
Stored procedures Stored Procedure CREATE FUNCTION user-defined function (function template)

6 Stored Procedure 145


>>-CREATE--+-----------------+--FUNCTION--function-name-------------->

-OR REPLACE-

.-IN------.
>--(--+---------+--parameter-name--| data-type1 |--+-------------------+--|-)-->
|
|
-| default-clause |-
+-OUT----+

-INOUT---

>-- RETURNS--+-| data-type2 |-------------+--| option-list |----->

-+-ROW-----+-----| column-list |-

--TABLE---

>--| SQL-function-body |---------------------------------------><


SQL PL

CREATE FUNCTION REVERSE(INSTR VARCHAR(40))


RETURNS VARCHAR(40)
DETERMINISTIC NO EXTERNAL ACTION CONTAINS SQL
BEGIN ATOMIC
DECLARE REVSTR, RESTSTR VARCHAR(40) DEFAULT ;
DECLARE LEN INT;
IF INSTR IS NULL THEN
RETURN NULL;
END IF;
SET (RESTSTR, LEN) = (INSTR, LENGTH(INSTR));
WHILE LEN > 0 DO
SET (REVSTR, RESTSTR, LEN)
= (SUBSTR(RESTSTR, 1, 1) CONCAT REVSTR,
SUBSTR(RESTSTR, 2, LEN - 1),
LEN - 1);
END WHILE;
RETURN REVSTR;
END
@
DB2 v9.7 Information Center

6.3.3
SQL
CALL SELECT VALUES REVERSE
SELECT reverse(col_name) from myschema.mytable
OR
VALUES reverse(abcd)
FROM SQL
TABLE() (alias)

146

getEnumEmployee SELECT 6.1

SELECT * FROM

TABLE ( getEnumEmployee(E01)) T
TABLE () function

alias

6.7

6.3.4

user-defined function
1.
2. CREATE OR REPLACE FUNCTION CREATE FUNCTION
ALTER FUNCTION
FUNCTION
Function Function (fully qualified name)
DROP FUNCTION
DROP FUNCTION myschema.reverse
Function CREATE OR REPLACE FUNCTION Function
Function
Function CREATE OR REPLACE FUNCTION

6.4
Stored Procedures
Stored Procedures
EXECUTE Stored Procedure Stored Procedure

6.5
1. SQL PL Stored Procedure IBM Data Studio SAMPLE
DB2 procedure
EMPLOYEE

2. UDF (1)

3. SQL Function
( Monday, Tuesday )

4. SQL Function (
Monday, Tuesday )

5. procedure

6. procedure

6 Stored Procedure 147

6.6
1.
A. Select
B. Update
C. Count
D. Delete
E.

2.
A. avg
B. count
C. insert
D. substr
E.
3.
A. avg
B. count
C. max
D. substr
E.
4.
A. trim
B. upper
C. min
D. substr
E.
5.
A. lcase
B. year
C. max
D. substr
E.

148

6.
A. sum
B. min
C. max
D. len
E.
7.
A. avg
B. year
C. max
D. substr
E.
8. Stored Procedures Data Studio
A. SQL PL
B. PL/SQL
C. Java
D.
E.
9. VALUES
A.
B.
10. Procedure CALL
A.
B.

6 Stored Procedure 149

7 SQL
Structured Query Language (SQL)
,
SQL C,
C++, Java, .NET

Transaction

embedded SQL
static dynamicSQL
APIs ODBC, CLI JDBC
pureQuery

7.1 SQL
SQL
SQL
C, C++ Java
(functional logic)
Host Language SQL
SQL (embedded) host application
Application Programming Interface (API)
ODBC, CLI JDBC SQL
7.1

7 SQL 151

Application

SQLJ
IBM DB2 CLI

JDBC

Embeded SQL

Supports both static and dynamic execution modes


Supports dynamic execution

7.1 SQL

7.2 Transaction ?
SQL
Transaction Transaction (unit of work)
insert, update delete
Transaction
1,000 A B

1,000 A
1,000 B

SQL SQL 2
2
Transaction SQL (Commit)
(Rollback) Transaction Transaction

7.3 Embedded SQL


Embedded SQL SQL host application
C, C++ COBOL host application
SQL
(compile)
SQL ?
(compiler)
SQL (pre-compilation)
DB2 (pre-compiler) SQL

152

API runtime services API calls


(link) host language
SQL host language embedded SQL C, C++ COBOL EXEC SQL SQL
(;)
EXEC SQL
UPDATE employee.details
SET emp_desig = Mgr WHERE emp_desig = Asst Mgr;
SQL Java
SQLJ #sql SQL
EXEC SQL host language
UPDATE SQL SQLJ :
#sql {
UPDATE employee.details
SET emp_desig = Mgr WHERE emp_desig = Asst Mgr;
SQLStatic ,
SQL

DynamicSQL

7.3.1 Static SQL


Static SQL SQL (embedded
SQL) Static SQL
SQL

SELECT
SQL
SQL (hard-code)
SQL (static embedded SQL application) SQL
where clause SQL
SQL
(host variables)
7.3.1.1 (Host variables)
static SQL
(default)
_hv
SQL C
7.1
EXEC SQL
SELECT emp_name, emp_dept, emp_salary
INTO :name_hv, :dept_hv, :salary_hv
FROM employee.details

7 SQL 153

WHERE emp_id = :id_hv ;


EXEC SQL
UPDATE employee.details
SET emp_salary = :new_salary_hv
WHERE emp_id = :id_hv ;

7.1 SQL C

(employee.details) (emp_name, emp_dept, etc.)


SQL
(id_hv, dept_hv, ) (:)
SQL
7.3.1.2 SQL
SQL
SQL

(DECLARE SECTION)

SQL
(commit) (rollback) SQL
7.2 SQL
C
int getDetails( int employee_id, double new_salary)
{
int ret_code = 1;
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
sqlint32 id_hv = 0;
// employee id
char name_hv[129] = {0};
// employee name
char dept_hv[129] = {0}; // employee department
double salary_hv = 0;
// employee salary
EXEC SQL END DECLARE SECTION;
// Copy the employee id and salary passed to this function
// into the host variables
id_hv = employee_id;
salary_hv = new_salary;
// Issue the UPDATE statement to set the new salary of an employee
EXEC SQL
UPDATE employee.details
SET emp_salary = :salary_hv WHERE emp_id = :id_hv;
if (SQLCODE < 0)

154

{
printf(\n UPDATE SQL Error:%ld\n,SQLCODE);
EXEC SQL ROLLBACK; // Rollback the transaction
ret_code = 0; // error
}
else
{
EXEC SQL COMMIT; // Commit the transaction
// Issue a SELECT to fetch updated salary information
EXEC SQL
SELECT emp_name, emp_dept, emp_salary
INTO :name_hv, :dept_hv, :salary_hv
FROM employee.details
WHERE emp_id = :id_hv;

if (SQLCODE < 0)
{
printf(\n SELECT SQL Error:%ld\n,SQLCODE);
Ret_code = 0;
}
else
{
// Display the updated salary information
printf(\n Employee name: %s,name_hv);
printf(\n Employee Id: %d,id_hv);
printf(\n Employee Department: %s,dept_hv);
printf(\n Employee New Salary: Rs. %ld p.a,salary_hv);
}
}
return ret_code;
int getDetails( int employee_id, double new_salary)
{
int ret_code = 1;
EXEC SQL INCLUDE SQLCA;
EXEC SQL BEGIN DECLARE SECTION;
sqlint32 id_hv = 0;
// employee id
char name_hv[129] = {0};
// employee name
char dept_hv[129] = {0}; // employee department
double salary_hv = 0;
// employee salary
EXEC SQL END DECLARE SECTION;

7 SQL 155

// Copy the employee id and salary passed to this function


// into the host variables
id_hv = employee_id;
salary_hv = new_salary;
// Issue the UPDATE statement to set the new salary of an employee
EXEC SQL
UPDATE employee.details
SET emp_salary = :salary_hv WHERE emp_id = :id_hv;
if (SQLCODE < 0)
{
printf(\n UPDATE SQL Error:%ld\n,SQLCODE);
EXEC SQL ROLLBACK; // Rollback the transaction
ret_code = 0; // error
}
else
{
EXEC SQL COMMIT; // Commit the transaction

// Issue a SELECT to fetch updated salary information


EXEC SQL
SELECT emp_name, emp_dept, emp_salary
INTO :name_hv, :dept_hv, :salary_hv
FROM employee.details
WHERE emp_id = :id_hv;
if (SQLCODE < 0)
{
printf(\n SELECT SQL Error:%ld\n,SQLCODE);
Ret_code = 0;
}
else
{
// Display the updated salary information
printf(\n Employee name: %s,name_hv);
printf(\n Employee Id: %d,id_hv);
printf(\n Employee Department: %s,dept_hv);
printf(\n Employee New Salary: Rs. %ld p.a,salary_hv);
}
}
return ret_code;
}
7.2 -- SQL C

156

SQL C host language


C++, COBOL, Java
7.3.1.3 SQL communications area SQLCODE SQLSTATE
SQL Communications Area (SQLCA)
(client) SQLCA
SQL SQLCODE
0 () SQL
SQL
(Warning) SQLCODE
SQL (error) SQLCODE
SQLCODE SQL
SQLCODE

SQLCODE SQL
SQLSTATE SQLCA String
SQL SQLSTATE

7.3.1.4 Static SQL


SQL
DB2 (DB2 pre-compiler)
SQL DB2 runtime APIs
( comment SQL )
(link) host language
DB2 PRECOMPILE ( PREP)
DB2
1. SQL

fetch

2. (access plan)

SQL SQL DB2 optimizer


SQL

Static (static embedded SQL statement)

optimizer
(system catalog)

SQL
SQL optimizer

SQL Static
(pre-compile)

SQL (bind)
SQL (link)

7 SQL 157

4
5
6

158

SQL Dynamic
(Interactive)
SQL 7.3 ,Employee finder tool
HR

Employee Finding Tool


Select Search field

Enter Search Value


Submit

V
Employee Name
Employee Id

RESULTS
Employee Name

Employee Id
Employee Designation

7.3 Employee finder tool


HR

SQL
SQL Dynamic Static SQL
Dynamic SQL (Runtime)
7.3.2.1 SQL
7.3
Employee Finder Tool SQL Dynamic
SQL C
int findEmployee(char * field, char * value, char * emp_name, char * emp_id, char *
emp_desig)
{
int ret_code = 1;
char sqlstmt[250] = {0};
EXEC SQL INCLUDE SQLCA;
EXEC
char
char
char
char

SQL BEGIN DECLARE SECTION;


name_hv[129] = {0}; // employee name
desig_hv[129] = {0}; // employee designation
id_hv[10] = {0};
// employee id
value_hv[250] = {0}; // Field value

7 SQL 159

EXEC SQL END DECLARE SECTION;


// Copy the Search Field passed to this function into
// the sqlstmt string
sprintf(sqlstmt,SELECT emp_name, emp_id, emp_desig
FROM employee.details
WHERE %s = ?,field);
// Copy the field value passed to this function into the
// host variable
strcpy(value_hv,value) ;
// Prepare the dynamic SQL statement first. This statement would
// create the access plan at runtime
EXEC SQL PREPARE dynsqlstmt FROM :sqlstmt;
if (SQLCODE <0)
{
printf(\n Error during Prepare statement:%ld,SQLCODE);
ret_code = 0; //error
}
else
{
EXEC SQL DECLARE cur1 CURSOR FOR :dynsqlstmt;
if (SQLCODE <0)
{
printf(\n Error during Declare Cursor:%ld,SQLCODE);
ret_code = 0; //error
}
else
{
EXEC SQL OPEN cur1 USING :value_hv;
if (SQLCODE <0)
{
printf(\n Error during Open Cursor:%ld,SQLCODE);
ret_code = 0; //error
}
else
{
EXEC SQL FETCH cur1 INTO :name_hv, :id_hv, :design_hv;
if (SQLCODE <0)
{
printf(\n Error during Fetch cursor:%ld,SQLCODE);
ret_code = 0; //error
}
else
{

160

EXEC SQL CLOSE cur1;


if (SQLCODE <0)
{
printf(\n Error during Close cursor:%ld,SQLCODE);
Ret_code = 0; //error
}
else
{
// Copy the fetched results into the target variables
strcpy(emp_name,:name_hv);
strcpy(emp_id,:id_hv);
strcpy(emp_desig,:desig_hv);

}
return ret_code;
7.3 SQL C SQL static
Dynamic

Employee Finder Tool


() field
SQL( sqlstmt )
Employee Id SQL ( predicate
where )
SELECT emp_name, emp_id, emp_desig from employee.details WHERE emp_id =?
(?) parameter marker
( emp_id)
(runtime)
(prepare) SQL Dynamic (
EXEC SQL PREPARE )
SQL
SELECT emp_name, emp_id, emp_desig from employee.details WHERE emp_name =?
SQL
(prepare) SQL Dynamic
( )
(prepare) SQL
SELECT (declare cursor)
SQL (open cursor)
fetch

(Close cursor)

7 SQL 161

1. (code) Static SQL

(Statement preparation) (cursor declaration),


SQL ( SQLJ)
SQL static

2. Static SQL APIs, /

SQL

SQL Dynamic SQL Static ( PREPARE, EXECUTE, CURSOR ,)

7.3.3 Static dynamic SQL


Static SQL Dynamic SQL
SQL
1.

SQL Dynamic SQL Static


Dynamic (runtime)
Dynamic (prepare)

2.

SQL

Dynamic Static SQL Dynamic SQL


Dynamic SQL Static
SQL

3.

SQL Dynamic Static SQL


SQL Static

SQL Dynamic
4.

Dynamic SQL Static SQL

SQL Static

rebinding
Dynamic SQL
(runtime), rebinding

7.4 Application Programming Interface (APIs)


SQL
SQL Dynamic SQL Static
(Pre-compilation) SQL (SQL translation)
SQL
(Database
catalog)
(Database Application Programming Interfaces)
Dynamic

162

API APIs
C, C++, Java
SQL
callable interfaces API
database connectivity driver
libraries libraries source code



API SQL

7.4.1 ODBC IBM Data Server CLI driver

X/

Open SQL Access Group X/Open Call


Level Interface


(ISO/IEC 9075-3:1995 SQL/CLI)

SQL callable Open Database

Connectivity (ODBC) X/Open CLI


ODBC

DB2 IBM Data Serv-

er CLI driver DB2 Call level interface Microsoft ODBC


SQL/CLI DB2 Call Level Inteface

Call Level Interface

CLI DB2

DB2 CLI API C C++ (function


call) SQL Dynamic (arguments)

PREPARE EXECUTE SQLPrepare() SQLExecute


SQL EXEC SQL

SQL Dynamic (prepare) SQLPrepare () API


SQLCHAR *stmt = (SQLCHAR *)UPDATE employee.details SET emp_id = ? WHERE
emp_name = ? ;
/* prepare the statement */
int rc = SQLPrepare(hstmt, stmt, SQL_NTS);
IBM CLI callable interface SQLConnect (),
SQLFetch (), SQLExecute
ODBC IBM DB2 Call Level Interface ODBC
3.51
7.4 IBM DB2 CLI driver Dynamic SQL


ODBC driver ODBC Driver Manager

IBM DB2 CLI driver

7 SQL 163

ODBC Driver Manager


Environment

DB2 CLI
Environment
Application

Application
ODBC Driver Manager

Other
ODBC
driver

Other
ODBC
driver

DBMS A

Gateway
B

DB2 CLI
dirver
DB2
ODBC
driver

Data Server
Client

Data Server
Client

DB2
Server

DB2 Connect

DBMS B
DB2
Server

DB2 Connect

7.4-- IBM DB2 CLI ODBC

DB2 (MVS)
SQL/DS
SQL400
other DRDS
DBMS

7.4.2 JDBC
JDBC Java Database Connectivity

SQL ODBC CLI JDBC


(Java) CLI

(link) CLI libraries JDBC


JDBC APIs import

SELECT JDBC 7.4

// SQL for SELECT. The name, country, street and province information
// which has been provided by the user are stored in respective variables.
String sqlSel = select +name+, +country+, +street+, +province+, +zip+
from CUSTOMER where Customer = ?;
//prepare the SELECT statement
try {
PreparedStatement pstmt=con.prepareStatement(sqlSel);

164

pstmt.setString (1, custCountry);


//set the Input parameter
pstmt.execute();
//execute SELECT statement
ResultSet result = pstmt.getResultSet (); //get the results and set
//values
List<Customer> custList = new ArrayList<Customer>();
while (result.next ()) {

Customer cust = new Customer();

cust.name = result.getString (1);

cust.country = result.getString (2);

cust.street = result.getString (3);


cust.province = result.getString (4);


cust.zip = result.getString (5);
custList.add (cust);

}
} catch (SQLException e) {e.pringStackTrace ();
}
7.4 JDBC

SQL (sqlSel)

SQL Dynamic prepare parameter marker


( ?)

SQL parameter marker

JDBC pstmt.setString(1, custCountry) parameter marker


custCountry


ResultSet result

7.5 pureQuery
Dynamic SQL

overhead SQL prepare


parameter marker JDBC

pureQuery SQL

Dynamic SQL

JDBC

7.4 SELECT pureQuery


7.5

7 SQL 165

//The name, country, street and province are variables which would be
//populated at runtime using user inputs.
String sqlSel = select +name+, +country+, +street+, +province+, +zip+
from CUSTOMER where Customer = ?;
Data data = DataFactory.getData (con);
//execute the Select and get the list of customer
List<Customer> customerList = data.queryList (sqlSel, Customer.class, custCountry);
7.5 pureQuery
pureQuery API queryList sqlSel

custCountry cutomerList
JDBC SQL (runtime)

JDBC

pureQuery (inline method)

SQL Dynamic pureQuery SQL static


(annotated method)

SQL API
pureQuery SQL string pureQuery annotation

@Select ( )
@Update ( SQL Data Manipulation Language: DML)
@Call ( SQL CALL)

SELECT
SELECT Name, Country, Street, Province, Zip FROM customer where Customer = ?
pureQuery

SQL Select annotation


(user-defined function) SQL

7.6 SQL SELECT @Select annotation


public interface CustomerData
{
//Select PDQ_SC.CUSTOMER by parameters and populate Customer bean with

166

results
@Select(sql=select Name, Country, Street, Province, Zip from CUSTOMER where
Customer =?)
Customer getCustomer(int cid);

}
7.6 @Select

SQL Custom-

erData

pureQuery pureQuery

pureQuery generator

(instance variable) CustomerData

pureQuery API getCustomer() SQL


7.7

// use the DataFactory to instantiate the user defined interface


CustomerData cd = DataFactory.getData(CustomerData.class, con);
// execute the SQL for getCustomer() and get the results in Customer beans
Iterator<Customer> cust = cd.getCustomer();
7.7 SQL pureQuery annotation method
pureQuery generator (CustomerDataImpl.java

) (user-defined interface - CustomerData) SQL (declare method)


getCustomer

SQL

SQL

SQL (Business Logic)

pureQuery Static
Dynamic

pureQuery :

http://publib.boulder.ibm.com/infocenter/idm/v2r2/index.jsp?topic=/com.ibm.datatools.
javatool.runtime.overview.doc/topics/helpindex_pq_sdf.html

7.5.1 IBM pureQuery Client Optimizer


pureQuery pureQuery Client Optimizer

SQL Dynamic SQL

pureQuery Client Optimizer

JDBC Dynamic

7 SQL 167

SQL Static
pureQuery Client Optimizer

pureQuery Client Optimizer


SQL pureQueryXml

SQL XML Command


Line Configure

staticBinder

static
SQL Static

SQL SQL

pueryQueryXml
SQL Static
SQL SQL
Dynamic

7.6
SQL

transaction SQL

SQL Static Dynamic


SQL Static SQL
Dynamic

SQL
SQL

SQL SQLJ Static Dynamic

Dynamic

SQL Static

API ODBC, CLI JDBC

SQL Dynamic SQL

pureQuery

SQL Dynamic

(prepare)

168

7.7

A.
B.

C.
D.

Dynamic
Static

7.8
1. SQL Static
A. (runtime)
B. (pre-compile)
C.

D.
2. SQL
A. SQL
B. SQL
C.
D.
3. C C++ SQL
A. DB2 pre-compiler
B. DB2 pre-compiler

4. SQLJ

D. SQL
E. Call Level Interface SQL

5. ODBC
E.

Open Database Community

G.

Open source database community

F.

H.
I.

Open Database Connectivity


Open database connection

6. Static Dynamic
A. JDBC
B. SQLJ

C. DB2 CLI

169

D.

E.
7.
A. JDBC
B. SQLJ

C. DB2 CLI

D.

E.
8. (?)
H. (runtime)
I.

J. SQL
K.

L.
9. pureQuery (annotated method)
I.

SQL Dynamic

J. SQL Static
K.

L.
10. pureQuery Client Optimizer

J. JDBC Static

K. JDBC Static

8 XML

(relational mod-

el)

(structure relational) (semi-structure)


(unstructured)

XML (semi-structure)

XML

XML

DB2
XML (hybrid data server)

8.1 XML
XML eXtensible Markup Language XML (hi-

erarchical) nodes parent/child


XML

8.1.1 XML element

8 XML 171

XML element XML (XML document) XML

XML element XML element root document element element (attribute) child element
XML element
<name>I am an XML element</name>
XML element

(start tag) (end tag)

<name> </name> element

(text value) I am an XML element XML


XML element

<employees>

<employee id=121>

<firstname>Jay</firstname>

<lastname>Kumar</lastname>

<job>Asst. manager</job>


<doj>2002-12-12</doj>

</employee>
</employees>
<employees> document element XML child ele-

ment <employee> element <employee> child element element

id 121 DB2 XML

department(id integer, deptdoc xml)


id deptdoc

XML XML XML


8.1 XML DB2

172

XML data is stored in XML-type columns in tables

create table dept (deptID char(8),..., deptdoc xml);

XML data is stored

in a parsed hierarchical
format

Relational columns

are stored in relational


format

deptID

--

PR27

... <dept> ...


<emp> ... </emp>
</dept>

...

...

deptdoc

...
DB2 Storage

8.1 XML DB2


DB2 XML (parsed)
(hierarchical format) DB2
XML

8.1.2 XML (XML attribute)


element ele-

ment element id uid 100-233-03


45

<product id=100-233-03 uid=45/>


element element

element
<product id=100-233-03 id=10023303/>

XML (XML schema definition)
element

child element

element

<xs:element name=employee>
<xs:complexType>
<xs:sequence>
<xs:element name=firstname type=xs:string/>

8 XML 173

<xs:element name=lastname type=xs:string/>


</xs:sequence>
<xs:attribute name=empid type=xs:integer/>
</xs:complexType>
</xs:element>

8.1.3 Namespaces
XML namespaces

element

XML

XML

element

element namespace element


XML namespace

Namespace Uniform Resource Identifier (URI)


Local name
http://www.acme.com/names namespace URI customer local name
prefix URI customer element

http://www.acme.com/names URI acme:customer acme

namespace prefix http://www.acme.com/names namespace prefix


XQuery Prolog

Declare namespace acme http://www.acme.com/names


namespace prefix element constructors
<book xmlns:acme=http://www.acme.com/names>
namespace element child element
namespace

namespace prefix namespace prefix :


Xml, xs, xsi, fn, xdt
namespace (default) namespace prefix
:

declare default element namespace http://www.acme.org/names


( XQuery Prolog)
<book xmlns = http://www.acme.com/names">
( element constructor )

8.1.4 (Document Type Definition: DTD)


XML

174

element XML DTD


XML DTD
<!DOCTYPE TVSCHEDULE [
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT

PRODUCTS (PRODUCT+)>
PRODUCT (NAME,PRICE,DESCRIPTION)>
NAME (#PCDATA)>
PRICE (#PCDATA)>
DESCRIPTION (#PCDATA)>

<!ATTLIST PRODUCTS ID CDATA #REQUIRED>


]>
XML DTD
<PRODUCTS>
<PRODUCT ID=100-200-43>
<NAME>Laptop</NAME>
<PRICE>699.99</PRICE>
<DESCRIPTION>This is a Laptop with 15 inch wide screen, 4 GB RAM, 120 GB HDD </
DESCRIPTION>
</PRODUCT>
</PRODUCTS>
<PRODUCTS>
<PRODUCT ID=100-200-56>
<NAME>Printer</NAME>
<PRICE>69.99</PRICE>
<DESCRIPTION>This is a line printer </DESCRIPTION>
</PRODUCT>
<PRODUCT ID=100-200-89>
<NAME>Laptop</NAME>
<PRICE>699.99</PRICE>
<DESCRIPTION>This is a Laptop with 13 inch wide screen, 4 GB RAM, 360 GB HDD </
DESCRIPTION>
</PRODUCT>
</PRODUCTS>

8.1.5 XML Schema


XML Schema XML

schema document namespace schema document

8 XML 175

<xsd:schema targetNamespace=http://www.mycompany/products

xmlns:xsd=http://www.w3.org/2001/XMLSchema>

<xsd:simpleType name=PriceType>

<xsd:restriction base=xsd:decimal>
<xsd:minInclusive value=0/>
XML Schema
<xsd:maxInclusive value=100000/>
Namespace
<xsd:totalDigits value=9/>
<xsd:fractionDigits value=3/>

</xsd:restriction>

</xsd:simpleType>

<xsd:complexType name=StockPriceType>

<xsd:sequence>
<xsd:element name=Asktype=PriceType/>
<xsd:element name=Bid type=PriceType/>
<xsd:element name=P50DayAvg type=PriceType/>

</xsd:sequence>

<xsd:complexType>
<xsd:element name=StockPrice type=StockPriceType/>
</xsd:schema>
8.2 XML Schema
XML Schema XML DTDs XML Schema

XML XML Schema XML Schema Definition (XSD)


XML Schema DTDs XML Schema

XML XML Schema

integer date decimal datetime


complex element
(enumeration)

element XML XML Schema DTDs

XML Namespaces XML Schema (inheritance) W3C 2544

XML Schema schema documents namespaces

176

Orderschema
Namespace:
Order

Namespace:
Lineitem
Order.xsd

include

Lineitem.xsd

Parts.xsd

import

http://www.w3.org/TR/xmlschema-0/
8.3 - namespace namespace XML Schema
DB2 XML Schema

XML XML XML XML Schema XML Schema fixed schema

XML (validate) XML XML

( ) XML Schema XML


Schema XML XML

XML DB2 XML


(clause) IS VALIDATED select

8.2 XML Schema


XML Standard Generalized Markup Language (SGML)

XML namespace
XML XML
integrity constraints

8.2.1 (simple types)


XML Schema W3C 8.4

8 XML 177

Built-In Simple Types:


string
boolean
float
decimal
integer
positiveInteger
byte
date
datetime

Derived Simple Types:

Complex Types:

Restriction of simple type

may include
elements/attribute
definition

Union of simple type

can define choice or


sequence of elements

"integer between 5 and 10"


"integer U string"

Enumerations
etc.

anytime
...

8.4 XML Schema


element XML
element
(user-defined type)

myInteger
xs:integer -2 5

<xs:simpleType name= myInteger >


<xs:restriction base= xs:integer >
<xs:minInclusive value = -2 />
<xs:maxExclusive value = 5 />
</xs:restriction>
</xs:simpleType>
(derivation by restriction)

(enumeration) schema element :
<xs:simpleType name= passGrades >
<xs:restriction base= xs:string >
<xs:enumeration value = A />
<xs:enumeration value = B />
<xs:enumeration value = C />
</xs:restriction>
</xs:simpleType>
element passGrades
(A, B C) element XML Schema
(pattern of value) element

178

:
<xs:simpleType name= CapitalNames >
<xs:restriction base= xs:string >
<xs:pattern value = ([A-Z]( [a-z]*)?)+ />
</xs:restriction>
</xs:simpleType>
derivation by list derivation by
union derivation by list
<xs:simpleType name= myintegerList >
<xs:list itemType= xs:integer />
</xs:simpleType>
element
1 234 333 -32321 derivation by union
<xs:simpleType name= intordate >
<xs:union memberTypes= xs:integer xs:date />
</xs:simpleType>

element
223 1 2001-10-26

(integer date)

8.2.2 (complex types)


element

element element/

element (empty)
element (text)

<xs:complexType name=employeeType>
<xs:sequence>
<xs:element name=firstname type=xs:string/>
<xs:element name=lastname type=xs:string/>
</xs:sequence>
</xs:complexType>
element
<xs:element name=employee type=employeeType>

<xs:element name=employee>
<xs:complexType>
<xs:sequence>
<xs:element name=firstname type=xs:string/>
<xs:element name=lastname type=xs:string/>
</xs:sequence>
</xs:complexType>

8 XML 179

</xs:element>

element

8.2.3 Integrity Constraints


XML Schema

ID IDREFs XML DTDs XML Schema xs:ID xs:IDREFs


XML Schema, xs:ID xs:IDREFs element

DTDs element
element xs:unique
<xs:element name =book >
<xs:complexType>
.
</xs:complexType>
<xs:unique name=book>
<xs:selector xpath=book/>
<xs:field xpath=isbn/>
</xs:unique>
</xs:element>

ISBN XML
xs:key xs:keyref integrity constraints key unique constraint
element unique
<xs:element name =book >
<xs:complexType>
.
</xs:complexType>
<xs:key name=book>
<xs:selector xpath=book/>
<xs:field xpath=isbn/>
</xs:key>
</xs:element>
xs:keyref key (current scope)
element xs:keyref xs:key element xs:unique
element element element (ancestor)

8.2.4 XML Schema


XML

XML Schema

DB2 XML Schema

DB2 XML XML Schema DB2

180

XML XML Schema XML DB2


(compatibility) XML Schema
DB2 Schema Schema

XML Schema
DB2 pureXML:

Schema ( compatible) register schema


XML Schema Repository (XSR) schema
schema ( SQL URI)
schema

XML Schema ( not compatible) register schema


SQL URI

schema XMLVALIDATE

XML SChema SQL URI XML


instance document URI XML instance document
schema

schema

XML Schema XSR


:

1. stored procedure XSR_REGISTER REGISTER XMLSCHEMA XML Schema XSR

XML Schema
schema schema

2. stored procedure XSR_UPDATE UPDATE XMLSCHEMA XML Schema XSR schema

XML Schema Schema XML Schema


XML Schema

dropnewschema stored procedure XSR_UPDATE UPDATE XMLSCHEMA schema schema

8.3 XPath
XPath 2.0 expression language XQuery/XPath

Data Model (XDM) XPath path expression XML


XSLT XQuery W3C

8 XML 181

8.3.1 XPath (XPath data model - XDM)


XDM XML XDM (se-

quence) (zero item) (more item)


(item) :

Atomic values integers strings Booleans


XML nodes Document, element, attribute text
XPath XQuery expression instance XDM (sequence)

(item) atomic

values nodes

(<x/>, <y/>, 45) (beta, 2)

(beta, <x/>, <y/>, 45, 2)

XQuery

(comma)
8.3.2 Document node

Document node node XML XML

document node document node XML DB2

(sequence) XQuery XPath XML 8.5


nodes XML data model

8.5 XML Data Model:


content expression XML root element customer-list:

182

document
{
<customer-list>
{db2-fn:xmlcolumn(MYSCHEMA.CUSTOMER.INFO)/ns1:customerinfo/
name}
</customer-list>
}
XML (well-formed) node document
node

XML element <products> document node


document node root node

<products>
<product pid=100-201-01><description>
<name>Ice Scraper, Windshield 4 inch</name>
<price>3.99</price></description>
</product>
</products>

8.3.3 Path Expressions


Path expressions expression XPath (step)

(/) (//)

path expression (final step) path expression

expression / path root node

expression // path root node

node (all child nodes) //name element name


XML

8.3.4 Advanced Navigation in XPath


(step) axis step filter expression axis

step :

optional axis XML


node test node
Predicates (sequence) (step)
axis step axisname::nodetest[predicate]

Child::book book node child node node

Attribute::id id attribute node

8 XML 183

axis step nodes node context position

context position

8.3.5 XPath Semantics



Context node node (match)
node context node nested XPath expression
( [ ] )
axes DB2
Axis

Description

Direction

Self

Returns the context node.

Forward

Child

Returns the children of the context node

Forward

descendant
descendant-or-self

Returns the descendants (children, grandchildren) of the context node


Returns the context node and its descendants

Forward
Forward

Parent

Returns the parent of the context node

Reverse

Attribute

Returns the attributes of the context node

Forward

node test nodes (true) node


axis step node test name test kind test

name test node

node QName

(*) node (element ) (match)

QNames QName QName node QName name test


QNames namespace local names

name test DB2


Test

Description

QName

Matches all nodes whose QName is equal to the specified QName

NCName.*

Matches all nodes whose namespace URI is the same as the


namespace to which the specified prefix is bound

*.NCName

Matches all nodes whose local name is equal to the specified NCName

Matches all nodes

184

Kind test nodes nodes kind test


DB2

Test

Description

node()

Matches any node

text()

Matches any text node

comment()

Matches any comment node

processing-instruction()

Matches any processing instruction node

element()

Matches any element node

attribute()

Matches any attribute node

Document-node()

Matches any document node

(syntax) 2 axis step unabbreviated abbreviated


unabbreviated axis node test (::)
abbreviated

abbreviated DB2
Abbreviated syntax

Description

No Axis specified

child:: except when the node test is attribute(). In that case,


omitted axis shorthand for attribute::

attribute::

//

/descedent-or-self::node() except when it appear in the beginning of path expression. In that case, axes step selects the
root of the tree plus all nodes that are its descendents

self::node()

..

Parent::node()

path expressions
Path expression

Path Expression using abbreviated


syntax

/dept/emp/firstname/child::node()

/dept/emp/firstname

/dept/emp//firstname/parent::node()/@id

/dept/emp/firstname/../@id

8 XML 185

8.3.6 XPath Queries


DB2 XPath expression path expressions XQuery
XQuery ( element)
DESCRIPTION

XQuery db2-fn:xmlcolumn(PRODUCT.DESCRIPTION)/product/description/name
Execution result
1
-----------------------------------------------------<name>Snow Shovel, Basic 22 inch</name>
<name>Snow Shovel, Deluxe 24 inch</name>
<name>Snow Shovel, Super Deluxe 26 inch</name>
<name>Ice Scraper, Windshield 4 inch</name>
4 record(s) selected.
xmlcolumn XQuery string argument SCHEMANAME.TABLENAME.XMLCOLUMNNAME default schema
TABLENAME.XMLCOLUMNNAME Db2-fn namespace
xmlcolumn xmlcolumn XML
XML

DB2 XQuery sqlquery xmlcol-

umn sqlquery
XML

XML

xmlcolumn XQuery pid 100-201-01


pid (relational column)

XQuery db2-fn:sqlquery(select DESCRIPTION from PRODUCT where pid= 100-20101)/product/description/name


Execution result :
1
--------------------------------------------------<name>Ice Scraper, Windshield 4 inch</name>
1 record(s) selected.

8.4 XQuery
XQuery

XQuery XML

W3C

XQuery XML XQuery XML


SQL 8.6 XQuery XML

8.6 XPath XQuery XPath XPath


expressions

186

Owned by
XSLT WG

Owned by
Query WG

XML
SCHEMA

XQuery

Owned by
Schema WG

XSLT
XPath 2.0

Owned jointly by
Query and XSLT WGs

The W3C XML Query Working Group worked with the W3C XML Schema Working
Group and the W3C XSL Working Group to make a set of specifications that all
work together.
Use XQuery to take data from multiple databases, from XL files, from remote
Web documents even from CGI scripts, and to produce XML results that you can
process with XSLT.
www.w3.org/CML/Query/

8.6 - XQuery

8.4.1 XQuery
XQuery
prolog (declarations)
(query)

(query body) expression


(input) (output) XQuery instance XDM


XQuery element namespace default
prolog FLWOR expression FLWOR expression

XQUERY
declare default element namespace http://posample.org;
for $cust in db2-fn:xmlcolumn(CUSTOMER.DESCRIPTION)
return $cust/Name/LastName;
(body) XQuery expression

8 XML 187

Literals and variables


Path expressions
Predicates
If ..then..else
Constructors
Comparisons
FLWOR expressions

8.4.2 FLWOR expressions


FLWOR expressions XQuery

FLWOR

FOR LET

WHERE ORDER BY RETURN FLWOR SELECT FROM WHERE


ORDER BY SQL FLWOR expression XQuery
XQuery
for $x in db2-fn:xmlcolumn(PRODUCT.DESCRIPTION)
let $p := $x/product/description/name
where $x/product/description/price < 3
return <cheap_products> {$p} </cheap_products>

for ( $x)

$x XML DESCRIPTION PRODUCT


for $x XML XML
$p XQuery XML

$x 4 (sequence)
$p

where where SQL


3

return XDM instance


XQuery FLWOR

1. XQuery for $i in (1 to 3) return $i


OR
2. XQuery for $x in db2-fn:xmlcolumn(PRODUCT.DESCRIPTION)//text()
Execution Result

188

1
----1
2
3
text node
DESCRIPTION PRODUCT

XML

8.4.3 Joins XQuery


XQuery Join XML

XML XML Join


XQuery

for $book in db2-fn:xmlcolumn(BOOKS.DOC)/book


for $entry in db2-fn:xmlcolumn(REVIEWS.DOC)/entry
where $book/title = $entry/title
return <review>
{$entry/review/text()}
</review>;

join XML DOC BOOKS


REVIEWS DOC BOOKS
XML DOC REVIEWS
XQuery
(text nodes )
BOOKS REVIEWS
8.4.4 (User-defined functions)

XQuery

XQuery XQuery DB2


built-in functions XQuery
(sequence)
XQuery contains DB2 :
XQuery
declare default element namespace http://posample.org;
for $x in db2-fn:xmlcolumn(PRODUCT.DESCRIPTION)
let $p := $x/product/description/name
where $x/product/description/name/fn:contains(text(),Scraper)
return $p
Execution Result
:
1
---------------------------------------------------------------------

8 XML 189
<name>Ice Scraper, Windshield 4 inch</name>
1 record(s) selected.

8.4.5 XQuery XML Schema


XQuery XML Schema W3C, XML
schema XDM instance
DB2 built-in functions node XML Schema XQuery xs:double
XQuery
declare default element namespace http://posample.org;
for $x in db2-fn:xmlcolumn(PRODUCT.DESCRIPTION)
let $p := $x/product/description/name
where $x/product/description/xs:double(price) = 3.99
return $p

8.4.6 (Grouping and aggregation)


XQuery XML
XML XML
CUSTOMER
for XML info customer
element city $city city let $cust names element
city
XQuery
for $city in fn:distinct-values(db2-fn:xmlcolumn(CUSTOMER.INFO)
/customerinfo/addr/city)
let $cust-names := db2-fn:xmlcolumn(CUSTOMER.INFO)
/customerinfo/name[../addr/city = $city]
order by $city
return <city>{$city, $cust-names} </city>

Execution result :
1
<city>Aurora
<name>Robert Shoemaker</name>
</city>
<city>Markham
<name>Kathy Smith</name>
<name>Jim Noodle</name>

190

</city>
<city>Toronto
<name>Kathy Smith</name>
<name>Matt Foreman</name>
<name>Larry Menard</name>
</city>
(aggregation) XQuery
element PurchaseOrder 2005 element
$po for path expression $po/item/
element item element PurchaseOrder nested expression(price * quantity) item fn:sum
item let fn:sum
$revenue
order by

for $po in db2-fn:xmlcolumn(PURCHASEORDER.PORDER)/


PurchaseOrder[fn:starts-with(@OrderDate, 2005)]
let $revenue := sum($po/item/(price * quantity))
order by $revenue descending
return
<tr>
<td>{string($po/@PoNum)}</td>
<td>{string($po/@Status)}</td>
<td>{$revenue}</td>

</tr>

8.4.7 Quantification
Quantified expressions true false
(sequence)
some $i in (1 to 10) satisfies $i mod 7 eq 0
every $i in (1 to 5) , $j in (6, 10) satisfies $i < $j
Quntified expression quantifier some every quantifier
(sequence)
$i (1 to 10) $i $j
(1 to 5) (6 to 10) expression
expression
$i mod7 0
qualifier some
Quntified expression $i $j qualifier
every Quntified expression

8.5 XSLT
XSLT eXtensible Stylesheet Language Transformations
XSL XML XML

XML style sheets
HTML tag 8.7
XSLT

8 XML 191

XSL
Style
sheet 1
<dept bldg=101>
<employee id=901>
<name>John Doe</name>
<phone>408 555 1212</phone>
<office>344</office>
</employee>
</dept>

XSL
Style
sheet 2

<emp name=John Doe>


<empNo>=901</empNo>
<contact>
<phone>408 555 1212</phone>
<room>344</room>
</contact>
</emp>

John Doe;901;408 555 1212;344

XSL (FO)
Style
sheet 3

8.7 eXtensible Stylesheet Language (XML)


DB2 9.7 XSLT
1.

XML

2.

XSLT Stylesheet

XSLT style sheet XML (well-formed)


XML DB2 XSLT style sheet
<xsl:stylesheet version=1.0
xmlns:xsl=http://www.w3.org/1999/XSL/Transform>
<xsl:template match=/>
<html>
<body>
<h2>Product Details</h2>
<table border=1>
<tr >
<th>Name</th>
<th>Price</th>
</tr>
<xsl:for-each select=product/description>
<tr>
<td><xsl:value-of select=name/></td>
<td><xsl:value-of select=price/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
XML :

192

<products>
<product pid=100-201-01>
<description>
<name>Ice Scraper, Windshield 4 inch</name>
<details>Basic Ice Scraper 4 inches wide, foam handle</details>
<price>3.99</price>
</description>
</product>
</products>
DB2 9.7 XslTransform XML XSLT stylesheet
( XML )
SELECT XslTransform HTML document
.html
SELECT XSLTRANSFORM (description USING stylesheet AS CLOB (10M)) FROM
product where pid like 100-201-01
:
1
---------------------------------------------------------<html>
<body>
<h2>Product Details</h2>
<table border=1>
<tr>
<th>Name</th><th>Price</th>
</tr>
</table>
</body>
</html>
1 record(s) selected.

8.6 SQL/XML
SQL / XML XML SQL SQL/XML
ANSI / ISO SQL based extensions ()
XML XML
SQL
XML XML XML schema
XMLCONCAT XMLAGG XML XML
8.6.1 XML Document
SQL / XML XML XML
(parse) (serialize) XML (Publishing)
XML web service
( XML )
XML web service XML
XML
business intelligence XML

8 XML 193

8.6.2 XML
(Publishing) SQL / XML
XML XML

8.6.3 SQL / XML


SQL / XML
8.6.3.1 XMLELEMENT XMLATTRIBUTES
XMLELEMENT XMLATTRIBUTES
XMLELEMENT XML element
SELECT
Select XMLELEMENT(NAME firstname, firstnme) from employee
: 1
-------------------------------------------<FIRSTNAME>CHRISTINE</FIRSTNAME>
<FIRSTNAME>MICHAEL</FIRSTNAME>
<FIRSTNAME>SALLY</FIRSTNAME>
<FIRSTNAME>JOHN</FIRSTNAME>
<FIRSTNAME>IRVING</FIRSTNAME>
<FIRSTNAME>EVA</FIRSTNAME>
6 record(s) selected.
NAME XML element
XML element firstname
XMLATTRIBUTES SELECT
Select XMLELEMENT(NAME emp , XMLATTRIBUTES(EMPNO AS employee_num ))
from employee
:
1
------------------------------------------------------<EMP EMPLOYEE_NUM=000010/>
<EMP EMPLOYEE_NUM=000020/>
<EMP EMPLOYEE_NUM=000030/>
<EMP EMPLOYEE_NUM=000050/>
<EMP EMPLOYEE_NUM=000060/>
6 record(s) selected.
XMLATTRIBUTES 2
A AS B A (empno)
AS (employee_num) EMP
XML element (text value) XMLATTRIBUTES EMP XML element (NUM SALARY) element
element (FIRST LAST)

194

Select
XMLELEMENT(NAME emp ,
XMLATTRIBUTES(EMPNO AS NUM,SALARY as salary ),
XMLELEMENT(NAME first , firstnme),
XMLELEMENT(NAME last, lastname) )
from employee
:
1

-----------------------------------------------------------

<EMP NUM=000010 SALARY=152750.00><FIRST>CHRISTINE</


FIRST><LAST>HAAS</LAST></EMP>
<EMP NUM=000020 SALARY=94250.00><FIRST>MICHAEL</
FIRST><LAST>THOMPSON</LAST></EMP>
<EMP NUM=000030 SALARY=98250.00><FIRST>SALLY</
FIRST><LAST>KWAN</LAST></EMP>
<EMP NUM=000050 SALARY=80175.00><FIRST>JOHN</
FIRST><LAST>GEYER</LAST></EMP>
<EMP NUM=000060 SALARY=72250.00><FIRST>IRVING</
FIRST><LAST>STERN</LAST></EMP>

8.6.3.2 XMLQUERY
SQL / XML XQuery
XML XMLQUERY SQL
/ XML XMLQUERY XQueryexpression-constant (expression) XML SELECT
SELECT pid , XMLQUERY($DESCRIPTION/product/description/name
PRODUCTNAME FROM product

) AS

:
PID
PRODUCTNAME
-----------------------------------------------------------100-100-01 <name>Snow Shovel, Basic 22 inch</name>
100-101-01 <name>Snow Shovel, Deluxe 24 inch</name>
100-103-01 <name>Snow Shovel, Super Deluxe 26 inch</name>
100-201-01 <name>Ice Scraper, Windshield 4 inch</name>
4 record(s) selected.

DESCRIPTION XML
DESCRIPTION ( join )
PASSING
SELECT pid , XMLQUERY($D/product/description/name PASSING
prod.description as D ) AS PRODUCTNAME FROM product prod,
purchaseorder po
XML namespaces Query

8 XML 195

SELECT pid , XMLQUERY($DESCRIPTION/*:product/*:description/*:name


PRODUCTNAME

FROM product

) AS

:
PID
PRODUCTNAME
-------------------------------------------------------------------100-100-01 <name xmlns=http://posample.org>Snow Shovel, Basic 22 inch</
name>
100-101-01 <name xmlns=http://posample.org>Snow Shovel, Deluxe 24 inch</
name>
100-103-01 <name xmlns=http://posample.org>Snow Shovel, Super Deluxe 26
inch</name>
100-201-01 <name xmlns=http://posample.org>Ice Scraper, Windshield 4 inch</
name>
4 record(s) selected.
XMLQUERY XML sequence XML
predicate XMLEXISTS
XMLQUERY
SELECT PID 100-103-01
49.99
SELECT pid , XMLQUERY($DESCRIPTION/*:product/*:description/*:name ) AS
PRODUCTNAME FROM product
where
XMLEXISTS($DESCRIPTION/*:product[@pid=100-103-01]/*:description[*:pri
ce=49.99])
:
PID
PRODUCTNAME
-------------------------------------------------------------------100-103-01 <name xmlns=http://posample.org>Snow Shovel, Super Deluxe 26
inch</name>
1 record(s) selected.
XMLEXISTS XMLQUERY predicate
empty sequences XMLEXISTS (true false)
predicate XMLQUERY sequence XMLEXISTS empty sequence
SELECT predicate XMLEXISTS
SELECT predicate XQuery-expression-constant
XMLQUERY
SELECT pid , XMLQUERY(
$DESCRIPTION/*:product[@pid=100-103-01]/*:description[*:price=49.99]/*:n
ame)
AS PRODUCTNAME
FROM product

196

:
PID
PRODUCTNAME
----------------------------------------------------------------------100-100-01
100-101-01
100-103-01 <name xmlns=http://posample.org>Snow Shovel, Super Deluxe 26
inch</name>
100-201-01
4 record(s) selected.
3 empty sequences XMLQUERY sequence
sequence Predicate empty sequence Predicate XMLEXISTS XMLQUERY Predicate
8.6.3.3 XMLAGG

XMLAGG XML sequence null XML values


SELECT
SELECT
XMLELEMENT (NAME Department,
XMLATTRIBUTES (e.workdept AS name ),
XMLAGG ( XMLELEMENT (NAME emp, e.firstnme) )
) AS dept_list
FROM employee e
GROUP BY e.workdept;
:
dept_list
-------------------------------------------------------------------<Department name=A00>
<emp>CHRISTINE</emp>
<emp>VINCENZO</emp>
<emp>SEAN</emp>
<emp>GREG</emp>
</Department>
<Department name=B01>
<emp>MICHAEL</emp>
</Department>
<Department name=C01>
<emp>SALLY</emp>
<emp>DELORES</emp>
<emp>HEATHER</emp>
<emp>KIM</emp>
</Department>
<Department name=D21>
<emp>EVA</emp>
<emp>MARIA</emp>
</Department>
<Department name=E01>
<emp>JOHN</emp>
</Department>

8 XML 197

8.7 XML
XML SQL / XML
XQuery XML XML
SELECT SQL XMLQUERY SQL /
XML XQuery

XML XQuery XMLQUERY
SQL SELECT XML
SELECT SQL XMLQUERY

8.8 XML
XML
DB2
XML native storage
DB2 XML XMLPARSE XMLSERIALIZE
XML text native XML native XML XML text

8.8.1 XMLPARSE
XMLPARSE XML
XML native XML ( hierarchical
tree format) insert DB2 default XML implicit
XML explicit XMLPARSE
INSERT XML
XML XML well-formed insert XML

INSERT INTO PRODUCT(PID,DESCRIPTION) VALUES(100-345-01, XMLPARSE(


DOCUMENT <product xmlns=http://posample.org pid=100-100-01>
<description><name>Snow Shovel, Basic 22 inch</name>
<details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
<price>9.99</price>
<weight>1 kg</weight>
</description>
</product> ))
XMLPARSE whitespace default
DB2 element
PRESERVE WHITESPACE
INSERT INTO PRODUCT(PID,DESCRIPTION) VALUES(100-345-01, XMLPARSE(
DOCUMENT <product xmlns=http://posample.org pid=100-100-01>
<description><name>Snow Shovel, Basic 22 inch</name>
<details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</details>
<price>9.99</price>
<weight>1 kg</weight>
</description>
</product> PRESERVE WHITESPACE))

198

8.8.2 XMLSERIALIZE
XMLSERIALIZE XML (
) CHAR /
CLOB / BLOB XML
(text) XQuery XML
XML SELECT XML DESCRIPTION
CLOB PID 10010001
SELECT XMLSERIALIZE(DESCRIPTION AS CLOB(5K)) FROM PRODUCT WHERE PID LIKE
10010001
:
1
-----------------------------------------------------------------------<product xmlns=http://posample.org pid=100-100-01>
<description><name>Snow Shovel, Basic 22 inch</name>
<details>Basic Snow Shovel, 22 inches wide, straight handle with D-Grip</
details><price>9.99</price><weight>1 kg</weight>
</description>
</product>
1 record(s) selected.

8.8.3 TRANSFORM expression


TRANSFORM expression DB2 9.5 XML
XML TRANSFORM expression XQuery
XDM
(insert of a node)

(deletion of the node)



(identity)

(properties)


TRANSFORM expression XML cid=
1000 TRANSFORM expression element
Type Home
XML :
<customerinfo>
<name>John Smith</name>
<addr country=Canada>
<street>Fourth</street>
<city>Calgary</city>
<state>Alberta</state>
<zipcode>M1T 2A9</zipcode>
</addr>
<phone type=work>963-289-4136</phone>
</customerinfo>

8 XML 199

update TRANSFORMexpression :
update customer
set info = xmlquery( copy $new := $INFO
modify (

do replace value of $new/customerinfo/phone with 416-123-4567,

do replace value of $new/customerinfo/phone/@type with home )

return $new)
where cid = 1000;
XML :
<customerinfo>
<name>John Smith</name>
<addr country=Canada>
<street>Fourth</street>
<city>Calgary</city>
<state>Alberta</state>
<zipcode>M1T 2A9</zipcode>
</addr>
<phone type=work>963-289-4136</phone>
</customerinfo>

8.9
XML XML

(semi-structured) XML
IBM DB2
XML ( XML Native ) XML
2 XQuery SQL/XM
L DB2 XML schema
(validate) XML XML schema TRANSFORM DB2
XML

8.10
1. (cid) XML

insert XML XML


<customer id=C62>
<firstname>Pete</firstname>
<lastname>Bush</lastname>
<address>
<door>No 34</door>
<building>Galaxy Apartment</building>
<road>Meera road</road>

200

<city>Mumbai</city>
<zip>411202</zip>
</address>
</customer>
2. INSERT 5 XML XML
INSERT CID 10, 13, 15, 20, 23

3. SELECT XML
4. XQuery XML
5. XQuery XML XML cid 10 20

8.11
1. SQL / XML Publishing?
A. XMLELEMENT
B. XMLATTRIBUTE
C. XMLCONCAT
D. XMLPARSE
E.
2.
create table clients(
id
int primary key not null,
name
varchar(50),
status varchar(10),
contactinfo xml )
XML contactinfo
<customerinfo>

<name>Kathy Smith>

<addr country=Canada>


<city>Toronto</city>

<prov-state>Ontario</prov-state>

<zip>M5H-4C9</zip>

</addr>
</customerinfo>
<customerinfo>

<name>Amit Singh>

<addr country=Canada>

8 XML 201



<city>Markham</city>

<prov-state>Ontario</prov-state>

<zip>N9C-3T6</zip>

</addr>
</customerinfo>
Query ?
select xmlquery($c/customerinfo/addr/city[1]

passing info as c) \
from xmlcustomer \
where xmlexists($c/customerinfo/addr[prov-state=Ontario] \
passing xmlcustomer.info as c)
A. Toronto
Markham
B. <City>Toronto</City>
<City>Markham</City>
C. <City>Toronto
Markham</City>
D.
3. XML parsing
A.
(hierarchical format)

(relational

format)

B. XML (serialized string format)


C. XML
D. XML
E.
4. FLWOR
A. For, Lower, Where, Or, Run
B. From, Let, Where, Or, Reset
C. For, Let, Where, Order by, Reset
D. For, Let, Where, Order by, Return
5. XQuery SQL
A. XQuery Case sensitive SQL Case Sensitive
B. XQuery SQL Case Sensitive
C. SQL Case sensitive XQuery Case Sensitive
D.

202

E.
6. XQuery
xquery db2-fn:xmlcolumn(NNXML1.XMLCOL)/a/b
A. element b element element a XMLCOL
NNXML1
B. element a element root node b XMLCOL
NNXML1
C. element b element root node a XMLCOL
NNXML1
D. elementa XMLCOL NNXML1
7. XML DOC
Table description: CONTEST (DOC XML)
<dept bldg=111>
<employee id=901>
<name>Ajit Patil</name>
<phone>567 789 1342</phone>
<office>124</office>
</employee>
<employee id=922>
<name>Peter Jose</name>
<phone>121 768 3456</phone>
<office>213</office>
</employee>
</dept>
Query element <name>Peter Jose</name> ?
A. db2-fn:xmlcolumn(CONTEST.DOC)/dept/employee[@id=922]/name
B. select xmlquery($d/dept/employee[@id=922]/name passing DOC as d)
from contest
C. A B
D.
8. XQuery XQuery
xquery db2-fn:xmlcolumn(CONTEST.DOC)/dept/employee[@id=922]/name
A. xquery
db2-fn:xmlcolumn(CONTEST.DOC)
id=922]
B. xquery
name

db2-fn:xmlcolumn(CONTEST.DOC)

/dept/employee/name[../@
/dept/employee[../@id=922]/

C. xquery db2-fn:xmlcolumn(CONTEST.DOC) /dept/employee/name[@id=922]

203

D.
9. DB2 9.7 update XPath expression $new/
customer/phone phone element
update customer
set info =
xmlquery(copy $new := $information
modify do replace value of $new/customer/phone with 091-454-8654
return $new)
where cid = 67;
A. UPDATE
B. UPDATE phone element phone element
091-454-8654
C. UPDATE phone element phone element
091-454-8654
D.

9.1



9.1

9 205

Threats

Threats

Threats

9.1
:
(Privacy)

(Integrity)
(Availability)


(DBMS)

(Data Base Administrator: DBA)


DBA

206

9.1.1

















(secondary storage)

(backup)

9 207


(access control)
(view) (encryption) (integrity control)
(policy) (procedure)

9.1.2 (Access Control)


2
(Discretionary control) (Mandatory
control)
(access rights privileges)
A X Y B
Y X




(Hierarchy)



9.1.3
IBM DB2
DB2
(authentication) (authorization)
DB2
9.1.3.1 (Authentication)
DB2

DB2
Kerberos Lightweight Directory Access Protocol (LDAP)

208

DB2 authorization ID DB2 authorization ID (connect privilege)


9.1.3.2 (Authorization)

(grant
privilege)


procedure



(access control)

(DBMS)

(configuration files) DB2
authorization
ID (
Role)

( authorization ID)
(Group Role)
(Public Group) context-sensitive trusted context
role

DB2 implicit explicit explicit
role Grant implicit

DB2 3 (privilege)
Label-Based Access Control (LBAC) role

9.1.3.3 (Administrative Authority)


(hierarchy) SYSADM SYSADM


instance (privilege)

instance

(group) instance
instance (database manager configuration file)
DB2 instance 4
SYSADM (System administrator)
instance SYSADM
(migrate database) instance
transaction log
(Table Space) (Grant)
instance audit instance

SYSCTRL (System control)



Start/Stop instance

9 209

SYSMAINT (System maintenance)

instance

SYSMON (System monitor)

(Database authority) DB2


DBADM (Database administrator)


( DB2 version 9.7
DB2 9.7 DBADM DATAACCESS)
transaction log
(system catalog) log history files Reorganize

(runstats)

SECADM (Security administrator)


( Role LBAC labels)

CONNECT
BINDADD
CREATETAB
CREATE_EXTERNAL_ROUTINE

procedure

CREATE_NOT_FENCED_ROUTINE (User-Defined Function: UDF) procedure not fenced

IMPLICIT_SCHEMA schema CREATE SCHEMA schema SYSIBM


PUBLIC schema

9.1.3.4 (Priviledges)
(Priviledges) Role
9.2
DB2 [9.1]

210

CREATE NOT FENCED


BINDADD
CONNECT

Privileges

CREATETAB
CONTROL (Indexes)
IMPLICIT SCHEMA
CONTROL (Packages)
CONTROL (Tables)
CONTROL (IVoews)
Schema Owners

BIND
EXECUTE
ALL
ALTER
DELETE
INDEX
INSERT
REFERENCES
SELECT
UPDATE
ALL
DELETE
INSERT
SELECT
UPDATE
ALTERIN
CREATEIN
DROPIN

9.2 DB2

(Role) (PUBLIC)
PUBLIC PUBLIC
Public default CONNECT,
CREATETAB, BINDADD, IMPLICIT_SCHEMA, SELECT, UPDATE, EXECUTE, USE
CONTROL
9.1.3.5 Label Based Access Control
Label Based Access Control (LBAC)
mandatory access control (MAC) LBAC (row) (column) discretionary access control (DAC)
LBAC
(SECADM)
(security policy)


(security labels)

protected data
Grant

DB2

LBAC (system catalog)
LBAC SYSDBA, DBADM
SECADM

9 211

9.1.3.6 (Roles)


(Role)
(Role) (privilege)
(public)
GRANT (Developer role)
(insert) (update)




9.1.3.7 (Trusted Contexts)


3 (three-tiered application model)

2

(applications server authorization ID)

(end users)
3


(end users)
(applications server authorization ID)
(end users)
Trusted Contexts (trusted relationship) DB2
DB2
(system authorization) (IP address)
(data stream encryption)

Trusted Contexts

(trusted connection)
2 explicit implicit explicit
(
)
(privilege) trusted context implicit
(privilege)
trusted context
:
(A system authorization ID)

IP (A list of IP addresses)

(A data stream encryption)

212

9.1.4 (Views)



union (base table)

9.1.5 (Integrity Control)




trigger Procedure log file

(domain)
(User-defined data type) domain

domain constraint Check
constraint
Assertions constraint

Assertion
Assertions
Trigger
Trigger code
Trigger INSERT, UPDATE DELETE Trigger (event) (condition)
(action) Trigger

9.1.6


9.2

9.2.1

9 213

9.2.2









Mobile office




(GPS)

9.3

(access control)
(Discretionary control)
(Mandatory control)
DB2 (authentication) (authorization)
(privilege) (role) (LBAC) (trust context)
(view)

Check
constraint, Assertions Trigger


214

9.4
10 eBook Getting
started with DB2 Express-C 2

SYSCAT.TABLES ?

9.5
1.
2.
3.
4.
control)

(Discretionary

5. (Authorization) DB2
6. (Privileges)
7. (Trusted contexts) DB2
8.
9. (Integrity control)

10.

10 -

10

.. 2010 ..
2015
2,000

Cloud Computing

iPhone Android, Tablet PCs iPad


PlayBook,

Cloud Computing,

10.1 (Cloud computing) ?


(Cloud computing)

Cloud

Cloud computing , ,

10.1
Cloud computing

10 - 217

Cloud computing

120 2

10.1 - Cloud computing



Cloud computing


120
Cloud computing
2

3 25
2 5
5 3 Cloud computing
3 2 5

10.1.1 Cloud
Cloud computing 3 :

(Standardization)

(Virtualization)

(Automation)

Cloud
Cloud
Cloud Facebook, Yahoo, Gmail

10.1.2 Cloud computing


Cloud computing 3 :

(Infrastructure as a service: IaaS)


(Platform as a service: PaaS)

218

(Software as a service: SaaS)



IBM PaaS DB2, WebSphere Application Server

SaaS Salesforce.com

10.1.3 Cloud
Cloud Smart
Business Development and Test on the IBM Cloud, Amazon Amazon Web Services (AWS), Rackspace
10.1.3.1 IBM Smart Business Development and Test on the IBM Cloud
IBM Smart Business Development and Test on the IBM Cloud IBM developer cloud
Cloud
Intel 32- 64-
Linux RedHat SUSE Linux Microsoft Windows
IBM Developer Cloud https://www-147.ibm.com/cloud/enterprise 10.1 IBM Developer Cloud

10.1 The IBM Developer Cloud dashboard


Add instances
10.2

10 - 219

10.2 IBM Developer Cloud


IBM DB2 Express-C 9.7.1 PAYG (Pay as you go)
SUSE Linux Next
10.3
(32-, 64-)
(copper, bronze, silver, gold) bronze
32- 1 1.25 GHz, 2GB 175GB

10.3
SSH ssh
putty

220

10.3
Next
( DB2
Express-C )

10.1.3.2 Amazon
Amazon Web Services AWS Cloud AWS
:

IBM developer cloud AWS
Elastic Cloud compute (EC2) instances
Intel (32 64-) Windows Linux
10.4
AWS EC2 aws.amazon.com

10 - 221

Micro Instances
Micro Instance
32-bit or 64-bit
613MB of memory
2 ECUs

Standard Instances m1

Small Instance
Large Instance
32-bit,
64-bit,
1.7GB of memory
7.5GB of memory
1VC *1ECU = 1 ECU 2VC *2ECU = 4 ECUs

Extra Largel Instance


64-bit,
15GB of memory
4VC *2ECU = 8 ECUs

High-memory Instances m2

m2.xlarge
64-bit,
17.1GB of memory
2VC *3.25ECU = 6.5 ECUs

m2.2xlarge
64-bit,
34.2GB of memory
4VC *3.25ECU = 13 ECUs

High CPU Instances

Medium Instance
32-bit,
1.7GB of memory
2VC *2.5ECU = 5 ECUs

Extra Large Instance


64-bit,
7.5GB of memory
8VC *2.5ECU = 20 ECUs

m2.4xlarge
64-bit,
68.4GB of memory
8VC *3.25ECU = 26 ECUs

Cluster compute Instances


Cluster Compute Quadruple Extra Large
64-bit,
23GB of memory
33.5 EC2 Compute Units
10 Gigabit Ethernet

VC = Virtual core
ECU = EC2 Compute Unit. 1 ECU ~ CPU capacity of 1.0 - 1.2 GHz 2007 or 2007 Xeon processsor

10.4 AWS EC2


AWS

Instance storage -

Simple Storage Service (S3) - S3


http

Elastic Block Storage (EBS) - EBS


10.1.4 Cloud
Cloud

Cloud Cloud

IBM Cloudburst IBM WebSphere Cloudburst Appliance
Cloud
Amazon Cloud
Internet

hybrid clouds cloud


cloud

222

10.1.5 Cloud
Cloud
IBM DB2 Cloud
DB2 AWS IBM
developer cloud DB2 cloud VMware WebSphere Cloudburst appliance 10.5 DB2 (private cloud)
(hybrid cloud) (public cloud)

What does DB2 have to offer?


Private
Available Now:
DB2 WebSphere ClouBurst
Appliance images
DB2 VMWare images

Hybrid

Public

Developer Cloud
DB2 Enterprise Developer Edition
(pay)
DB2 Express-C (free)
Amazon:
DB2 AMIs
DB2 Templates on RightScale.com
Industry AMIs (include DB2)
DB2 Ubuntu AMIs by Canonical

10.5 DB2 Cloud Private, Hybrid, and Public


:

DB2 (BYOL) Cloud


Pay as you go (PAYG)

DB2 Express-C Cloud


Cloud
DB2 Cloud :

Database Partitioning Feature (DPF)

High Availability Disaster Recovery (HADR)


Compression
DPF
Cloud provisioning DPF
Business Intelligence Reports DPF

Cloud
DB2

HADR DB2 10 HADR



( ) HADR

10 - 223

(
) Cloud
Cloud

DR site Cloud
ssh HADR
Cloud Cloud
HADR 15
DB2
Cloud Cloud DB2

DB2

10.2


Cloud

Symbian, Microsoft Windows Mobile, Linux BlackBerry OS


Apples OS X iPhone, Android Palms Web OS
10.6

Mobile Applications
Mobile Application development platform
Mobile device platform
(Embedded OS, and mobile device)
10.6
10.6
Mobile device platform
Microsoft Windows Mobile 5.0
Dell AXIM X51v
Mobile application development platform
, APIs Mobile
application development platform Mobile device platform
Windows Mobile 6.0 Microsoft Visual Studio 2005/2008 Windows Mobile 6.0
SDK
Mobile device platforms mobile application development platforms
:

224

10.2.1
()
SDK

10.2 SDKs,
Operating System Language/OS op- SDKs/Tools
Developer Web Site
(OS)

tions

Symbian OS

C++, Java, Ruby,

Carbide C++,

Flash Lite, .NET

and Java SDKs, per

Java, C++

Visual Studio, Plat- Microsoft Windows Embedded

Windows Mobile

Python, Perl, OPL, IDE(Nokia) C++,

developer.symbian.com

device

form Builder, Em-

bedded Visual C++

Developer Center

(eVC), Free Pascal,


and Lazarus
iPhone OS

Objective-C

Xcode

www.apple.com/iphone

Android

Java

Eclipse, Android

www.android.com

SDK, Android Development Tool


Plugin, JDK 5

Palm OS

C, C++, Java

Palm OS SDK, Java www.palm.com/us/developer


development with
IBM Websphere

EveryPlace Micro

Environment, Palm
Windows Mobile

SDK for Palm products on Windows


Mobile platform

10.2 SDKs

10 - 225

10.2.2
?


Java, .NET (C#,
VB), C, C++


/
Java
Java Java

10.2.3

10.2.3.1 Windows Mobile


Windows Mobile Windows CE (.. 1996)
Microsoft Windows APIs

PDA Windows Mobile Pda
Motorola Q Treo

Microsoft ActiveSync
Microsoft Windows Mobile
C C++
.NET Compact Framework
10.2.3.2 Symbian OS
Symbian OS ,
, Symbian Ltd.
EPOC Release 5 EPOC Psion Symbian
C++ Symbians frameworks
Symbian Java ME
Symbian Symbian Java ME
10.2.3.3 iPhone
iPhone
Apple Inc. Safari

iPhone iPod Touch SDK Objective C C
Xcode
Max OS x Apple
10.2.3.4 Android
Android , ,

226

Android Java
Android Java Java
SDK , ,
( QEMU), ,
x86 Linux ( Linux ), Max
OS X 10.4.8 , Windows XP Vista Java
Development Kit, Apache Ant Python 2.2
Eclipse (3.2 ) Android Development Tools (ADT)
Java XML
, Android

10.2.4

10.2.4.1 Java Micro Edition (Java ME)


Java ME, Java 2 Micro Edition (J2ME)
Java
ME
C C++ API
Windows Mobile Symbian OS
10.2.4.2 .NET Compact Framework
.NET Framework Windows CE
.NET Framework

.NET Compact Framework V1.0, V2.0 V3.5


?
1.0
2.0 .NET Compact Framework
2.0
.NET Compact Framework Runtime
10.2.4.3 Native C++
C++ native

Native C++ Microsoft Visual C++6/.NET, Eclipse


C++ SDK, Borland C++ Builder Symbian
Metrowerks CodeWarrior Studio Symbian C++ SDK Nokia
10.2.4.4 Binary Runtime Environment
Binary Runtime Environment for Wireless (BREW)
Qualcomm CDMA BREW SDK
C C++
BREW BREW SDK, ARM ReslView Compilation Tools,
Visual C++

10.2.5
PDA

3G

10 - 227



Telematics, m-Commerce m-Enterprise, Mobile Multimedia Streaming, Mobile Messaging, Location
Based Mobile Computing

10.2.6 DB2
DB2 DB2 Everyplace DB2 Everyplace


:
Getting started with mobile application development,
DB2

10.3 (Business intelligence and appliances)

business intelligence


IBM Cognos


IBM Smart Analytics System
Business Intelligence
: business intelligence
Getting started with data warehousing, DB2

10.4 db2university.com: Cloud ()



db2university.com
10.7 db2university

228

10.7 db2university.com

10.4.1 Moodle



db2university.com Moodle (CMS)
Moodle PHP CMS
Martin Dougiamas Curtin University of Technology
Perth .. 2001
52,000 950,000 175
moodle.org
Moodle .. 2009 California
State University, Long Beach (CSULB)
Moodle 1.9.6 DB2 Express-C (
patch) http://moodle.org/mod/data/view.php?d=13&rid=3100&filter=1
.. 2010 Moodle 2.0 DB2 Express-C Moodle 2.0

Moodle 2.0 Release Candidate 1 DB2 Express-C
db2univertsity.com 2.0
db2university.com Moodle
10.8 db2university.com
Learn Learn
db2university

10 - 229

10.8 db2university.com
db2university.com DB2
PHP Ruby on Rails
DB2

:
Paypal Moodle
10.9 10.10 DB2 Essential Training I Moodle : ,
transcripts ( PDF )

10.9 DB2 Essential Training I

230

10.10 DB2 Essential Training I ()


IBM developerWorks db2university.com
:

Getting started with open source development DB2

10.4.2 openID

db2university.com openID
Facebook, Google, Yahoo, AOL, ChannelDB2
db2university
10.11

10 - 231

10.11 openID
Sign in with OpenID
ChannelDB2
/

db2university.
com
IBM developerWorks openID

10.4.3 Cloud Amazon


db2university.com Cloud Amazon
Cloud DB2 HADR
Cloud AWS :

EC2 standard large instance (64-, 4 , 7.5


GB, 850 GB)

EBS 50 GB
S3 buckets 3 1 GB
CloudFront
EC2 Moodle
DB2 (DB2 HADR )
DB2 HADR
S3 EBS 10.12

232

EBS
DB2 config

EBS
DB2 data
& Logs

10.12 DB2 Cloud Amazon


10.3

EBS DB2 DB2


50 GB RAID

EBS 2 GB DB2 DB2


DB2
S3

S3 EBS volume
snapshots S3

AWS CloudFront
edge
S3 bucket edge

Ubuntu Linux 10.04.1 LTS


DB2 Express 9.7.2 Linux 64-
Moodle 2.0 Release Candidate 1
PHP 5.3.3

DB2 Express DB2 Express-C HADR


DB2 DB2 Express
RightScale AWS RightScale

IBM developerWorks AWS
db2university

10 - 233

10.4.4 Android
Moodle
Android App Inventor
10.13
Moodle

App Inventor
( Web Service Ruby/Sinatra) IBM developerWorks

10.13 db2university App Inventor Android

234

10.5
.. 2015
Cloud



business intelligence

business
intelligence IBM Smart Analytics
db2university.com

235

1.

2. DBMS

3.

4. (Data Inpendence) (
)

5. (DBMS)

6. A. pureXML

7. C.
8. E.
9. D.

10. B. pureXML DB2 RDBMS

cloud Database Partitioning Feature (DPF) DB2 cloud

237

2
1.

2. Intersection:

R1 R2 = R1-(R1-R2).

Join: R1join_condition R2 = join_condition (R1X R2)


Division for relation R1(A,B)and R2(A):
R1 R2 = B (R1) - B ((R2X B (R1)) - R1)
3. Name(Address=New York AND Discount>0.05(R))
4. RANGE OF SUPPLIERS IS SUPPLIERS.Name WHERE (SUPPLIERS.Address =New York
AND SUPPLIERS.Discount>0.05)
5. NameX WHERE (DiscountX >0.05 AND SUPPLIERS (Name:NameX,
Discount:DiscountX, Address:New York)
6. A.
C. (data characteristic)
7. B.
C.
8. B. (instance)
D. (degree)
9. A.
10. D. Cascade

3
1. D.
2. A.
3. C.
4. A.
5. B.
6. D.
7. B.
8. D.
9. C.
10. B.

238

4
1. 4.6.1 Lossless Lossy Decompositions
2. C.
3. B.
4. E.
5. B.
6. C.

5
1. D.
2. D.
3. A, C.
4. D.
5. D.
6. A.
7. B.
8. D.
9. D.
10. B.

6
1. C.
2. C.
3. E.
4. C.
5. C.
6. D.
7. D.
8. D.
9. A.
10. A.

239

7
1. B.
2. A.
3. B.
4. A.
5. B.
6. B.
7. B.
8. A.
9. B.
10. B.

8
1. D.
2. B.
3. B.
4. D.
5. A.
6. A.
7. C.
8. A.
9. A.

9
1.

2. ,

:

3. :


4. Discretionary Control

5. DB2 3 :
Label-Based Access Control (LBAC)

240

6.

7. Trusted Context DB2



, Trusted Context

8.


9.

,
10.

241

DB2

DB2

DB2

:
DB2
DB2
DB2
DB2
DB2


DB2
:
DB2 (free e-book) Getting Started with DB2 Express-C

.1 DB2
DB2
DB2 XQuery SQL DB2

.1 DB2 Getting Started
with DB2 Express-C e-book.

DB2 243

DB2 Commands & SQL/XML,


XQuery Statements
SQL/XML Xquery
Statements

Command Line Tools

Command Editor
Command Line Processor
Command Window

create bufferpool
create tablespace
create table
alter buferpool
alter tablespace
alter table
select
insert
update
delete
...

General Administrator Tools


Control Center
Journal
License Center
Replication Center
Task Center

DB2 System Commands


db2set
db2tart
db2stop
db2list
db2icrt
db2idrop

Information

Information Center
Check for DB2 Updates

Monitoring Tools

...
DB2 CLP Commands
db2
update dbm cfg
catalog db

list node directory


create database
list applications

list tablespaces
...

<sql statement>
xquery<

DB2 Tools

>

Event Analyzer
Health Center
Indoubt Transaction
Manager
Memory Visualizer
Activity Monitor

Setup Tools

Configuration Assistant
Configure DB2 .Net Data
Provider
First Steps
Default DB2 Selection Wizard

DB2 Environment

Instance 'myinst'
Database Manager
Configuration

File (dbm cfg)


Database MYDB1
Database

Configuration

File (dbm cfg)

Port

Development Tools
IBM Data Studio
Optim Development Studio

.1 DB2
.1 DB2 SQL

DB2
.2 DB2
DB2 , DB2

DB2 DB2

.2.1 DB2
.2 DB2

244

DB2 Enterprise Edition


DB2 Express Edition

DB2 Express Edition

DB2 Express-C

Extra
functionality

Extra
functionality

Extra
functionality

.2 DB2
.2 DB2 DB2 Express-C DB2 DB2
DB2 Express-C DB2 Express DB2 Express
DB2 Workgroup .2 DB2
DB2 Express-C DB2 DB2
DB2 Express-C.
DB2 Express-C DB2

.2.2 DB2
DB2 DB2 DB2
IBM Data Server Client IBM Data Server Runtime
Client .3
IBM Data Server Client
IBM Data Server Runtime Client
Drivers & Network
Supprt

Gui Tools

Development Tools &


Library

.3 DB2
.3 IBM Data Server Runtime Client (
) DB2 IBM Data Server Client
IBM Data Server Runtime Client
GUI
DB2 :

DB2 245

DB2 Runtime Client Merge Modules for Windows: DB2 runtime client Windows
IBM Data Server Driver for JDBC and SQLJ: Java
DB2
IBM Data Server Driver for ODBC and CLI: ODBC CLI
DB2
IBM Data Server Driver Package: .NET
ODBC, CLI open source IBM Data Server Driver
ODBC, CLI NET
IBM DB2 DB2

.3 DB2
DB2 DB2

.3.1 Windows
DB2 Windows :
1. (user) (Administrator Group) DB2
2. unzip DB2 Express-C Windows ibm.com/db2/express
setup.exe
3.
4. :
DB2 C:\Program Files\IBM\SQLLIB
Windows DB2USERS DB2ADMNS
DB2 C:\Program Files\IBM\SQLLIB\DB2
DB2 Administration Server (DAS)
:

My Documents\DB2LOG\db2.log

My Documents\DB2LOG\db2wi.log

Windows Services

.3.2 DB2 Linux


DB2 Linux :
1. Root DB2
2. DB2 Express-C Linux ibm.com/db2/express
db2setup :
. / db2setup
3.
4. :

246

- DB2 /opt/ibm/db2/V9.7
- :

db2inst1 ()
db2fenc1 ( fenced )

dasusr1 ( DAS )

- :
db2iadm1

db2fadm1
dasadm1

- db2inst1
- dasusr1

- :
/tmp/db2setup.his

/tmp/db2setup.log
/tmp/db2setup.err

.4 DB2


DB2 DB2 Control Center, DB2 Command
Editor DB2 9.7
IBM Data Studio IBM Data Studio
DB2 Ebook Getting started with IBM Data
Studio for DB2

.4.1 Control Center


DB2 9.7 DB2 Control Center
.4 DB2

.4 DB2 Control Center

DB2 247


Control Center Windows start - > Programs - > IBM DB2
- > DB2COPY1(Default) - > General Administration Tools - > Control Center
db2cc Windows Command Prompt or Linux shell Control Center
:


DB2

( .5)

SAMPLE

.4.2 Command Line


Command Line :
DB2 Command Window ( Windows)
DB2 Command Line Processor (DB2 CLP)
DB2 Command Editor (GUI-based, )

.4.2.1 DB2 Command Window



DB2 Command Window Windows
Windows Command Prompt DB2 Command
Window Start -> Programs -> IBM DB2 -> DB2COPY1 (Default) -> Command Line
Tools -> Command Window db2cmd Windows Command Prompt
.5 DB2 Command Window

.5 DB2

248


DB2 Command Window
DB2 CLP DB2 Command Window
db2 :
db2 connect to sample

db2 select * from staff



Linux DB2 Command Window Linux shell ()
DB2 db2profile
.login DB2
db2inst1
.4.2.2 DB2 Command Line Processor

DB2 Command Line Processor (CLP) DB2 Command Window
db2 = >
DB2 Command Line Processor Windows Start -> Programs -> IBM DB2 -> DB2COPY1 (Default) -> Command Line Tools -> Command Line Processor DB2 Command
Window Linux shell db2 Enter db2 = > .6

.6 DB2 Command Line Processor (CLP)


.6 CLP
DB2 CLP quit
.4.2.3 DB2 Command Editor
DB2 Command Editor GUI DB2 Command Window DB2 Command Line
Processor .7 DB2 9.7

DB2 249

.7 DB2 Command Editor

.5 DB2

.8 DB2
DB2 Express-C Server
Environment Variables

Instance 'myinst'

Database Manager
Configuration

File (dbm cfg)


Database MYDB1
Database

Configuration

File (dbm cfg)


DB2 Profile
Registry

.8 DB2

Port

250


.8 DB2 Express-C
(Environment Variables, Database Manager Configuration File, Database Configuration File, DB2 Profile Registry ) DB2
myinst




.1
GUI DB2

db2start

db2stop

db2icrt <instance_name>

db2idrop <instance_name>

db2ilist

db2 get instance

.1 DB2


.8 MYDB1
myinst .2
/SQL

create database <database_name>

drop database <database_name>

connect to <database_name>

create table/create view/create


index

SQL

.2 SQL

.6 DB2


DB2 Configuration Advisor GUI
tool Control Center
Configuration Advisor

Configuration Advisor DB2


DB2
Configuration Advisor DB2
DB2 4 .8:
(Environment variables)
DB2INSTANCE
DB2
(Database Manager Configuration File

DB2 251

dbm cfg)
.3 dbm cfg

get dbm cfg

dbm cfg

update dbm cfg using <parameter_


name> <value>

dbm cfg

.3 dbm cfg
(Database Configuration File db cfg)

.4
db cfg

get db cfg for <database_name>

db cfg

update db cfg for <database_


name>
using <parameter_name> <value>

db cfg

.4 db cfg
DB2 (DB2 Profile Registry variables)
() (
) .5 DB2

db2set -all

DB2 profile
registry

db2set <parameter>=<value> DB2


.5 DB2

.7


()
(Catalog DB)
connect to database_name

Configuration Assistant GUI tool :

1. Configuration Assistant db2ca Windows command
prompt Linux shell .9 Configuration Assistant GUI tool

252

.9 Configuration Assistant GUI tool



2. Configuration Assistant Selected --> Add database

3.
DB2 Known systems

DB2 Other systems (Search the network)


4.
Manually configure a connection to a database TCP/IP
(IP Address) DB2 service name
.

5.

6.
Test Connection

.8



DB2

ftp://ftp.software.ibm.com/software/data/db2/udb/db2express/samples.zip
CLI
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0401chong/index.html#scenario1
ODBC
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0401chong/index.html#scenario2

DB2 253

C SQL
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0401chong/index.html#scenario3
JDBC Type 2 Universal (JCC)
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0401chong/index.html#scenario6
JDBC Type 4 Universal (JCC)
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0401chong/index.html#scenario8
Visual Basic c ++ ADO - IBM OLE DB provider DB2 (IBMDADB2)
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0402chong2/index.html#scenario1
Visual Basic c ++ ADO - Microsoft OLE DB Provider ODBC (MSDASQL)
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0402chong2/index.html#scenario2
Visual Basic C# ADO .NET IBM DB2 .NET Data Provider
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0402chong2/index.html#scenario3
Visual Basic C# ADO .NET Microsoft OLE DB .NET Data Provider
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0402chong2/index.html#scenario4
Visual Basic C# ADO .NET Microsoft ODBC .NET Data Provider
http://www.ibm.com/developerworks/db2/library/techarticle/dm-0402chong2/index.html#scenario5

.9 DB2


DB2 Information Center DB2
DB2 Information Center http://publib.boulder.ibm.com/infocenter/db2luw/
v9r7/index.jsp DB2 Information Center
http://www.ibm.com/software/data/db2/9/download.htmlS_TACT=download & S_CMP =
expcsite

1. DB2 Express-C
ibm.com/db2/express
DB2 Express-C. DB2 Express-C

2. IBM Data Studio


http://www-01.ibm.com/software/data/optim/data-studio/
IBM Data Studio, Eclipse-based tool
DB2
3. DB2 Express-C IBM Data Studio
http://www.ibm.com/db2/express/download.htmlS_CMP = ECDDWW01 & S_TACT =
DOCBOOK01
4. InfoSphere Data Architect

254

http://www-01.ibm.com/software/data/optim/data-architect/

Free ebook: Getting started with DB2 Express-C (3rd Edition)


Raul F. Chong et all - June 2009
http://www.db2university.com
Free ebook: Getting started with IBM Data Studio for DB2
Debra Eaton et all - Dec 2009
http://www.db2university.com
DB2 9 pureXML Guide
Whei-Jen Chen, Art Sammartino, Dobromir Goutev, Felicity Hendricks, Ippei Komi, MingPang Wei, Rav Ahuja
August 2007 - SG24-7315-01
http://www.redbooks.ibm.com/abstracts/sg247315.html
Free Redbook: DB2 Security and Compliance Solutions for Linux, UNIX, and Windows,
Whei-Jen Chen, Ivo Rytir, Paul Read, Rafat Odeh, March 2008, SG 24-7555-00
http://www.redbooks.ibm.com/abstracts/sg247555.html?Open

[1.1] CODD, E.F. A relational model of data for large shared data banks, CACM 13, NO
6, 1970
[2.1] DATE, C.J. An introduction to database systems, Addison-Wesley Publishing Company, 1986
[2.2] MITEA, A.C. Relational and object-oriented databases, Lucian Blaga University
Publishing Company, 2002
[2.3] CODD, E.F. Relational completeness on data base sublanguage, Data Base Systems, Courant Computer Science Symposia Series, Vol.6 Englewood Cliffs, N.J, PrenticeHall, 1972
[2.4] KUHNS, J.L. Answering questions by computer: A logical study, Report RM-5428PR, Rand Corporation, Santa Monica, California, 1967
[2.5] CODD, E.F. A data base sublanguage founded on the relational calculus, Proceedings ACM SIGFIDET Workshop on Data Description, Access and Control, 1971
[2.6] LACROIX, M., PIROTTE, A. Domain oriented relational languages, Proceedings 3rd
International Conference on Very Large Data Bases, 1977
[2.7]LACROIX, M., PIROTTE, A. Architecture and models in data base management systems, G.M. Nijssen Publishing company, North-Holland, 1977
[3.1] IBM Rational Data Architect Evaluation Guide
[3.2] Connolly, T., Begg, C., Strachan, A. Database Systems A Practical Approach
to Design, Implementation and Management, Addison Wesley Longman Limited 1995,
1998
[3.3] IBM InfoSphere Data Architect Information Center
[3.4] http://www.ibm.com/developerworks/data/bestpractices/
[3.5] 03_dev475_ex_workbook_main.pdf, IBM Rational Software, Section 1: Course
Registration Requirements, Copyright IBM Corp. 2004
[4.1] Codd, E. F. The Relational Model for Database Management
[4.2] Codd, E.F. Further Normalization of the Data Base Relational Model.
[4.3] Date, C. J. What First Normal Form Really Means
[4.4] Silberschatz, Korth, Sudershan - Database System Concepts
[4.5] William Kent - A Simple Guide to Five Normal Forms in Relational Database Theory
[4.6] Raghu Ramakrishnan, Johannes Gehrke - Database management systems
[4.7] Vincent, M.W. and B. Srinivasan. A Note on Relation Schemes Which Are in 3NF
But Not in BCNF.
[4.8] C. J Date : An Introduction to Database Systems 8th Edition

DB2 255

[4.9] William Kent: A simple guide to five normal forms in relational database theory
http://www.bkent.net/Doc/simple5.htm
[4.10] Ronald Fagin, C J Date: Simple conditions for guaranteeing higher normal forms
in relational databases
http://portal.acm.org/citation.cfm?id=132274
[4.11] Ronald Fagin: A Normal Form for Relational Databases That Is Based on Domains
and Keys
http://www.almaden.ibm.com/cs/people/fagin/tods81.pdf
[4.12] C. J. Date, Hugh Darwen, Nikos A. Lorentzos: Temporal data and the relational
model p172
[4.13] C J Date: Logic and databases, Appendix C
[5.1] Differences between SQL procedures and External procedures
http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db29.doc.
apsg/db2z_differencesqlprocexternalproc.htm
[5.2] SQL Reference Guide
http://www.ibm.com/developerworks/data/library/techarticle/0206sqlref/0206sqlr
ef.html
[6.1] http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/topic/com.ibm.db29.
doc.apsg/db2z_differencesqlprocexternalproc.htm

: DB2 Campus Program : db2univ@ca.ibm.com






SQL Procedure
DB2 pureXML XML





IBM DB2 DB2 Express-C DB2
SQL XML

:
ibm.com/developerworks/data/
DB2 Express-C :
ibm.com/db2/express
:
channelDB2.com
DB2 on Campus ebook db2university.
com

256


Rattasit Sukhahuta
8


rattasit.s@cmu.ac.th

8
( 2539 - )
( 2548
-)


Bachelor Degree in Computer Science
University of Hawaii at Hilo, Hawaii, USA, 1995

Master Degree in Information Systems
Hawaii Pacific University, Hawaii, USA, 1996

Doctor of Philosophy
University of East Anglia, Norwich, United Kingdom, 2001

257

Information Management

DB2 Express-C

DB2 C/C++, Java, .Net, PHP






DB2 Express-C 10.1

PureXML

XML

DB2 Express-C 10.1


www.ibm.com/software/data/db2/express

You might also like