04sql and advanced sql
TRANSCRIPT
-
8/6/2019 04SQL and Advanced SQL
1/133
IBM DB2 Universal Databases 8.1
SQL & Advanced SQL
Chapter - 4
1
-
8/6/2019 04SQL and Advanced SQL
2/133
IBM DB2 Universal Databases 8.1
SQL & Advanced SQL1. SQL
1. SQL Getting Started
2. Database Objects
3. Data Types, Constraints, Rules4. Data Definition Language
5. Data Manipulation Language
6. Indexes
7. Views
8. Identity Column
2. Advanced SQL1. User Defined Data Types
2. Sequences
3. Advanced Functions
2
-
8/6/2019 04SQL and Advanced SQL
3/133
IBM DB2 Universal Databases 8.1
SQL1. SQL Getting Started
2. Database Objects
3. Data Types
4. Data Definition Language, Constraints & Rules
5. Data Manipulation Language
6. Indexes
7. Views
8. Identity Columns
3
-
8/6/2019 04SQL and Advanced SQL
4/133
Standard language of relational database access is SQL(Structured Query Language).
Designed for accessing tabular data.
Three major categories..
DDL (Data Definition Language) - Used to create, modify, or drop database
objects
DML (Data Manipulation Language) - Used to select, insert, update, or delete
database data (records)
DCL (Data Control Language) - Used to provide data object access control
What is SQL ?
4
-
8/6/2019 04SQL and Advanced SQL
5/133
Data Types
Each column in DB2 table must be associated with a data type.The data type indicates kind of data that is valid for column.
There are two major categories of data types in DB2...
Built-in data types
User-defined data types
5
-
8/6/2019 04SQL and Advanced SQL
6/133
User-Defined Data Types
User-defined distinct type:To create a new data type that has its own semantics based on existing built-in
data types.
User-defined structured type:
To create a structure that contains sequence of named attributes each of which
has a data type.
Is an extension of DB2 Object Relational functions
User-defined reference type:
Is a companion type to a user-defined structured type
Is a scalar type that shares a common representation with one of the built-in
data types.
May be used to reference rows in another table that uses a user-defined
structured type.
6
-
8/6/2019 04SQL and Advanced SQL
7/133
IBM DB2 Universal Databases 8.1
SQL1. SQL Getting Started
2. Database Objects
3. Data Types
4. Data Definition Language, Constraints & Rules
5. Data Manipulation Language
6. Indexes
7. Views
8. Identity Columns
7
-
8/6/2019 04SQL and Advanced SQL
8/133
Tables
Is an unordered set of rows.Rows consist of columns.
Each column is based on a data type.
There are three types of tables:
Permanent (base) tables
Temporary (declared) tables
Temporary (derived) tables
8
-
8/6/2019 04SQL and Advanced SQL
9/133
Schema
Schemas are database objects used in DB2 to logically group otherdatabase objects.
Most database objects are named using a two-part naming
convention (SCHEMA_NAME.OBJECT_NAME ).
When an object is created without specifying a schema, object will
be associated with an implicit schema using the authorization ID.
When an object is referenced in an SQL statement, it is also
implicitly qualified with authorization ID of issuer (dynamic
SQL) if no schema name is specified in SQL statement.
9
-
8/6/2019 04SQL and Advanced SQL
10/133
The CURRENT SCHEMA special register contains defaultqualifier to be used for unqualified objects referenced for dynamic
SQL statements issued from within a specific DB2 connection.
Value can be modified by user with SET CURRENT SCHEMA
statement.
Can use the QUALIFIER option of BIND command to define
default qualifier at bind time.
NOTE: for temporary tables 'session' qualifier is used
Schema
10
-
8/6/2019 04SQL and Advanced SQL
11/133
Tablespaces
Logical layers between database and tables stored in that database.
Table spaces are created within a database, and tables are created
within table spaces.
DB2 supports two kinds of table spaces:
System Managed Space (SMS)
Database Managed Space (DMS)
11
-
8/6/2019 04SQL and Advanced SQL
12/133
Views
Virtual tables derived from one or more tables or viewsCan be used interchangeably with tables when retrieving data.
When changes are made to data through a view, the data is
changed in underlying table itself.
Views do not contain real data.
Created to limit access to sensitive data while allowing more
general access to other data.
Can be deletable, updatable, insertable, and read-only.
12
-
8/6/2019 04SQL and Advanced SQL
13/133
-
8/6/2019 04SQL and Advanced SQL
14/133
Can be created on computed columns ...So that optimizer can save computation time by using index instead of doing
calculations.
Indexes are maintained automatically by DB2 as data is inserted,
updated, and deleted.
Indexes
14
-
8/6/2019 04SQL and Advanced SQL
15/133
Indexes
Can be defined ...
In ascending or descending order,
Is unique or nonunique, and
On a single column or multiple columns,
To support both forward and reverse scans.
15
-
8/6/2019 04SQL and Advanced SQL
16/133
Buffer Pools
Are database objects used to cache data pages in memory.
Once a data page is placed in a buffer pool, physical I/O access to
disk can be avoided.
Buffer pools can be assigned to cache only a particular table space,
if required.
Every database will have atleast one bufferpool
16
-
8/6/2019 04SQL and Advanced SQL
17/133
Transactions
Is a sequence of SQL statements that execute as a single operation.
Term 'unit of work' is synonymous with the term 'transaction'.
Starts implicitly with first executable SQL statement in a program.
Ends when either an explicit or implicit COMMIT or ROLLBACK
statement is encountered.
SAVEPOINTs are like the bookmarks in a transaction, used to
control the scope of ROLLBACK statement. SAVEPOINT does
not end the current transaction.
17
-
8/6/2019 04SQL and Advanced SQL
18/133
IBM DB2 Universal Databases 8.1
SQL1. SQL Getting Started
2. Database Objects
3. Data Types
4. Data Definition Language, Constraints & Rules
5. Data Manipulation Language
6. Indexes
7. Views
8. Identity Columns
18
-
8/6/2019 04SQL and Advanced SQL
19/133
Data Types
Categories of DB2 supplied datatypes:Numeric
String (Binary, Single Byte, Double Byte)
Datetime
19
-
8/6/2019 04SQL and Advanced SQL
20/133
Numeric Data Types
DB2 data types that can be used to store numeric data are:
SMALLINT
INTEGER
BIGINT
DECIMAL/NUMERIC
REAL
DOUBLE
20
-
8/6/2019 04SQL and Advanced SQL
21/133
Small Integer (SMALLINT)
Uses least amount of storage in database for each value.
Data value range for a SMALLINT is -32768 to 32767.
Precision for a SMALLINT is 5 digits (to the left of the
decimal).
Two bytes of database storage are used for each
SMALLINT column value.
Numeric Data Types
21
-
8/6/2019 04SQL and Advanced SQL
22/133
Integer (INTEGER)
Takes twice as much storage as a SMALLINT but has a
greater range of possible values.
Range value for INTEGER data type is -2,147,483,648 to
2,147,483,647 .
Precision for INTEGER is 10 digits to the left of the
decimal.
Four bytes of database storage are used for each
INTEGER column value.
Numeric Data Types
22
-
8/6/2019 04SQL and Advanced SQL
23/133
Big Integer (BIGINT)
Is available for supporting 64-bit integers.
Range is -9,223,372,036,854,775,808 to
+9,223,372,036,854,775,807 .
Eight bytes of database storage are used for each BIGINT
column value.
NOTE:As platforms include native support for 64 bit integers, processing of large
numbers with BIGINT is more efficient than processing with DECIMAL and
more precise than DOUBLE or REAL .
Numeric Data Types
23
-
8/6/2019 04SQL and Advanced SQL
24/133
Decimal (DECIMAL/NUMERIC)
Is used for numbers with fractional and whole parts.
DECIMAL data is stored in a packed format.
Precision and scale must be provided
NOTE:
The precision is the total number of digits (range from 1 to 31), and the scale is
the
Number of digits in the fractional part of the number.
Numeric Data Types
24
-
8/6/2019 04SQL and Advanced SQL
25/133
Decimal (DECIMAL/NUMERIC):
Terms NUMERIC,NUM,DECIMAL, and DEC can all be
used to declare a decimal/numeric column.
If a decimal data type is to be used in a C program, host
variable must be declared as a double.
NOTE:
A DECIMAL number takes up p/2 + 1 bytes of storage, where p is the
precision used.
For example, DEC(8,2) would take up 5 bytes of storage (8/2 + 1), whereasDEC(7,2) would take up only 4 bytes (truncate the division of p/2).
Numeric Data Types
25
-
8/6/2019 04SQL and Advanced SQL
26/133
Single-Precision Floating-Point (REAL/FLOAT):A REAL data type is an approximation of a number.
Approximation requires 32 bits / 4 bytes of storage.
To specify single-precision number using REAL
datatype,its length must be defined between 1 and 24
Double-Precision Floating-Point (DOUBLE/FLOAT)
DOUBLE/ FLOAT data type is an approximation of a
number.
Approximation requires 64 bits or 8 bytes of storage.
To specify double-precision number using FLOAT data
type, its length must be defined between 25 and 53.
Note:
Exponential notation is used to represent REAL ,DOUBLE, and FLOAT data
values.
Numeric Data Types
26
-
8/6/2019 04SQL and Advanced SQL
27/133
String Data Types
Fixed-Length Character String (CHAR)Strings are stored in database using entire defined amount
of storage.
Length of a fixed-length string must be between 1 and 254
characters.
If value for length is not specified, a value of 1 is
assumed.
27
-
8/6/2019 04SQL and Advanced SQL
28/133
Varying-Length Character String (VARCHAR)Strings are stored using only amount of space required to
store data.
Term CHAR VARYING or CHARACTER VARYING
can be used
Maximum length of VARCHAR column is 32,672 bytes.
String Data Types
28
-
8/6/2019 04SQL and Advanced SQL
29/133
Varying-Length Long Character Strings (LONG VARCHAR) :
Used to store character data with a varying length.
Maximum length of a LONG VARCHAR column is
32,700.
Notes:
LONG VARCHAR data types are similar to CLOB data types.
The FOR BIT DATA clause can be used following character string column
definition. During data exchange, data is treated and compared as binary (bit)
data.
String Data Types
29
-
8/6/2019 04SQL and Advanced SQL
30/133
Character Large Object (CLOB)
Are varying-length SBCS (single-byte character set) or
MBCS (multibyte character set) character strings.
Used to store greater than 32KB of text.
Maximum size for each CLOB column is 2GB
(gigabytes).
String Data Types
30
-
8/6/2019 04SQL and Advanced SQL
31/133
Double-Byte Character Strings (GRAPHIC):GRAPHIC data types represent a single character using 2
bytes of storage.
The GRAPHIC data types include:
GRAPHIC (fixed length - maximum 127 characters)
VARGRAPHIC (varying length - maximum 16336
characters)
LONG VARGRAPHIC (varying length - maximum
16350 characters).
String Data Types
31
-
8/6/2019 04SQL and Advanced SQL
32/133
Double-Byte Character Large Objects (DBCLOB)
Are varying-length character strings
Are stored using 2 bytes to represent each character.
Are used for large amounts (>32KB) of double-byte text
data such as Japanese text.
String Data Types
32
-
8/6/2019 04SQL and Advanced SQL
33/133
Binary Large Object (BLOB)
Are variable-length binary strings.
Data is stored in a binary format .
Is useful for storing nontraditional relational database
information (audio, video).
Maximum size of each BLOB column is 2GB (gigabytes).
Binary Data Type
33
-
8/6/2019 04SQL and Advanced SQL
34/133
Date and Time Data Types
DATE :
Is stored internally as a (packed) string of 4 bytes.
Externally, string has a length of 10 bytes
(MM-DD-YYYY - can vary and is dependent on country
code).
TIME :
Is stored internally as a (packed) string of 3 bytes.
Externally, string has a length of 8 bytes (HH-MM-SS -
this representation may vary).
TIMESTAMP :
Is stored internally as a (packed) string of 10 bytes.
Externally, string has a length of 26 bytes
(YYYY-MM-DD-HH-MM-SS-NNNNNN ).
34
-
8/6/2019 04SQL and Advanced SQL
35/133
External File Data Types (DATALINK)
Is an encapsulated value
Contains a logical reference from database to a file stored in
a Data Links Manager Server, which is outside database.
35
-
8/6/2019 04SQL and Advanced SQL
36/133
IBM DB2 Universal Databases 8.1
SQL1. SQL Getting Started
2. Database Objects
3. Data Types
4. Data Definition Language, Constraints & Rules5. Data Manipulation Language
6. Indexes
7. Views
8. Identity Columns
36
-
8/6/2019 04SQL and Advanced SQL
37/133
Managing Database Objects - DDL
To create, modify, delete objects in a database, SQL Data
Definition Language (DDL) is used.
DDL has four basic SQL statements:
CREATE
ALTERDROP
DECLARE
37
-
8/6/2019 04SQL and Advanced SQL
38/133
CREATE Statement
Table
Index
Schema
View
User-defined function
User-defined data type
Buffer pool
Stored procedures
Trigger
Alias
Method
Transform
Nickname
Sequence
Table space
38
-
8/6/2019 04SQL and Advanced SQL
39/133
DECLARE Statement
It is used to create temporary tables that are used only during a
session.
The only object that can be DECLARED is a table
DECLARE GLOBAL TEMPORARY TABLE T1 LIKETRANSACTIONS ON COMMIT PRESERVE ROWS NOT
LOGGED IN SESSIONTEMP;
Note:
'LIKE' clause defines a table with same column names, data types andnullability characteristics of each of the columns of specified table.
39
-
8/6/2019 04SQL and Advanced SQL
40/133
DROP Statement
To delete objects from database.
Can drop any object created with CREATE and
DECLARE statements.
40
-
8/6/2019 04SQL and Advanced SQL
41/133
ALTER Statement
Table
Table space
Database partition
Procedure
Function
Nickname
Sequence
Type
View
Method
User mapping
Buffer pool
41
-
8/6/2019 04SQL and Advanced SQL
42/133
Index can not be altered.
It has to be dropped and re-created.
Every time a DDL statement (except for DECLARE statement) is
issued, catalog is updated.
Update includes a creation or modification timestamp and authorization ID ofthe user issuing the statement.
Important...
42
-
8/6/2019 04SQL and Advanced SQL
43/133
Constraints
Three types of constraints:
Unique constraint
Ensures unique values of a key in a table.
Referential integrity
Enforces referential constraints on insert, update, delete
operations.
Are imparted using insert rules, delete rules and update
rules.
Table check constraint
Verifies that changed data does not violate conditions
specified when a table was created or altered.
43
-
8/6/2019 04SQL and Advanced SQL
44/133
INSERT rule is implicit when a foreign key is specified.
A row can be inserted at any time into a parent table without
any action being taken in dependent table.
A row cannot be inserted into dependent table unless there is
a row in parent table with a parent key value equal to foreign
key value of row being inserted, unless foreign key value is
null.
If an INSERT operation fails for one row during an attempt
to insert more than one row, all rows inserted by the
statement are removed from the database.
INSERT Rules
44
-
8/6/2019 04SQL and Advanced SQL
45/133
DELETE Rules
RESTRICT
Prevents any row in parent table from being deleted if any
dependent rows are found.
NO ACTION
Enforces the presence of a parent row for every child after
all the referential constraints are applied.
This is the default.
The difference between NO ACTION and RESTRICT is
based on when constraint is enforced.
45
-
8/6/2019 04SQL and Advanced SQL
46/133
DELETE Rules
CASCADE
Implies that deleting a row in parent table automatically
deletes any related rows in dependent table.
SET NULL
Ensures that deletion of a row in parent table sets values
of foreign key in any dependent row to null (if nullable).
Other parts of row are unchanged.
46
-
8/6/2019 04SQL and Advanced SQL
47/133
UPDATE Rules
RESTRICT
Update for parent key will be rejected if a row in
dependent table matches original values of key.
NO ACTION
Update operation for parent key will be rejected if any
row in dependent table does not have a corresponding
parent key when update statement is completed .
This is the default.
47
-
8/6/2019 04SQL and Advanced SQL
48/133
Table-Check Constraint
Will enforce data integrity at table level.
Once defined for a table, every UPDATE, INSERT statement
will involve checking the constraint.
If constraint is violated, row will not be inserted or updated.
Can be defined at table creation time or later using ALTER
TABLE statement.
48
-
8/6/2019 04SQL and Advanced SQL
49/133
Adding Table-Check Constraint
When a check constraint is added to a table that contains
data, following can happen:
All rows meet check constraint...
Check constraint will be created successfully.
Some or all rows do not meet check constraint...
Check constraint will not be created
ALTER TABLE EMPLOYEE ADD CONSTRAINT
check_job CHECK (JOB IN ('Engineer','Sales','Manager'));
49
-
8/6/2019 04SQL and Advanced SQL
50/133
Create Table Statement
CREATE TABLE Department (Deptnumb SMALLINT NOT
NULL, Deptname VARCHAR(20), Mgrno
SMALLINT,PRIMARY KEY(Deptnumb) )
CREATE TABLE Employee (Id SMALLINT NOT NULL,Name
VARCHAR(9) NOT NULL, Dept SMALLINT,Job CHAR(5) CHECK (Job IN ('Sales','Mgr','Clerk')),
Hiredate DATE WITH DEFAULT CURRENT DATE,
Salary DECIMAL(7,2), Comm DECIMAL(7,2),
CONSTRAINT UNIQUEID PRIMARY KEY(Id),
FOREIGN KEY(Dept) references DEPARTMENT(Deptnumb)ON DELETE RESTRICT) IN HUMRES INDEX IN
HUMRES_IDX NOT LOGGED INITIALLY
50
-
8/6/2019 04SQL and Advanced SQL
51/133
Alter Table Statement
Adding one or more columns to a table
Adding or dropping a primary key
Adding or dropping one or more unique or referential constraints
Adding or dropping one or more check constraint definitions
Altering the length of a VARCHAR column
Altering a reference type column to add a scope
Altering or dropping a partitioning key
Changing table attributes such as the DATA CAPTURE ,
PCTFREE , LOCKSIZE , or APPEND mode option
Activating the not logged initially attribute of the table
51
-
8/6/2019 04SQL and Advanced SQL
52/133
Alter Table Statement
ALTER TABLE Employee ACTIVATE NOT LOGGED
INITIALLY LOCKSIZE TABLE APPEND ON VOLATILE
LOCKSIZE : indicates the granularity of locks
APPEND ON : indicates whether data is appended to end of atable or inserted where free space is available.
VOLATILE : indicates to optimizer that cardinality of table can
vary significantly at run time, from empty to quite large.
52
-
8/6/2019 04SQL and Advanced SQL
53/133
IBM DB2 Universal Databases 8.1
SQL1. SQL Getting Started
2. Database Objects
3. Data Types
4. Data Definition Language, Constraints & Rules5. Data Manipulation Language
6. Indexes
7. Views
8. Identity Columns
53
-
8/6/2019 04SQL and Advanced SQL
54/133
Data Manipulation Language
Retrieving Data
Inserting Data
Updating Data
Deleting Data
54
-
8/6/2019 04SQL and Advanced SQL
55/133
Retrieving Data
SELECT * FROM EMPLOYEE
SELECT EMPNO, FNAME, LNAME FROM EMPLOYEE
ORDER BY FNAME
SELECT EMPNO, FNAME, LNAME FROM EMPLOYEEWHERE EMPNO = 150
SELECT * FROM EMPLOYEE FETCH FIRST 5 ROWS ONLY
SELECT EMPNO, FNAME, LNAME FROM EMPLOYEE
WHERE MIN(SALARY) < 1000
55
R i i D F M Th O T bl
-
8/6/2019 04SQL and Advanced SQL
56/133
Retrieving Data From More Than One Tables -Joins
Process of combining data from two or more tables is achieved
using joins.
Database manager forms all combination of rows from specified
tables.
For each combination it checks the join condition.
Data types of the columns invloved in the join condition do not
have to be identical but they have to be compatible.
56
-
8/6/2019 04SQL and Advanced SQL
57/133
SAMP_PROJECT Table
NAME PROJ
Haas AD3100
Thompson PL2100
Walker MA2112
Lutz MA2111
57
-
8/6/2019 04SQL and Advanced SQL
58/133
SAMP_STAFF Table
NAME JOB
Hass PRES
Thompson MANAGER
Lucchessi SALESREP
Nicholls ANALYST
58
-
8/6/2019 04SQL and Advanced SQL
59/133
SELECT SAMP_PROJECT.NAME, SAMP_PROJECT.PROJ,
SAMP_STAFF.NAME, SAMP_STAFF.JOB FROM
SAMP_PROJECT, SAMP_STAFF
Query With-Out Join Condition
59
-
8/6/2019 04SQL and Advanced SQL
60/133
NAME PROJ NAME JOB
---------- ------ ---------- --------
Haas AD3100 Haas PRES
Thompson PL2100 Haas PRES
Walker MA2112 Haas PRES
Lutz MA2111 Haas PRES
Haas AD3100 Thompson MANAGERThompson PL2100 Thompson MANAGER
Walker MA2112 Thompson MANAGER
Lutz MA2111 Thompson MANAGER
Haas AD3100 Lucchessi SALESREP
Thompson PL2100 Lucchessi SALESREPWalker MA2112 Lucchessi SALESREP
Lutz MA2111 Lucchessi SALESREP
Haas AD3100 Nicholls ANALYST
Thompson PL2100 Nicholls ANALYST
Walker MA2112 Nicholls ANALYST
Lutz MA2111 Nicholls ANALYST
Cartesian / Cross Product
60
-
8/6/2019 04SQL and Advanced SQL
61/133
Main Types of Joins
Inner Join:
Keeps only the rows from the cross product that meet the join condition.If a
row exists in one table, but not the other, the information is not included in the
result table.
Outer Join:
Are a concatenation of the inner join and rows from the left table, right table,
or both tables that are missing from the inner join.
NOTE:
When you perform an outer join on two tables, you arbitrarily assign one table
as the left table and the other one as the right table.
61
-
8/6/2019 04SQL and Advanced SQL
62/133
Types of Outer Joins
Left outer join
Includes the inner join and the rows from the left table that are not included in
the inner join.
Right outer join
Includes the inner join and the rows from the right table that are not included
in the inner join.
Full outer joinIncludes the inner join and the rows from both the left and right tables that are
not included in the inner join.
62
-
8/6/2019 04SQL and Advanced SQL
63/133
Example of Inner Join
The inner join lists full-time employees who are assigned to project :
SELECT SAMP_PROJECT.NAME,
SAMP_PROJECT.PROJ, SAMP_STAFF.NAME, SAMP_STAFF.JOB
FROM SAMP_PROJECT, SAMP_STAFF
WHERE SAMP_STAFF.NAME = SAMP_PROJECT.NAME
OR
SELECT SAMP_PROJECT.NAME,
SAMP_PROJECT.PROJ, SAMP_STAFF.NAME,SAMP_STAFF.JOB
FROM SAMP_PROJECT INNER JOIN SAMP_STAFF
ONSAMP_STAFF.NAME = SAMP_PROJECT.NAME
63
-
8/6/2019 04SQL and Advanced SQL
64/133
Result of Inner Join Query
The result :
NAME PROJ NAME JOB
---------- ------ ---------- --------
Haas AD3100 Haas PRES
Thompson PL2100 Thompson MANAGER
64
-
8/6/2019 04SQL and Advanced SQL
65/133
Left Outer Join
SELECT SAMP_PROJECT.NAME, SAMP_PROJECT.PROJ,
SAMP_STAFF.NAME, SAMP_STAFF.JOB
FROM SAMP_PROJECT LEFT OUTER JOIN SAMP_STAFF
ON SAMP_PROJECT.NAME = SAMP_STAFF.NAME
The result:
NAME PROJ NAME JOB
---------- -------------------- ---------- --------------------
Haas AD3100 Haas PRESLutz MA2111 - -
Thompson PL2100 Thompson MANAGER
Walker MA2112 - -
65
-
8/6/2019 04SQL and Advanced SQL
66/133
Right Outer Join
SELECT SAMP_PROJECT.NAME,
SAMP_PROJECT.PROJ, SAMP_STAFF.NAME,
SAMP_STAFF.JOB
FROM SAMP_PROJECT RIGHT OUTER JOIN SAMP_STAFF
ON SAMP_PROJECT.NAME = SAMP_STAFF.NAME
The result :
NAME PROJ NAME JOB
---------- -------------------- ---------- --------------------
Haas AD3100 Haas PRES
- - Lucchessi SALESREP
- - Nicholls ANALYST
Thompson PL2100 Thompson MANAGER
66
-
8/6/2019 04SQL and Advanced SQL
67/133
Full Outer Join
SELECT SAMP_PROJECT.NAME, SAMP_PROJECT.PROJ,
SAMP_STAFF.NAME, SAMP_STAFF.JOB
FROM SAMP_PROJECT FULL OUTER JOIN SAMP_STAFF
ON SAMP_STAFF.NAME = SAMP_PROJECT.NAME
The result :
NAME PROJ NAME JOB
---------- -------------------- ---------- --------------------
Haas AD3100 Haas PRES
- - Lucchessi SALESREP
- - Nicholls ANALYSTThompson PL2100 Thompson MANAGER
Lutz MA2111 - -
Walker MA2112 - -
67
-
8/6/2019 04SQL and Advanced SQL
68/133
Retrieving Data using - DB2 Functions
Scalar functions
Also known as row functions
Provide a result for each row of the result table. A scalar function can be used
any place an expression is allowed.
Column functions
Also known as vector functions.
Work on a group of rows to provide a result.
The group is specified using a fullselect and optionally grouped using GROUP
BY clause.
68
-
8/6/2019 04SQL and Advanced SQL
69/133
Retrieving Data using - DB2 Functions
Scalar Functions:
SELECT lname, SUBSTR(CHAR(wphone),1,3) FROM db2cert.candidate
SELECT fname, MONTHNAME(date_taken) FROM candidate c, test_taken
tt WHERE c.cid=tt.cid
SELECT empno, sal FROMemployee WHERE UCASE(firstnme) = 'BILL'
Column Functions:SELECT MAX(smallint(length)) FROM test
SELECT AVG(noseats) FROM test_center
SELECT country, AVG(noseats) FROM test_center GROUP BY country
69
-
8/6/2019 04SQL and Advanced SQL
70/133
Searching for String Patterns
SELECT fname,lname,wphone,hphone FROM candidate WHERE
fname LIKE 'G%' ORDER BY lname, fname
SELECT fname,lname,wphone,hphone FROM candidate WHERE
fname LIKE '_a%' ORDER BY lname,fname
70
-
8/6/2019 04SQL and Advanced SQL
71/133
Searching for Data in Ranges
SELECT DISTINCT fname,lname,wphone,hphone FROM
candidate c, test_taken tt WHERE c.cid=tt.cid AND integer
(score) BETWEEN 60 AND 75
SELECT DISTINCT fname,lname,wphone,hphone FROM
candidate c, test_taken tt WHERE c.cid=tt.cid AND integer(score)
BETWEEN 60 AND 75 AND lname BETWEEN 'B' AND 'G'
71
-
8/6/2019 04SQL and Advanced SQL
72/133
Searching for NULLs
SELECT fname,lname,wphone,hphone FROM candidate c,
test_taken tt WHERE c.cid=tt.cid AND score IS NULL
72
-
8/6/2019 04SQL and Advanced SQL
73/133
Searching for Negative Conditions
SELECT DISTINCT fname,lname,wphone,hphone FROM
candidate WHERE lname NOT LIKE 'S%' ORDER BY
lname,fname
SELECT fname,lname,wphone,hphoneFROM candidate c,
test_taken tt WHERE c.cid=tt.cid AND integer(score) NOT
BETWEEN 60 and 75
73
-
8/6/2019 04SQL and Advanced SQL
74/133
Searching for Set of Values
SELECT name,phone FROM test_center tc, test_taken tt WHERE
tc.tcid=tt.tcid AND char(number) IN ('500','502')
74
-
8/6/2019 04SQL and Advanced SQL
75/133
Subqueries
Subqueries can be used in IN clause to specify search arguments
for SQL statement.
SELECT DISTINCT name,phone FROM test_center tc, test_taken
tt WHERE tc.tcid=tt.tcid AND number IN (SELECT number
FROM test WHERE name LIKE 'DB2%')
The subquery used in this example is known as an uncorrelated
subquery.
An uncorrelated subquery is one where the values retrieved by the subquery
are not directly related to the rows processed by the outer SELECT
75
-
8/6/2019 04SQL and Advanced SQL
76/133
A correlated subquery is a query in which subquery references
values of the outer SELECT
SELECT tc.name, count(*) FROM test_center tc,test t WHERE
tc.tcid IN (SELECT tcid FROM test_taken tt WHERE
tt.number=t.number) GROUP BY tc.name
The WHERE clause in the subquery references a table in the outer
FROM clause.
Subqueries
76
-
8/6/2019 04SQL and Advanced SQL
77/133
Quantified Predicates
Used to compare a value or values with a collection of values.
'SOME', 'ANY', 'ALL'
SELECT c.cid, lname, fname FROM db2cert.candidate c WHERE
cid = SOME (SELECT tt.cid FROM db2cert.test_taken tt WHEREc.cid = tt.cid)
77
-
8/6/2019 04SQL and Advanced SQL
78/133
Case Expression
SELECT fname,lname,
CASE
WHEN integer(SCORE) < 65 THEN 'Not Passed'
WHEN integer(SCORE)
-
8/6/2019 04SQL and Advanced SQL
79/133
Set Operators
Union (UNION operator),
Intersection (INTERSECT operator),
Difference (EXCEPT operator).
79
-
8/6/2019 04SQL and Advanced SQL
80/133
Union (UNION Operator)
Allows to combine results of two or more different SELECTs into
one result table.
Up to 16 different result tables can be combined using UNION
operator
Every table or SQL statement must be UNION compatible, i.e., have same
type, number, and order of columns.
UNION operator combines results of two or more separate queries
into a single result.
SELECT number,'Minimum:', MIN(integer(score))
FROM test_taken GROUP BY number
UNION
SELECT number,'Maximum:', MAX(integer(score))
FROM test_taken GROUP BY number
80
-
8/6/2019 04SQL and Advanced SQL
81/133
Intersection (INTERSECT Operator)
To find rows that belong to two different result tables.
SELECT cid FROM candidate INTERSECT
SELECT cid FROM test_taken
81
-
8/6/2019 04SQL and Advanced SQL
82/133
Difference (EXCEPT Operator)
Can find out which rows of one result table are not present in
another result table.
SELECT cid FROM candidate EXCEPT
SELECT cid FROM test_taken
First part of example retrieves all candidate IDs. The second
section of the query retrieves candidate IDs present in
TEST_TAKEN table. Finally, EXCEPT operator performs
difference operation that selects only those candidate IDs not
present in TEST_TAKEN table.
82
-
8/6/2019 04SQL and Advanced SQL
83/133
Data Modifications
Inserting Rows
Updating Rows
Removing Data
83
-
8/6/2019 04SQL and Advanced SQL
84/133
Inserting Rows
INSERT INTO test
(number,name,type,cut_score,length,totaltaken,totalpassed)
VALUES ('508','DB2 Data Propagation','P',NULL,90,0,0)
INSERT INTO test VALUES ('508','DB2 Data
Propagation','P',DEFAULT,90,79,11)
INSERT INTO test_taken
(CID,TCID,NUMBER,DATE_TAKEN,SEAT_NO) VALUES
('888','TR01','500','2000-06-04','1'),
('888','TR01','501','2000-07-11','2'),('888','TR01','502','2000-11-08','1')
84
-
8/6/2019 04SQL and Advanced SQL
85/133
Updating Rows
UPDATE EMPLOYEE SET salary = salary + 1000 WHERE
deptid = 10 AND age > 24
UPDATE test_taken
SET (date_taken,tcid) =
(SELECT current date,tcid FROM test_center WHERE
substr(city,1,7)='Toronto' AND country='Canada')
WHERE CHAR(cid)= '888' AND number=test_id('500')
85
-
8/6/2019 04SQL and Advanced SQL
86/133
Removing Data
DELETE FROM candidate WHERE hphone IS NULL AND
wphone IS NULL
DELETE FROM candidate WHERE cid IN (SELECT cid FROM
test_taken WHERE MONTH(date_taken)=2)
86
-
8/6/2019 04SQL and Advanced SQL
87/133
IBM DB2 Universal Databases 8.1
SQL1. SQL Getting Started
2. Database Objects
3. Data Types
4. Data Definition Language, Constraints & Rules5. Data Manipulation Language
6. Indexes
7. Views
8. Identity Columns
87
-
8/6/2019 04SQL and Advanced SQL
88/133
Index
An index is a list of locations of rows sorted by contents of one or
more specified columns.
Indexes contain a pointer, known as a record id (RID), to physical
location of rows in table.
These are two main purposes for creating indexes:
To ensure uniqueness of values
To improve query performance
There are three types of Indexes
Index
Unique Index
Clustering Index
88
-
8/6/2019 04SQL and Advanced SQL
89/133
Unique Index
Guarantees uniqueness of data values in one or more columns.
Uniqueness is also checked during execution of CREATE INDEX
statement.
If table already contains rows with duplicate key values, index is not created.
89
-
8/6/2019 04SQL and Advanced SQL
90/133
Referencial Integrity and Index
Primary key is maintained using an index.
Index supporting a primary key is known as primary index of
table.
Indexes supporting primary or unique key constraints cannot be
dropped explicitly.
Primary key indexes are dropped with DROP PRIMARY KEYoption.
Unique key indexes are dropped using DROP UNIQUE
(CONSTRAINT NAME) option.
90
-
8/6/2019 04SQL and Advanced SQL
91/133
NULL Values and Indexes
Unique indexes do not enforce primary key constraint by
themselvesthey allow nulls.
Nulls, when it comes to indexing, are treated as equal to all other
nulls.
Null can not be inserted twice if the column is a key of a
unique-index because it violates uniqueness rule for index.
91
-
8/6/2019 04SQL and Advanced SQL
92/133
Create Index Statement
CREATE UNIQUE INDEX EMP_IX ON EMPLOYEE(EMPNO)
INCLUDE(FIRSTNME,JOB)
NOTE:
Index attributes cannot be changed without recreating the index definition.
92
-
8/6/2019 04SQL and Advanced SQL
93/133
IBM DB2 Universal Databases 8.1
SQL1. SQL Getting Started
2. Database Objects
3. Data Types
4. Data Definition Language, Constraints & Rules5. Data Manipulation Language
6. Index
7. Views
8. Identity Columns
93
-
8/6/2019 04SQL and Advanced SQL
94/133
Views
Are logical tables which are derived from one or more base tables
or views.
Can be used interchangably with base tables when retrieving the
data.
Does not contain real data.
View can be ....
Updatable
Deletable
Insertable
Read-only.
NOTE: constraints defined on base table are independents of
operations that can be performed using a view.
94
-
8/6/2019 04SQL and Advanced SQL
95/133
CREATE VIEW view1(tcid,cid,number,
date_taken,start_time,seat_no,score)AS SELECT tcid,cid,number,date_taken,start_time,seat_no,
score from test_table
WHERE tcid=center_id('TR01')
CREATE VIEW Statement
95
l bl i
-
8/6/2019 04SQL and Advanced SQL
96/133
Deletable View
A view meet all rules listed below to be considered a deletable
view...Each FROM clause of outer fullselect identifies only one base table, deletable
view , deletable nested table expression, or deletable common table expression.
The outer fullselect doesnt use VALUES clause.
The outer fullselect doesnt use GROUP BY or HAVING clauses.
The outer fullselect doesnt include column functions in its select list.The outer fullselect doesnt use set operations (UNION,EXCEPT, or
INTERSECT) with exception of UNION ALL .
The base tables in operands of a UNION ALL must not be same table, and
each operand must be deletable.
The select list of outer fullselect does not include DISTINCT .
96
U d bl Vi
-
8/6/2019 04SQL and Advanced SQL
97/133
Updatable View
Is a special case of deletable view
A deletable view becomes a updatable view when at lease one of
its columns is updatable.
Column of a view is updatable when...
View is deletable
Column resolves to a column of a base table
All the corresponding columns of UNION ALL have exactly matching data
types (including length or precision and scale).
97
I bl Vi
-
8/6/2019 04SQL and Advanced SQL
98/133
Insertable Views
Allows you to insert rows using view definition.
A view is insertable when.....
All of its columns are updatable.
98
R d O l Vi
-
8/6/2019 04SQL and Advanced SQL
99/133
Read-Only Views
Is a non-deletable view.
A view can be read-only if it does not comply with at least one of
the rules of the deletable views.
CREATE VIEW view1 (name,work_phone,home_phone) AS
SELECT DISTINCT fname,wphone,hphone FROM candidate c,
test_taken tt
WHERE c.cid = tt.cid
99
I ti Vi
-
8/6/2019 04SQL and Advanced SQL
100/133
Inoperative Views
Is no longer available for SQL statements.
A view becomes inoperative if...
Privilege upon which view definition is dependent, is revoked.
Object upon which view definition is dependent, is dropped
View, upon which this view definition is dependent, becomes inoperative.
100
Vi With CHECK OPTION
-
8/6/2019 04SQL and Advanced SQL
101/133
CREATE VIEW xyz(EMPNO,ENAME, DEPTNO) AS SELECT
EMPNO, ENAME, DEPTNO FROM EMPLOYEE WHEREDEPTNO = 10 WITH CHECK OPTION.
'WITH CHECK OPTION' ensures that the condition is aways
checked.
If the view is used in INSERT statement, row will be rejected if
value of DEPTNO column is not 10.
View With CHECK OPTION
101
IBM DB2 U i l D t b 8 1
-
8/6/2019 04SQL and Advanced SQL
102/133
IBM DB2 Universal Databases 8.1
SQL1. SQL Getting Started
2. Database Objects
3. Data Types
4. Data Definition Language, Constraints & Rules5. Data Manipulation Language
6. Indexes
7. Views
8. Identity Columns
102
Id tit C l
-
8/6/2019 04SQL and Advanced SQL
103/133
Identity Columns
A numeric column in a table for which DB2 automatically
generates a unique numeric value for each row that is inserted intothe table
A table may have a single column that is defined with the identity
attribute
Intended to be used for generating unique primary key values
Examples: order number, employee number, stock number
Values can be generated by DB2 always or by default
Always
Values are always generated by DB2
Applications are not allowed to provide an explicit value.
By default
Values can be explicitly provided by an application or if no value is given,
then DB2 generates one
DB2 cannot guarantee uniqueness
103
Creating Identit Col mn
-
8/6/2019 04SQL and Advanced SQL
104/133
Creating Identity Columns
CREATE TABLE INVENTORY
(partno INTEGERGENERATED ALWAYS AS IDENTITY
(START WITH 100 INCREMENT BY 1),
description CHAR(20));
CREATE TABLE EMPLOYEES
(empno INTEGER
GENERATED BY DEFAULT AS IDENTITY
(START WITH 1000 INCREMENT BY 1 CACHE 10),
name CHAR(20));
Cache: minimum value is 2 and the maximum value is 32767
104
Notes:
-
8/6/2019 04SQL and Advanced SQL
105/133
Identity column
Must be numeric: SMALLINT, INTEGER, BIGINT, DECIMAL with precision 0Implicitly NOT NULL
Identity column does not imply a unique column. If uniqueness is required must create aunique index or primary key on the column.
START WITH n INCREMENT BY mn specifies the first value for the column, can be positive or negative, default is 1
m specifies the interval between consecutive values of the column, can be positive ornegative resulting in ascending or descending sequence
CACHE or NO CACHE
Specifies whether to keep some pre-allocated values in memory for faster access
Performance option - reduces synchronous I/O to the log when values are generated
When a database is deactivated (normally or by failure), all cached sequence values arelost
Notes:
105
Inserting into Identity Columns
-
8/6/2019 04SQL and Advanced SQL
106/133
Inserting into Identity Columns
CONNECT TO sample;
CREATE TABLE inventory
(partno INTEGER
GENERATED ALWAYS AS IDENTITY (START WITH 100 INCREMENT BY 1),
description CHAR(20) );
COMMIT;
INSERT INTO inventory VALUES (DEFAULT,'door'); --->inserts 100,door
INSERT INTO inventory (description) VALUES ('hinge'); --->inserts 101,hinge
INSERT INTO inventory VALUES (200,'windor'); --->error
COMMIT;
INSERT INTO inventory (description) VALUES ('lock'); --->inserts 102,lock
ROLLBACK;
INSERT INTO inventory (description) VALUES ('frame'); --->inserts 103,frame
COMMIT;
SELECT * FROM inventory;
100 door
101 hinge
103 frame
106
Inserting into Identity Columns
-
8/6/2019 04SQL and Advanced SQL
107/133
Inserting into Identity ColumnsCONNECT TO sample;
CREATE TABLE inventory
(partno INTEGER PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY (START WITH 100 INCREMENT BY 1),
description CHAR(20) );
COMMIT;
INSERT INTO inventory VALUES (DEFAULT,'door'); --->inserts 100,door
INSERT INTO inventory (description) VALUES ('hinge'); --->inserts 101,hinge
INSERT INTO inventory VALUES (200,'window'); --->inserts 200,window
INSERT INTO inventory VALUES (102,'handle'); --->inserts 102,handleINSERT INTO inventory VALUES (101,'bolt'); --->error, duplicate
COMMIT;
INSERT INTO inventory (description) VALUES ('lock'); --->error, duplicate
INSERT INTO inventory (description) VALUES ('lock'); --->inserts 103,lock
ROLLBACK;
INSERT INTO inventory (description) VALUES ('frame'); --->inserts 104,frameCOMMIT;
SELECT * FROM inventory order by partno;
100 door
101 hinge
102 handle
104 frame
200 window 107
Retrieving Generated Value
-
8/6/2019 04SQL and Advanced SQL
108/133
Retrieving Generated Value
Function available to retrieve the last value generated:
identity_val_local()Must be used with a VALUES clause
Function has no input parameter
Result returned is a DECIMAL(31,0) data type, regardless of the actual
data type of the identity column
Function returns the most recently assigned value for an identity column,where the assignment occurred as a result of a single row INSERT
statement
Value can only be retrieved within the same unit of work as the INSERT
statement
The assigned value could be values supplied by the user or by DB2
108
IDENTITY VAL LOCAL()
-
8/6/2019 04SQL and Advanced SQL
109/133
IDENTITY_VAL_LOCAL()
(SET AUTOCOMMIT OFF)
CONNECT TO sample;
CREATE TABLE T1
( C1 INTEGER GENERATED ALWAYS AS IDENTITY,
C2 INTEGER ) ;
INSERT INTO T1 (C2) VALUES (5);
INSERT INTO T1 (C2) VALUES (6);SELECT * FROM T1;
C1 C2
----- -----
1 5
2 6
VALUES IDENTITY_VAL_LOCAL( );
IDENTITY_VAL_LOCAL( )
--------------------
2
COMMIT;
109
Notes:
-
8/6/2019 04SQL and Advanced SQL
110/133
Identitymissing: when input data file does not contain any values for the identitycolumn. Example: a table tab1 has C1 identity, C2, C3, C4 columns. Input filecontains data for columns C2, C3 and C4 only. To invoke load:
load from data.del of del replace into tab1 (C2,C3,C4) ....is equivalent to...
load from data.del of del modified by identitymissing replace into table1
Identityignore: even though the input data file contains data for the identity column,
the data should be ignored and identity values should be generated for each row.
Identityoverride: used for loading user-supplied values into a table having aGENERATED ALWAYS identity column. Useful when migrating data from anotherdatabase.
Notes:
110
IBM DB2 Universal Databases 8 1
-
8/6/2019 04SQL and Advanced SQL
111/133
IBM DB2 Universal Databases 8.1
Advanced SQL1. User Defined Data Types
2. Sequences
3. Advanced Functions
111
User Defined Types
-
8/6/2019 04SQL and Advanced SQL
112/133
User Defined Types
User defined distinct types
User defined structured types
112
User Defined Types
-
8/6/2019 04SQL and Advanced SQL
113/133
User-defined distinct type :
Can be created on an existing data type.
Strong typing:
If columns are defined using different UDTs based on the same
base data type, these UDTs cannot be directly compared.
Only functions/operators defined on distinct type can be applied
to its instances.
Hence DB2 does not allow direct comparison between 'distinct'
type and 'source' type (ie. US_DOLLAR and DECIMAL)
Casting functions:
When UDTs are defined, system-generated SQL functions are
created.
Casting functions allow comparison between the UDT and its
base type.
User Defined Types
113
User Defined Types
-
8/6/2019 04SQL and Advanced SQL
114/133
User-defined distinct type :
CREATE DISTINCT TYPE pound AS INTEGER WITH COMPARISONS
CREATE DISTINCT TYPE kilogram AS INTEGER WITH
COMPARISONS
CREATE TABLE health (f_name VARCHAR(30), weight_p POUND,
weight_k KILOGRAM)
SELECT f_name, weight_p FROM health WHERE weight_p > POUND(30)
User Defined Types
114
User Defined Types
-
8/6/2019 04SQL and Advanced SQL
115/133
User-defined distinct type :
CREATE DISTINCT TYPE PHONENO AS CHAR(10)
WITH COMPARISONS
Creation of this user-defined data type will result in
creation of following casting functions:
CHAR(PHONENO): translates data values from the
PHONENO data type to base data type CHAR
PHONENO(CHAR): translates data values from base
data type CHAR to PHONENO data type
User Defined Types
115
User Defined Distinct Types
-
8/6/2019 04SQL and Advanced SQL
116/133
User Defined Distinct Types
CREATE DISTINCT TYPE US_DOLLAR AS DECIMAL(9,2)
WITH COMPARISONS
CREATE TABLE US_SALES (
PRODUCT_ITEM INTEGER,
YEAR INTEGER CHECK(YEAR>1985),
TOTAL US_DOLLAR)
116
User Defined Distinct Types
-
8/6/2019 04SQL and Advanced SQL
117/133
User Defined Distinct Types
As a part of distinct type generation, DB2 generates 'cast' function.
E.g.
SELECT PRODUCT_ITEM FROM US_SALES WHERE TOTAL >
US_DOLLAR(100000)
OR
SELECT PRODUCT_ITEM FROM US_SALES WHERE TOTAL > CAST(100000 AS US_DOLLAR)
117
Important Functions...
-
8/6/2019 04SQL and Advanced SQL
118/133
CREATE FUNCTION SUMDOLLAR(US_DOLLAR) RETURNS
US_DOLLAR SOURCE SYSIBM.SUM(DECIMAL())
SELECT SUMDOLLAR(TOTAL) FROM US_SALES
CREATE FUNCTION DOLLAR_AVG(US_DOLLAR)
RETURNS DECIMAL SOURCE SYSIBM.AVG(DECIMAL())
SELECT DOLLAR_AVG(TOTAL) FROM US_SALES
Important Functions...
118
Important Functions
-
8/6/2019 04SQL and Advanced SQL
119/133
Important Functions
SELECT DOLLAR_AVG(TOTAL) - 10 FROM US_SALES
SELECT ((SELECT DOLLAR_AVG(TOTAL) FROM
US_SALES WHERE YEAR = 1987)- (SELECT
DOLLAR_AVG(TOTAL) FROM US_SALES WHERE
YEAR=1986)) FROM US_SALES
119
User Defined Structured Types
-
8/6/2019 04SQL and Advanced SQL
120/133
'Structured types' are useful for modelling objects that have a well
defined structure consisting of 'attributes'.
CREATE TYPE ADDRESS_T AS (
HOUSE CHAR(15),
STREET1 CHAR(15),
STREET2 CHAR(15),
CITY CHAR(15),
PIN CHAR(6)) MODE DB2SQL
User Defined Structured Types
120
User Defined Structured Types
-
8/6/2019 04SQL and Advanced SQL
121/133
User Defined Structured Types
Inheritance:
CREATE TYPE PERSON_T AS(NAME CHAR(15),
AGE INT, ADDRESS ADDRESS_T) MODE DB2SQL
CREATE TYPE EMP_T
UNDER PERSON_TAS (EMPCODE INT, SALARY DECIMAL(9,2))
MODE DB2SQL
121
Using Typed Tables..
-
8/6/2019 04SQL and Advanced SQL
122/133
g yp
CREATE TABLE PERSON OF PERSON_T (REF IS OID USER
GENERATED)
CREATE TABLE EMP OF EMP_T UNDER PERSON INHERIT
SELECT PRIVILEGES
INSERT INTO PERSON(OID,NAME,AGE,ADDRESS)
VALUES(PERSON_T('a'),'Gopal',28,
ADDRESS_T()..HOUSE('house1')..STREET1('MG Road')
..STREET2('Off High Way')..CITY('Mumbai')..PIN('400063'))
INSERT INTO PERSON (OID,NAME,AGE,ADDRESS)
VALUES (PERSON_T(GENERATE_UNIQUE()),
'Prakash',28,ADDRESS_T()..HOUSE('house2')..STREET1('L T
Road')..STREET2('Off high Way')..PIN('400063'))
122
Reference Columns
-
8/6/2019 04SQL and Advanced SQL
123/133
In typed table definition, columns can be defined as reference
columns to another typed table.Referenced typed table is called a target table.
A reference column holds values that correspond to OID values of
target table and clearly identify rows in target tables.
Data type of a reference column is REFERENCE , the same type
as OID in target table.
Reference column is similar to foreign key; however, evaluation,like a foreign key, is not performed for operations such as insert,
update, or delete.
123
Reference Columns
-
8/6/2019 04SQL and Advanced SQL
124/133
CREATE TYPE DEPT_T AS (NAME CHAR(40), LOCATION CHAR(20))
REF USING INTEGER MODE DB2SQL
CREATE TYPE EMP_T UNDER PERSON_T AS (SALARY INTEGER,
DEPTREF REF(DEPT_T)) MODE DB2SQL
Deptref REF(Dept_t) means that this attribute DEPTREF of EMP_T type is
reference type and target of reference is a row of table whose row type is
DEPT_T or its sub-type.
CREATE TABLE DEPT OF DEPT_T (REF IS Oid USER GENERATED)
CREATE TABLE EMP OF EMP_T UNDER PERSON INHERIT SELECT
PRIVILEGES (DEPTREF WITH OPTIONS SCOPE Dept)
DEPTREF WITH OPTIONS SCOPE DEPT means that values in column
DEPTREF are pointing to rows in table DEPT or values in any sub-tables of
DEPT table.
124
Selecting Rows From Typed Table
-
8/6/2019 04SQL and Advanced SQL
125/133
g yp
When a select statement is issued for a typed table, rows are
returned from target table and all of its sub-tables in tablehierarchy.
For retrieving rows of only PERSON table...
SELECT * FROM ONLY(Person)
125
Selecting Rows From Typed Tables
-
8/6/2019 04SQL and Advanced SQL
126/133
SELECT NAME,AGE,
ADDRESS..HOUSE,
ADDRESS..STREET1,
ADDRESS..STREET2,
ADDRESS..CITY,
ADDRESS..PIN FROM PERSON
g yp
126
Updating And Deleting Rows From Typed Tables
-
8/6/2019 04SQL and Advanced SQL
127/133
p g g yp
UPDATE Person SET birthyear=1969 WHERE oid=Emp_t(10)
DELETE FROM Person
Deletes all rows from PERSON table and its sub-tables.
DELETE FROM ONLY(Person)
127
IBM DB2 Universal Databases 8.1
-
8/6/2019 04SQL and Advanced SQL
128/133
Advanced SQL1. User Defined Data Types
2. Sequences
3. Advanced Functions
128
Sequences
-
8/6/2019 04SQL and Advanced SQL
129/133
q
SEQUENCE object lets DBA or developer create a value that gets
incremented under programmer control and can be used acrossmany different tables.
CREATE SEQUENCE CUSTOMER_NO AS INTEGER
By default this sequence number starts at one and increments by one at a time
and is of an INTEGER datatype.
NEXTVAL :
Function generates next value for sequence which can then be used for
subsequent SQL statements
INSERT INTO CUSTOMERS VALUE (NEXTVAL FORCUSTOMER_NO, 'Prakash', ...)
129
Sequences
-
8/6/2019 04SQL and Advanced SQL
130/133
PREVVAL:
Will only return last value generated by that application.Function can be used multiple times within application.
INSERT INTO INVOICES (34,PREVVAL FOR
CUSTOMER_NO, 234.44, ...)
If customer number generated, needs to be used for a subsequent invoicerecord.
130
IBM DB2 Universal Databases 8.1
-
8/6/2019 04SQL and Advanced SQL
131/133
Advanced SQL1. User Defined Data Types
2. Sequences
3. Advanced Functions
131
Advance Functions
-
8/6/2019 04SQL and Advanced SQL
132/133
Trigonometric Functions
COS , SIN , TAN , COT , TANH , COSH , SINH , ATAH , ATAN2
Math Functions
INTEGER , FLOOR , CEILING , TRUNC , SQRT , LN , EXP
String Functions
RTRIM,LTRIM,INSTR,TRANSLATE,REPEAT,REPLACE,CONCAT,
SUBSTR, LENGTH , LOWER/LCASE , UPPER/UCASE
Statistical Functions
CORRELATION , STDDEV , VARIANCE
Date Functions
DATE , TIME , TO_CHAR , TO_DATE , DAYNAME , DAYOFWEEK
Logic FunctionsCOALESCE , NULLIF
Speciality Functions
MQPUBLISH , MQREAD , ENCRYPT , REC2XML
132
Summary
-
8/6/2019 04SQL and Advanced SQL
133/133
SQL
SQL Getting StartedDatabase Objects
Data Types, Constraints, Rules
Data Definition Language
Data Manipulation Language
Indexes
ViewsIdentity Columns
Advanced SQLUser Defined Data Types
Sequences
Advanced Functions