+ All Categories
Home > Documents > OracleVsDB2

OracleVsDB2

Date post: 14-Nov-2014
Category:
Upload: api-3832227
View: 116 times
Download: 8 times
Share this document with a friend
Description:
OracleVsDB2
Popular Tags:
124
12/29/21 1 Oracle and DB2 Florida State University Administrative Information Systems University Data Services Penny Bowman February, 2002
Transcript
Page 1: OracleVsDB2

04/08/23 1

Oracle and DB2

Florida State University

Administrative Information Systems

University Data Services

Penny Bowman February, 2002

Page 2: OracleVsDB2

04/08/23 2

Differences Between Oracle and DB2

Since FSU/AIS is now using both DB2 databases and Oracle databases in the production solutions, you may be assigned to write SQL code that must access them both

Be aware that there are differences between the two databases that may affect your code or the ability to port what you have written

This presentation is not a comprehensive list of differences, only a brief comparison and contrast

For more in depth knowledge, you should study the two systems and consult with DBA

Page 3: OracleVsDB2

04/08/23 3

Differences Between Oracle and DB2

Platforms Catalog / Data Dictionary Tools Datatypes Functions Combining Data from Multiple Tables Explain Plan Tables Other Differences

Page 4: OracleVsDB2

04/08/23 4

DB2 Platforms in AIS

NWRDC 390 mainframe– DB2 Version 6– Test Region – DB2T– Production Region – DSN

UDB for Data Warehouse – local server– UDB Version 7.2– New Client tools– System will soon be ready

Page 5: OracleVsDB2

04/08/23 5

Oracle Platforms in AIS

Development Server - UNIX– Register2.acns.fsu.edu (128.186.6.100)– Oracle 8.1.7.2.0

Staging Server - NT – Athena (128.186.6.47)– Oracle 8.0.4.0.0

Production – UNIX– Puffer.oti.fsu.edu – Oracle 8.0.6.0.0

COLD Server – NT– Zeus.oit.fsu.edu (128.186.6.45)– Oracle 8.1.6.0.0

Page 6: OracleVsDB2

04/08/23 6

DB2 Catalog

Contains information about all the objects in DB2 SYSIBM.SYSDUMMY1(one row system table) WorkBench refreshed nightly from the DB2

Catalog SELECT access to PUBLIC has been granted for

the DB2 catalog tables on NWRDC. By default, only SYSADM or SYSCTRL authority automatically has the privilege of retrieving data from catalog tables.

Page 7: OracleVsDB2

04/08/23 7

DB2 Catalog

No easy predefined views provided with DB2. This is the select statement to query the catalog to list the tables in your group that you can access:

SELECT DISTINCT TCREATOR,TTNAME FROM SYSIBM.SYSTABAUTH

WHERE GRANTEE='FSDBA' AND

GRANTEETYPE= ' ';

Page 8: OracleVsDB2

04/08/23 8

Oracle Data Dictionary

Contains information about objects in Oracle Dual (one row system table) DESCRIBE command

This is the select statement to query the catalog to list the tables you can access:

SELECT OWNER, TABLE_NAME FROM ALL_TABLES ORDER BY 2;

Page 9: OracleVsDB2

04/08/23 9

Oracle Data Dictionary

Prefix for Views for DBAs: DBA_

Prefix for Views for Non DBA users : USER_ and ALL_

Views for All Users: Session_Privs and Session_Roles

Views for DBAs: Privilege related views

V$ Performance Views

Page 10: OracleVsDB2

04/08/23 10

Data Dictionary Views for Users

Use the DESCribe command to examine the table structure of each View before you SELECT from the View. This is a sampling of the available views:

USER_CATALOG USER_COL_COMMENTS USER_COL_PRIVS USER_CONSTRAINTS USER_CONS_COLUMNS USER_DEPENDENCIES

USER_INDEXES USER_IND_COLUMNS USER_OBJECTS USER_RESOURCE_LIMITS USER_ROLE_PRIVS USER_TABLES USER_TABLESPACES USER_TAB_COLUMNS USER_TAB_COMMENTS USER_USERS USER_VIEWS

Page 11: OracleVsDB2

04/08/23 11

DB2 Mainframe Tools on NWRDC

SPUFI - to develop and test SQL WorkBench – primarily used to:

– analyze DB2 database objects – capture DDL to create or alter tables – review indexes & referential integrity between tables

R-Tools – used to browse and edit tables, can specify column values and dynamically join tables

Insight – primarily used to– Monitor Active Threads– Analyze Thread History – cost of DB2– Explain SQL statements

Page 12: OracleVsDB2

04/08/23 12

Oracle Client Tools

SQL Plus Worksheet (to develop and test SQL) DBA Studio - multiple database tools in one

application. Used to administer:– Instances, including startup, shutdown, and

initialization.– Schemas, including tables, indexes, and Oracle8

objects.– Security, including user accounts, roles, and privileges.– Storage, including tablespaces, datafiles, and rollback

segments.

Page 13: OracleVsDB2

04/08/23 13

Differences Between Oracle and DB2

This section includes the data types and functions for each database

First – the DB2 data types and functions are discussed

Followed by the Oracle datatypes and functions

Page 14: OracleVsDB2

04/08/23 14

DB2 Datatypes

String Types: CHARACTER(size) VARCHAR(size) (2 byte

overhead) GRAPHIC(size) VARGRAPHIC(size) BLOB(n) CLOB(n) DBCLOB(n)

String subtypes applicable to CHAR, VARCHAR, and CLOB:– BIT– SBCS– MIXED

ROWID

Page 15: OracleVsDB2

04/08/23 15

DB2 Datatypes

Numeric Types: SMALLINT (range of -32768 to +32767) INTEGER or INT (range -2147483648 to

+2147483647) REAL or FLOAT(n) Single precision floating-

point numbers. n must be in the range 1 through 21. If you omit n, the column has double precision.

Page 16: OracleVsDB2

04/08/23 16

DB2 Datatypes

Numeric Types Continued: FLOAT, FLOAT(n), or DOUBLE PRECISION,

or DOUBLE (packed decimal numbers with precision p and scale s.

The precision p, which is the total number of digits including the digits following the decimal point, must be greater than 0 and less than 32.

The scale s, which is the number of digits in the fractional part of the number, must be greater than or equal to 0 and less than or equal to the precision. s can be omitted; its default is 0. If s is omitted, p can also be omitted; its default is 5.

The maximum range is 1 - 10**31 to 10**31 - 1.

Page 17: OracleVsDB2

04/08/23 17

DB2 Identity

Identity is a type of column in a table DB2 automatically calculates the value on an INSERT or

UPDATE A table can have only one identity column. numeric type

with a scale of zero An identity column is implicitly NOT NULL.,

Identify column values increment if the initial value is positive, or decrement if the initial value is negative. The default is 1.

Page 18: OracleVsDB2

04/08/23 18

DB2 DATE / Functions

DATE – YYYY-MM-DD

TIME – HH.MM.SS

TIMESTAMP –

0001-01-01-00.00.00.000000 to

9999-12-31-24.00.00.000000

Default date format is

YYYY-MM-DD

Date FunctionsCHARDATEDAY

DAYOFMONTHDAYOFWEEKDAYOFYEAR–DAYS–HOURJULIAN_DAY–MICROSECOND–MIDNIGHT_ SECONDS–MINUTE–MONTHQUARTER–SECOND

Page 19: OracleVsDB2

04/08/23 19

DB2 Version 6 Functions

ABS or ABSVAL ACOS ASIN ATAN ATANH ATAN2 AVG BLOB

CEIL or CEILING CHAR CLOB COALESCE CONCAT COS COSH

Page 20: OracleVsDB2

04/08/23 20

DB2 Version 6 Functions

COUNT COUNT_BIG DATE DAY DAYOFMONTH DAYOFWEEK DAYOFYEAR DAYS DBCLOB

DECIMAL or DEC DEGREES DIGITS DOUBLE or

DOUBLE-PRECISIION

EXP FLOAT FLOOR

Page 21: OracleVsDB2

04/08/23 21

DB2 Version 6 Functions

GRAPHIC HEX HOUR IFNULL INSERT INTEGER or INT JULIAN_DAY LCASE or LOWER

LEFT LENGTH LN LOCATE LOG LOG10 LTRIM MAX

Page 22: OracleVsDB2

04/08/23 22

DB2 Version 6 Functions

MICROSECOND MIDNIGHT_

SECONDS MIN MINUTE MOD MONTH NULLIF

POSSTR POWER QUARTER RADIANS RAISE_ERROR RAND REAL REPEAT

Page 23: OracleVsDB2

04/08/23 23

DB2 Version 6 Functions

REPLACE RIGHT ROUND ROWID RTRIM SECOND SIGN SIN

SINH SMALLINT SPACE SQRT STDDEV STRIP SUBSTR SUM

Page 24: OracleVsDB2

04/08/23 24

DB2 Version 6 Functions

TAN TANH TIME TIMESTAMP TIMESTAMP_

FORMAT TRANSLATE TRUNCATE or

TRUNC

UCASE OR UPPER VALUE VARCHAR VARCHAR_

FORMAT VARGRAPHIC VARIANCE OR VAR WEEK YEAR

Page 25: OracleVsDB2

04/08/23 25

DB2 Date Type

Date/time values in DB2 are stored in a special internal format. When you load or retrieve data, DB2 can convert to or from any of the valid formats.

DATE– A date is a three-part value representing a year, month,

and day in the range 0001-01-01 to 9999-12-31 YYYYMMDD

YYYY corresponds to a year value from 0000 to 9999 MM corresponds to a month value from 1 to 12 DD corresponds to a day value from 1 to 31

Page 26: OracleVsDB2

04/08/23 26

DB2 Time Datatype

TIME– A time is a three-part value representing a time of day

in hours, minutes, and seconds, in the range 00.00.00 to 24.00.00.

– HHMMSS

HH corresponds to an hour value from 00 to 24 MM corresponds to a minute value from 0 to 59 SS corresponds to a second value from 0 to 59

Page 27: OracleVsDB2

04/08/23 27

DB2 Timestamp Datatype

TIMESTAMP– A timestamp is a seven-part value representing a date and time by

year, month, day, hour, minute, second, and microsecond, in the range 0001-01-01-00.00.00.000000 to 9999-12-31-24.00.00.000000.

– YYYYMMDDHHMMSSMICROS YYYYMMDD corresponds to YEAR, MONTH and DAY HHMMSS corresponds to HOUR, MINUTE and SECOND MICROS corresponds to microseconds

Page 28: OracleVsDB2

04/08/23 28

DB2 Date, Time, Timestamp Data Types

The combination of using DATE and TIME requires 7 bytes, and using them in combination can save space over using TIMESTAMP. To calculate a duration using DATE and TIME columns, two subtractions must occur; one for the DATE column and one for the TIME column.

Use the DB2 TIMESTAMP data type when the date and time are always needed together, but rarely needed alone. TIMESTAMP provides greater time accuracy, down to the microsecond level, requires 10 bytes. Use this when greater precision is important. Subtracting one TIMESTAMP field from another results in a TIMESTAMP duration.

Page 29: OracleVsDB2

04/08/23 29

DB2 Date / Time Functions

CHAR DATE DAY DAYOFMONTH DAYOFWEEK DAYOFYEAR DAYS HOUR JULIAN_DAY

MICROSECOND MIDNIGHT_

SECONDS MINUTE MONTH QUARTER SECOND

Page 30: OracleVsDB2

04/08/23 30

DB2 Version 6 Functions

TIME TIMESTAMP TIMESTAMP_

FORMAT WEEK YEAR

Page 31: OracleVsDB2

04/08/23 31

DB2 CHAR Function to Format Date and Time

The CHAR function returns a character representation of a date, a time, a timestamp or a decimal number.

CHAR function allows you to easily convert date and time columns from the system format to one of several international standard formats.

CHAR( field, {ISO|USA|EUR|JIS} )

Page 32: OracleVsDB2

04/08/23 32

DB2 CHAR Function to Format Date and Time

IF field is a date - The result is a date character string in the specified format (ISO is the default,USA,EUR,JIS)

IF field is a time -The result is a time character string in the specified format (ISO is the default,USA,EUR,JIS)

IF field is a timestamp - The result is a timestamp character string, no format can be specified.

IF field is a decimal number - The result is a decimal character string (including sign), no format can be specified.

Page 33: OracleVsDB2

04/08/23 33

DB2 CHAR Function Examples

SELECT STUDENT_ID,

CHAR(BIRTHDATE,ISO) AS ISODATE,

CHAR(BIRTHDATE,USA) AS USADATE,

CHAR(BIRTHDATE,EUR) AS EURDATE,

CHAR(BIRTHDATE,JIS) AS JISDATE

FROM ...

STUDENT_ID ISODATE USADATE EURDATE JISDATE

001505664 1977-06-12 06/12/1977 12.06.1977 1977-06-12

Page 34: OracleVsDB2

04/08/23 34

DB2 Current Date / Time Functions

These functions return current information from DB2:

CURRENT DATE

CURRENT TIME

CURRENT TIMESTAMP

If you want to only manipulate the current date or time, and you are not selecting other columns from a table, you may issue a SELECT statement using the system provided one row table:

– SELECT CURRENT DATE, CURRENT TIME FROM SYSIBM.SYSDUMMY1;

Page 35: OracleVsDB2

04/08/23 35

DB2 CURRENT TIME Functions

SELECT STUDENT_ID,

CHAR(CURRENT_TIME,ISO) AS ISOTIME,

CHAR(CURRENT_TIME,USA) AS USATIME,

CHAR(CURRENT_TIME,EUR) AS EURTIME,

CHAR(CURRENT_TIME,JIS) AS JISTIME

FROM FSDBA.STUDENT_MASTER

WHERE STUDENT_ID = '001505664’ ;

---------+---------+---------+---------+---------+

STUDENT_ID ISOTIME USATIME EURTIME JISTIME

---------+---------+---------+---------+---------+

001505664 09.53.55 09:53 AM 09.53.55 09:53:55

Page 36: OracleVsDB2

04/08/23 36

DB2 CURRENT TIMESTAMP Functions

SELECT STUDENT_ID,

CHAR(CURRENT_TIMESTAMP) AS CHARTIMESTAMP,

CHAR(245.54 - 3448.98) AS CHARDECIMAL

FROM

FSDBA.STUDENT_MASTER

WHERE

STUDENT_ID = '001505664' ;

---------+---------+---------+---------+---------+--

STUDENT_ID CHARTIMESTAMP CHARDECIMAL

---------+---------+---------+---------+---------+--

001505664 1998-02-03-09.58.38.904056 -03203.44

Page 37: OracleVsDB2

04/08/23 37

DB2 DATE Function

– The DATE function returns an internal (binary) representation of a date, a timestamp, an integer or a character string. The result of subtracting one DATE value from another, as in the expression HIREDATE - BIRTHDATE, is a date duration.

– IF field is a date or more likely, a date calculation

– The result is the internal representation of that date.

– IF field is a timestamp

– The result is the internal representation of the date portion of the timestamp.

Page 38: OracleVsDB2

04/08/23 38

DB2 DATE Function

– IF field is an integer n

– The result is the internal representation of the date n-1 days from 01/01/0001.

– IF field is a character string representing a Julian date ('1998030')

– The result is the internal representation of the equivalent date.

Page 39: OracleVsDB2

04/08/23 39

DB2 DATE Function Examples

SELECT

DATE(CURRENT_DATE + 30 DAYS) AS DATEOFDATE,

DATE(CURRENT_TIMESTAMP) AS DATEOFTIMESTAMP,

DATE(730000) AS DATEOFINTEGER,

DATE('2000001') AS DATEOFCHAR

….

DATEOFDATE DATEOFTIMESTAMP DATEOFINTEGER DATEOFCHAR

1998-03-05 1998-02-03 1999-09-03 2000-01-01

Page 40: OracleVsDB2

04/08/23 40

DB2 DAY

– The DAY function returns the day of the month (1-31) representation of a date or timestamp, or the number of days in a date or timestamp duration.

– IF field is a date - the result is the day of the month for that date.

– IF field is a timestamp - the result is the day of the month for that timestamp.

– IF field is a date duration (date calculation) - the result is the number of days in the period (-99 to 99).

– IF field is a timestamp duration - the result is the number of days in the period (-99 to 99).

Page 41: OracleVsDB2

04/08/23 41

DB2 DAY Function Examples

SELECT CURRENT_DATE, DAY(BIRTHDATE) AS DAYOFDATE,

DAY(CURRENT_TIMESTAMP) AS DAYOFTIMESTAMP,

DAY(CURRENT_DATE - DATE('1997-12-31'))

AS DAYOFDATEDUR

FROM ….

CURRENT DATE DAYOFDATE DAYOFTIMESTAMP DAYOFDATEDUR

1998-02-03 12 3 3

Notice that, in the date duration calculation, only the DAYS portion of the dates are taken into consideration. A duration calculation for timestamps would be similar. Notice also that the example includes a FUNCTION (DATE) within a FUNCTION (DAY).

Page 42: OracleVsDB2

04/08/23 42

DB2 DAYOFMONTH( )

The DAYOFMONTH function returns the day part of its argument.

The function is similar to the DAY function, except DAYOFMONTH does not support a date, or timestamp duration as an argument.

The argument must be a date, a timestamp, or a valid character string, representation of a date or timestamp.

The result of the function is a large integer between 1 and 31, which represents the day part of the value. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Page 43: OracleVsDB2

04/08/23 43

DB2 DAYOFMONTH( )

Example: Set the INTEGER variable DAYVAR to the day of the month on which employee 140 in sample table DSN8610.EMP was hired.,

SELECT DAYOFMONTH(HIREDATE)

INTO :DAYVAR

FROM DSN8610.EMP

WHERE EMPNO = '000140';

Page 44: OracleVsDB2

04/08/23 44

DB2 DAYOFWEEK( )

The DAYOFWEEK function returns an integer in the range of 1 to 7 that represents the day of the week.

The argument must be a date, a timestamp, or a valid character string, representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Page 45: OracleVsDB2

04/08/23 45

DB2 DAYOFWEEK( )

Example: Using sample table DSN8610.EMP, set the integer host variable DAY_OF_WEEK to the day of the week that Christine Haas (EMPNO = '000010') was hired (HIREDATE).

SELECT DAYOFWEEK(HIREDATE)

INTO :DAY_OF_WEEK

FROM DSN8610.EMP

WHERE EMPNO = '000010';

The result is that DAY_OF_WEEK is set 6, which represents Friday.

Page 46: OracleVsDB2

04/08/23 46

DB2 DAYOFWEEK( )

Example : The following query returns four values: 1, 2, 1, and 2.,

SELECT

DAYOFWEEK(CAST('10/11/1998',AS DATE)),

DAYOFWEEK(TIMESTAMP('10/12/1998','01.02')),

DAYOFWEEK(CAST(CAST('10/11/1998', AS DATE) AS CHAR(20))),

DAYOFWEEK(CAST(TIMESTAMP('10/12/1998‘ ,'01.02') AS CHAR(20))),

FROM SYSIBM.SYSDUMMY1;

Page 47: OracleVsDB2

04/08/23 47

DB2 DAYOFYEAR( )

The DAYOFYEAR function returns an integer in the range of 1 to 366 that represents the day of the year where 1 is January 1.

The argument must be a date, a timestamp, or a valid character string, representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Page 48: OracleVsDB2

04/08/23 48

DB2 DAYOFYEAR( )

Example: Using sample table DSN8610.EMP, set the integer host variable AVG_DAY_OF_YEAR to the average of the day of the year on which employees were hired (HIREDATE):

SELECT AVG(DAYOFYEAR(HIREDATE)),

INTO :AVG_DAY_OF_YEAR

FROM DSN8610.EMP;

The result is that AVG_DAY_OF_YEAR is set to 202.

Page 49: OracleVsDB2

04/08/23 49

DB2 DAYS

The DAYS function returns an integer representation of a date, a timestamp or the character string equivalent of a date.

– IF field is a date -the result is the integer number of days plus 1 since 01/01/0001.

– IF field is a timestamp - the result is the integer number of days plus 1 since 01/01/0001.

– IF field is a character string equivalent of a date - the result is the integer number of days plus 1 since 01/01/0001.

Page 50: OracleVsDB2

04/08/23 50

DB2 DAYS Function Examples

SELECT CURRENT_DATE,

DAYS(CURRENT_DATE) AS DAYSOFDATE,

DAYS(CURRENT_TIMESTAMP) AS DAYSOFTIMESTAMP,

DAYS('1997-12-31') AS DAYSOFCHAR

FROM ...

CURRENT DATE DAYSOFDATE DAYSOFTIMESTAMP DAYSOFCHAR

1998-02-03 729423 729423 729389

Notice that the DAYS FUNCTION returns the number of days since 01/01/0001 PLUS 1! This coincides with the operation of the DATE FUNCTION which returns a date based on the number n -1 days since 01/01/0001. We will often use these two functions together when making date calculations.

Page 51: OracleVsDB2

04/08/23 51

DB2 DAY and DAYS Functions

Since the DAY function returns the day portion of a DB2 date or timestamp and the DAYS function converts a DB2 date or timestamp into an integer value representing one more than the number of days since January 1, 0001,

You can calculate the 'day of the week' using these functions where the returned values of 0 thru 6 represent Sunday through Saturday.

SELECT CURRENT DATE AS CUR_DATE, DAY(CURRENT DATE) AS CUR_DAY, DAYS(CURRENT DATE) AS CUR_DAYS, DAYS(CURRENT DATE) - (DAYS(CURRENT DATE) / 7 ) * 7 AS

DAY_OF_WEEK FROM FSDBA.ONE_ROW_TABLE;

CUR_DATE CUR_DAY CUR_DAYS DAY_OF_WEEK

1999-06-07 7 729912 1

Page 52: OracleVsDB2

04/08/23 52

DB2 HOUR

The HOUR function returns an integer representing the hour part of the field.

The argument must be a date, a timestamp, or a valid character string, representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

If the argument is a time, timestamp, or character string representation of either, the result is the hour part of the value, which is an integer between 0 and 24.

If the argument is a time duration or timestamp duration, the result is the hour part of the value which is an integer between -99 and +99. A nonzero result has the same sign as the argument.

Page 53: OracleVsDB2

04/08/23 53

DB2 HOUR

Example: Assume that a table named CLASSES contains a row for each scheduled class. Also assume that the class starting times are in a TIME column named STARTTM.

Select those rows in CLASSES that represent classes that start after the noon hour.

SELECT *

FROM CLASSES

WHERE HOUR(STARTTM) > 12;

Page 54: OracleVsDB2

04/08/23 54

DB2 JULIAN_DAY

The JULIAN_DAY function returns an integer representing the number of days from January 1, 4712 B.C. (the start of the Julian date calendar) to the date specified in the argument.

The argument must be a date, a timestamp, or a valid character string, representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Page 55: OracleVsDB2

04/08/23 55

DB2 JULIAN_DAY

Example 1: Using sample table DSN8610.EMP, set the integer host variable JDAY to the Julian day of the day that Christine Haas (EMPNO = ‘000010’) was employed (HIREDATE = ‘1965-01-01’).

SELECT JULIAN_DAY(HIREDATE)

INTO :JDAY

FROM DSN8610.EMP

WHERE EMPNO = ‘000010’;

The result is that JDAY is set to 2438762.

Page 56: OracleVsDB2

04/08/23 56

DB2 JULIAN_DAY

Example 2: Set integer host variable JDAY to the Julian day for January 1, 1998.

SELECT JULIAN_DAY(‘1998-01-01’)

INTO :JDAY

FROM SYSIBM.SYSDUMMY1;

The result is that JDAY is set to 2450815.

Page 57: OracleVsDB2

04/08/23 57

DB2 MICROSECOND

The MICROSECOND function returns the microsecond part of its argument.

The argument must be a date, a timestamp, or a valid character string, representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

If the argument is a timestamp or character string representation of a timestamp, the result is the microsecond part of the value which is an integer between 0 and 999999.

If the argument is a duration, the result is the microsecond part of the value which is an integer between -999999 and 999999. A nonzero result has the same sign as the argument.

Page 58: OracleVsDB2

04/08/23 58

DB2 MICROSECOND

Example : Assume that table TABLEX contains a TIMESTAMP column named TSTMPCOL and a SMALLINT column named INTCOL. Select the microseconds part of the TSTMPCOL column of the rows where the INTCOL value is 1234:

SELECT MICROSECOND(TSTMPCOL)

FROM TABLEX

WHERE INTCOL = 1234;

Page 59: OracleVsDB2

04/08/23 59

DB2 MIDNIGHT_SECONDS

The MIDNIGHT_SECONDS function returns an integer value in the range of 0 to 86400 that represents the number of seconds between midnight and the time specified by the argument.

The argument must be a date, a timestamp, or a valid character string, representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Page 60: OracleVsDB2

04/08/23 60

DB2 MIDNIGHT_SECONDS

Example : Find the number of seconds between midnight and 00:01:00, and midnight and 13:10:10. Assume that host variable XTIME1 has a value of ’00:01:00’, and that XTIME2 has a value of ’13:10:10’.

SELECT MIDNIGHT_SECONDS(:XTIME1), MIDNIGHT_SECONDS(:XTIME1)

FROM SYSIBM.SYSDUMMY1;

This example returns 60 and 47410. Because there are 60 seconds in a minute and 3600 seconds in an hour, 00:01:00 is 60 seconds after midnight ((60 * 1) +0), and 13:10:10 is 47410 seconds ((3600 * 13) + (60 * 10) + 10).

Page 61: OracleVsDB2

04/08/23 61

DB2 MIDNIGHT_SECONDS

Example : Find the number of seconds between midnight and 24:00:00, and midnight and 00:00:00.

SELECT MIDNIGHT_SECONDS(’24:00:00’), MIDNIGHT_SECONDS(’00:00:00’)

FROM SYSIBM.SYSDUMMY1;

This example returns 86400 and 0. Although these two values represent the same point in time, different values are returned.

Page 62: OracleVsDB2

04/08/23 62

DB2 MINUTE

The MINUTE function returns the minute part of its argument.

The argument must be a time, timestamp, time duration, timestamp duration, or a valid character string representation of a time or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

If the argument is a time, timestamp, or character string representation of either, the result is the minute part of the value which is an integer between 0 and 59.

If the argument is a time duration or timestamp duration, the result is the minute part of the value which is an integer between -99 and 99. A nonzero result has the same sign as the argument.

Page 63: OracleVsDB2

04/08/23 63

DB2 MINUTE

Example: Assume that a table named CLASSES contains one row for each scheduled class. Assume also that the class starting times are in the TIME column named STARTTM. Using these assumptions, select those rows in CLASSES that represent classes that start on the hour.

SELECT * FROM CLASSES

WHERE MINUTE(STARTTM) = 0;

Page 64: OracleVsDB2

04/08/23 64

DB2 MONTH

The MONTH function returns the month part of its argument.

The argument must be a date, timestamp, date duration, timestamp duration, or a valid character string representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

If the argument is a date, timestamp, or character string representation of either, the result is the month part of the value which is an integer between 1 and 12.

If the argument is a date duration or timestamp duration, the result is the month part of the value, which is an integer between -99 and 99. A nonzero result has the same sign as the argument.

Page 65: OracleVsDB2

04/08/23 65

DB2 MONTH

Example: Select all rows in the sample table DSN8610.EMP for employees who were born in May:

SELECT * FROM DSN8610.EMP

WHERE MONTH(BIRTHDATE) = 5;

Page 66: OracleVsDB2

04/08/23 66

DB2 QUARTER

The QUARTER function returns an integer in the range of 1 to 4 that represents the quarter of the year in which the date occurs. For example, the function returns a 1 for any dates in January, February, or March.

The argument must be a date, timestamp, or a valid character string representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Page 67: OracleVsDB2

04/08/23 67

DB2 QUARTER

Example: The following function returns 3 because August is in the third quarter of the year.

SELECT QUARTER(‘1996-08-25’)

FROM SYSIBM.SYSDUMMY1;

Page 68: OracleVsDB2

04/08/23 68

DB2 QUARTER

Using the sample table DSN8610.PROJ table, set the integer host variable QUART to the quarter of the year in which activity number 70 for project ‘AD3111’ occurred. Activity completion dates are recorded in column ACENDATE.

SELECT QUARTER(ACENDATE)

INTO :QUART

FROM DSN8610.PROJ

WHERE PROJNO = ‘AD3111’ AND ACTNO = 70;

QUART is set to 4.

Page 69: OracleVsDB2

04/08/23 69

DB2 SECOND

The SECOND function returns the seconds part of its argument.

The argument must be a time, timestamp, time duration, timestamp duration, or a valid character string representation of a time or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

If the argument is a time, timestamp, or character string representation of either, the result is the seconds part of the value, which is an integer between 0 and 59.

If the argument is a time duration or timestamp duration, the result is the seconds part of the value, which is an integer between -99 and 99. A nonzero result has the same sign as the argument.

Page 70: OracleVsDB2

04/08/23 70

DB2 SECOND

Example: Assume that RECEIVED is a TIMESTAMP column and that one of its values is the internal equivalent of ‘1988-12-25-17.12.30.000000’. Then, for this value:

SECOND(RECEIVED)

Returns the value 30.

Page 71: OracleVsDB2

04/08/23 71

DB2 TIME

The TIME function returns a time derived from its argument.

The argument must be a time, timestamp, or a valid character string representation of a time or timestamp.

The result of the function is a time. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

If the argument is a time, the result is that time.

If the argument is a timestamp, the result is the time part of the timestamp.

If the argument is a character string, the result is the time or time part of the timestamp represented by the character string.

Page 72: OracleVsDB2

04/08/23 72

DB2 TIME

Example: Assume that a table names CLASSES contains one row for each scheduled class. Assume also that the class starting times are in the TIME column named STARTTM. Using these assumptions, select those rows in CLASSES that represent classes that start at 1:30 P.M.

SELECT *

FROM CLASSES

WHERE TIME(STARTTM) = ’13:30:00’;

Page 73: OracleVsDB2

04/08/23 73

DB2 TIMESTAMP

The TIMESTAMP function returns a timestamp derived from its argument or arguments.

If only one argument is specified, it must be a timestamp, a valid string representation of a timestamp, a character string of length 8, or a character string of length 14.

A character string of length 14 must be a string of digits that represents a valid date and time in the form yyyymmddhhmmss where yyyy is the year, mm is the month, dd is the day, hh is the hour, mm is the minute, and ss is the seconds.

If only one argument is specified and it is a timestamp, the result is that timestamp. If only one argument is specified and it is a character string, the result is the timestamp represented by that character string. The timestamp represented by a string of length 14 has a microsecond part of zero.

Page 74: OracleVsDB2

04/08/23 74

DB2 TIMESTAMP

If both arguments are specified, the first argument must be a date or a valid string representation of a date and the second argument must be a time or a valid string representation of a time.

If both arguments are specified, the result is a timestamp with the date specified by the first argument and the time specified by the second argument. The microsecond part of the timestamp is zero.

If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Page 75: OracleVsDB2

04/08/23 75

DB2 TIMESTAMP

Example: Assume that table TABLEX contains a DATE column named DATECOL and a TIME column named TIMECOL. For some row in the table, assume that DATECOL represents 25 December 1988 and TIMECOL represents 17 hours, 12 minutes, and 30 seconds after midnight. Then, for this row:

TIMESTAMP(DATECOL, TIMECOL)

Returns the value ‘1988-12-25-17.12.30.000000’.

Page 76: OracleVsDB2

04/08/23 76

DB2 TIMESTAMP_FORMAT

The TIMESTAMP_FORMAT function returns a timestamp.

string-expression - An expression that returns any type of character string, except a CLOB, with a maximum length that is not greater than 255 bytes. Leading and trailing blanks are removed from the string and the resulting substring is interpreted as a timestamp using the format specified by format-string.

Format-string - An expression that returns a character string constant with a maximum length that is not greater than 255 bytes. Format-sring contains a template of how string-expression is to be interpreted as a timestamp value. Leading and trailing blanks are removed from the sting, and the resulting substring must be a valid template for a timestamp. The only valid format for the function is:

‘YYYY-MM-DD HH24:MI:SS’

Page 77: OracleVsDB2

04/08/23 77

DB2 TIMESTAMP_FORMAT

The TIMESTAMP_FORMAT function returns a timestamp.

– ‘YYYY-MM-DD HH24:MI:SS’

– Where:

– YYYY 4-digit year

– MM Month (01-12, January = 01)

– DD Day of month (01-31)

– HH24 Hour of day (00-24, when the value is 24,

the minutes and seconds must be 0).

– MI Minutes (00-59)

– SS Seconds (00-59)

Page 78: OracleVsDB2

04/08/23 78

DB2 TIMESTAMP_FORMAT

The result of the function is a timestamp. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Example: Set the character variable TVAR to the value of CREATEDTS from SYSIBM.SYSDATABASE if it is equal to one second before the beginning of the year 2000 ('1999-12-31 23:59:59'). The character string should be interpreted in the only format that can be specified for the function.

SELECT VARCHAR_FORMAT(CREATEDTS,

'YYYY-MM-DD HH24:MI:SS')

INTO :TVAR FROM SYSIBM.SYSDATABASE

WHERE CREATEDTS = TIMESTAMP_FORMAT

('1999-12-31 23:59:59','YYYY-MM-DD HH24:MI:SS');

Page 79: OracleVsDB2

04/08/23 79

DB2 WEEK

The WEEK function returns an integer in the range of 1 to 54 that represents the week of the year. The week starts with Sunday.

The argument must be a date, a timestamp or a valid character string representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

Page 80: OracleVsDB2

04/08/23 80

DB2 WEEK

Using sample table DSN8610.PROJ, set the integer host variable WEEK to the week of the year that project ‘AD2100’ ended.

SELECT WEEK(PRENDATE)

INTO :WEEK

FROM DSN8610.PROJ

WHERE PROJNO = ‘AD2100’;

The result of that :WEEK is set to 6.

Page 81: OracleVsDB2

04/08/23 81

DB2 YEAR

The YEAR function returns the year part of its argument.

The argument must be a date, timestamp, date duration, timestamp duration, or a valid character string representation of a date or timestamp.

The result of the function is a large integer. If the argument can be null, the result can be null; if the argument is null, the result is the null value.

If the argument is a date, a timestamp, or character string representation of either, the result is the year part of the value, which is an integer between 1 and 9999.

If the argument is a date duration or timestamp duration, the result is the year part of the value, which is an integer between -9999 and 9999. A nonzero result has the same sign as the argument.

Page 82: OracleVsDB2

04/08/23 82

DB2 YEAR

Example: From the table DSN8610.EMP select all rows for employees who were born in 1941.

SELECT *

FROM DSN8610.EMP

WHERE YEAR(BIRTHDATE) = 1941;

Page 83: OracleVsDB2

04/08/23 83

DB2 Review

Any questions about the DB2 Data types and Functions reviewed in this section?

Let’s now discuss the Oracle datatypes and function.

Page 84: OracleVsDB2

04/08/23 84

Oracle Datatypes

DATE CHAR(size) max 2000

characters NCHAR(size) max is 2000 NVARCHAR2(size) max

is 4000 bytes VARCHAR2(size) max

length is 4000 bytes VARCHAR max length is

4000 bytes ROWID

NUMBER(p,s) LONG RAW(size) LONG RAW BLOB (up to 4 gigabytes) CLOB (up to 4 gigabytes) NCLOB (up to 4

gigabytes) BFILE (references external

file up to 4 gigabytes) MLSLABEL

Page 85: OracleVsDB2

04/08/23 85

Oracle Number Datatypes

NUMBER(p,s) – stores zero, positive and negative fixed and floating-point numbers.

– P is precision – the total number of digits 1 to 38– S is the scale – the number of digits to the right of the decimal

point –84 to 127 -if a value exceeds the scale, Oracle rounds it

NUMBER (floating-point number for a decimal precision of 38 – no scale specified)

FLOAT (decimal precision 38 or binary precision 126) FLOAT(b) (binary precision b that can range from1 to

126)

Page 86: OracleVsDB2

04/08/23 86

Oracle Datatypes

LONG (store variable length character strings up to 2 gigabytes. - Only one LONG type can be in a table. LONG columns cannot be indexed.)

RAW(size) – This type is a variable-length datatype like the VARCHAR2 character datatype

LONG RAW – Used to store graphics, sound, documents, or arrays of binary data.

You can index RAW data, but not LONG RAW data.

Page 87: OracleVsDB2

04/08/23 87

Oracle Pseudocolumns

An Oracle pseudocolumn behaves like a table column, but is not

actually stored in the table.

You can select from pseudocolumns, but you cannot insert, update, or delete their values.

- NEXTVAL and CURRVAL- LEVEL- ROWID- ROWNUM

Page 88: OracleVsDB2

04/08/23 88

Oracle Sequences

A SEQUENCE is a schema object that can generate unique sequential values. These values are often used for primary and unique keys.

Use these pseudocolumns in SQL statements to refer to sequences: – CURRVAL (returns the current value of a sequence)– NEXTVAL (increments the sequence and returns the next value)

You must qualify CURRVAL and NEXTVAL with the name of the sequence: sequence.CURRVAL sequence.NEXTVAL

The following statement increments the ZSEQ sequence and returns the new value: SELECT zseq.nextval FROM dual;

The following statement selects the current value of ZSEQ, but does not change it’s value: SELECT zseq.currval from dual;

Page 89: OracleVsDB2

04/08/23 89

Oracle LEVEL Datatype

The pseudocolumn LEVEL is used for hierarchical queries in Oracle.

The LEVEL returns 1 for a root node, 2 for a child of a root, and so on.

A root node is the highest node within an inverted tree. A child node is any nonroot node. A parent node is any node that has children. A leaf node is any node without children.

Consult the Oracle manual for more information about coding hierarchical queries.

Page 90: OracleVsDB2

04/08/23 90

Oracle ROWNUM

The pseudocolumn ROWNUM returns a number indicating the order in which Oracle selects the row from a table or a set of joined rows.

The first row selected has a ROWNUM of 1, the second 1, and so on.

You can use ROWNUM to limit the number of rows returned by a query: SELECT * FROM table WHERE ROWNUM < 10;But – you can’t use the > because the conditions testing for ROWNUM

values greater than a positive integer are always false: this query returns no rows:

SELECT * FROM table WHERE ROWNUM > 10;

Page 91: OracleVsDB2

04/08/23 91

Oracle Number Functions

ABS(n)ACOS(n)ASIN(n)ATAN(n)ATAN2(n, m)CEIL(n)COS(n)COSH(n)EXP(n)FLOOOR(n)LN(n)LOG(m,n)

MOD(m,n)

POWER(m,n)

ROUND(n[,m])

SIGN(n)

SIN(n)

SINH(n)

SQRT(n)

TAN(n)

TANH(n)

TRUNC(n[,m])

Number functions accept numeric input and return numeric values.

Page 92: OracleVsDB2

04/08/23 92

Oracle Character Functions

Character functions accept character input and return either character or numeric values.

This first group of functions accept character input and return character values.

The second group of functions accept character input and return numeric values.

Page 93: OracleVsDB2

04/08/23 93

Oracle Character Functions – First Set

CHR(n)CONCAT(char1, char2)INITCAP(char)LOWER(char)LPAD(char,n[,char2])LTRIM(char[,set])NLS_INITCAP (n [,

nls_sort])NLS_LOWER (n [,

nls_sort])

NLS_UPPER (n [, nls_sort])REPLACE (char,

search_string [, replacement_string])

RPAD (char1, n[,char2])RTRIM (char [,set])SOUNDEX(char)SUBSTR(char, m[,n])SUBSTRB(char, m[,n])TRANSLATE(char,from,to)UPPER(char)

Page 94: OracleVsDB2

04/08/23 94

Oracle Character Functions – Second Set

ASCII(char)

INSTR(char1, char2 [,n[,m]])

INSTRB(char1, char2 [,n[,m]])

LENGTH(char)

LENGTHB(char)

NLSSORT(char [, nls_sort])

Page 95: OracleVsDB2

04/08/23 95

Oracle DATE / Functions

Date type includes timestamp YYYYMMDDHHMMSSDefault date format is DD-MON-YYDate Functions

- Day- Month- Year- To_Date- T0_Char- Add_Months- Months_Between

Subtracting one date from another date returns the number of days between them. The default time is 12:00:00AM(midnight).

Page 96: OracleVsDB2

04/08/23 96

Oracle Date Functions

Date functions operate on values of the DATE datatype.

All date functions return a value of DATE datatype, except the MONTHS_BETWEEN function, which returns a number.

Page 97: OracleVsDB2

04/08/23 97

Oracle Date Functions

ADD_MONTHS(d,n)LAST_DAY(d)MONTHS_BETWEEN(d,e)NEW_TIME(d,a,b)NEXT_DAY(d,char)ROUND (d [,fmt])SYSDATETRUNC(d [,fmt])

Page 98: OracleVsDB2

04/08/23 98

Oracle Date Truncation and Rounding

ROUND(d[,fmt])TRUNC(d[,fmt])

Format model for fmt in ROUND and TRUNC:

CC or SCCYYYY or SYYYYYYY or YY or YY,YYY or YEAR or SYEARQ

MONTH or MON or MM or RM

WW or IWWDDD or DD or JDAY or DY or DHH or HH12 or HH24MI

Page 99: OracleVsDB2

04/08/23 99

Oracle Conversion Functions

CHARTOROWID(char)CONVERT( char, dest_char_set

[,source_char_set ])HEXTORAW(char)RAWTOHEX(raw)ROWIDTOCHAR(rowid)TO_CHAR, date conversion TO_CHAR(d [, fmt [,

‘nlsparams’] ])TO_CHAR, number conversion TO_CHAR(n [, fmt [,

‘nlsparams’] ])

TO_DATE (char [, fmt [, ‘nlsparams’ ] ])

TO_MULTI_BYTE(char)

TO_NUMBER (char [, fmt [, ‘nlsparams’ ] ])

TO_SINGLE_BYTE(char)

TRANSLATE USING

TRANSLATE(text USING {CHAR_CS | NCHAR_CS })

Page 100: OracleVsDB2

04/08/23 100

Oracle Date Format Models for fmt of TO_CHAR and TO_DATE

SCC or CCYYYY or SYYYYYYY or YY or YIYYYIYY or IY or IY,YYYSYEAR or YEARRRBC or ADB.C. or A.D.QMMRMMONTHMON

WW or WIWDDD or DD or DDAYDYJAM or PMA.M. or P.M.HH or HH12HH24MISS or SSSSS-/ , . ; : (punctuation)“…text..” (string)

Page 101: OracleVsDB2

04/08/23 101

Oracle Date Format Prefixes and Suffixes

Prefix:FM (fill mode)FX (format exact)

Suffix:TH (ordinal number – 4th)SP (spelled out number - FOUR)SPTH and THSP (spelled out

ordinal number – FOURTH)

Note: When prefixes and suffixes are added to a date format, the case (upper, initial, or lower) is determined by the format element, not by the prefix or suffix. ‘ddTH’ produces “04th” not “04TH”

Date Format Case Control:

Uppercase:DAY, DY, MONTH, MON,

YEAR, AM, PM, A.M., A.m., P.M., P.m.

Initial Caps:Day, Dy, Month, Mon, Year, Am,

Pm

Lowercase:day, dy, month, mon, year, am,

pm

Page 102: OracleVsDB2

04/08/23 102

Oracle Number Formats for fmt of TO_CHAR

9

0

$

B

MI

S

PR

D

G

L

C

,

.

V

EEEE

RN or rn

DATE

Page 103: OracleVsDB2

04/08/23 103

Oracle SYSDATE Function

– The SYSDATE function returns the current date and time from Oracle.

– If you want to only manipulate the CURRENT DATE, and you are not selecting other columns from a table, you may issue a SELECT statement using the Oracle one row table:

SELECT SYSDATE FROM DUAL;

Note: This is the “DB2 way”

SELECT CURRENT DATE FROM SYSIBM.SYSDUMMY1

Page 104: OracleVsDB2

04/08/23 104

Oracle Conversion Functions

Conversion functions convert a value from one datatype to another.

Generally, the form of the function names follows the convention datatype TO datatype

The first datatype is the input datatype; the last datatype is the output datatype.

Page 105: OracleVsDB2

04/08/23 105

Oracle Other Single-Row Functions

DUMP (expr [, display_format [, start_position [, length ]]])

EMPTY_[B | C]LOB()

BFILENAME (‘directory’, ‘filename’)

GREATEST (expr [, expr] …)

LEAST (expr [, expr] …)

NLS_CHARSET_DECL_LEN(bytecnt, csid)

Page 106: OracleVsDB2

04/08/23 106

Oracle Other Single-Row Functions

NLS_CHARSET_ID(text)

NLS_CHARSET_NAME(n)

NVL (expr1, expr2)

UID

USER

USERENV (‘option’) (option can be ENTRYID, SESSIONID, TERMINAL, LANGUAGE, LABEL)

VSIZE (expr)

Page 107: OracleVsDB2

04/08/23 107

Oracle Group Functions

Default is to include all the candidate rows, but using DISTINCT causes the group function to use only the distinct values of the argument expression

AVG ([DISTINCT | ALL] n)COUNT(* | [DISTINCT | ALL] expr )MAX([DISTINCT | ALL] expr)MIN ([ DISTINCT | ALL] expr)STDDEV([DISTINCT | ALL] n)SUM([DISTINCT | ALL] n)VARIANCE ([DISTINCT | ALL] n)

* Note: more on grouping data later

Page 108: OracleVsDB2

04/08/23 108

Oracle Review

Any questions about the Oracle Data types and Functions reviewed in this section?

Let’s now discuss the way you combine data from multiple tables in Oracle and DB2.

Page 109: OracleVsDB2

04/08/23 109

Combining Tables

Oracle DB2-Join

-Outer join (+)

-Union, Union All

-Intersect, Minus

-Inner join

-Left Outer Join-Right Outer Join-Full Outer Join

-Union, Union All

Page 110: OracleVsDB2

04/08/23 110

JOIN Differences

Oracle DB2-Join, Outer join (+)

SELECT A.STUDENT_ID, B.EFFECTIVE_DATE , B.STOP

FROM FSDBA.STUDENT_MASTER A, FSDBA.STUDENT_HOLDS B WHERE

A.STUDENT_ID = B.STUDENT_ID(+) ;

-Inner Join, Left Outer Join, Right Outer Join, Full Outer JoinSELECT A.STUDENT_ID, B.EFFECTIVE_DATE , B.STOP

FROM FSDBA.STUDENT_MASTER AS A LEFT OUTER JOIN FSDBA.STUDENT_HOLDS AS B ON

A.STUDENT_ID = B.STUDENT_ID ;

Page 111: OracleVsDB2

04/08/23 111

Oracle Intersect & Minus

List the product and price only if it appears in both the queries - 25 rows.

SELECT product_id, max(list_price) from PRICE group by product_id INTERSECT SELECT product_id, max(actual_price) from ITEM group by product_id;

Report the products in the first query of prices that are not in the second query - 6 rows

SELECT product_id, max(list_price) from PRICE group by product_id MINUS SELECT product_id, max(actual_price) from ITEM group by product_id;

Page 112: OracleVsDB2

04/08/23 112

DB2 CASE – SQL Logic

SELECT A.COURSE_DEPT_NUMBER, B.COURSE_NUMBER, B.COURSE_IND, B.SECTION_NUMBER, A.COURSE_TITLE,

CASE COURSE_DEPT_NUMBER WHEN '4206' THEN 'ART‘

WHEN '4207' THEN 'ART HISTORY‘ WHEN '4208' THEN 'ART EDUCATION END

FROM FSDBA.COURSE_MASTER AS A

INNER JOIN FSDBA.CURRENT_COURSES AS

ON A.COURSE_NUMBER = B.COURSE_NUMBER AND A.COURSE_IND = B.COURSE_IND

WHERE YEAR = '1998' AND TERM = '1‘ AND COURSE_DEPT_NUMBER IN ('4206', '4207', '4208');

Page 113: OracleVsDB2

04/08/23 113

Tuning Considerations - Differences

Oracle DB2

When joining tables, enter the most restrictive predicates before the join predicates in the WHERE clause

When joining tables, enter the join predicates first – preferably in the ON clause - then enter most restrictive predicates first in the WHERE clause DB2 has filter factors on predicate types that help determine the cost of a queryCreate indexes for frequently used ORDER BY or GROUP BY or equality predicates

Page 114: OracleVsDB2

04/08/23 114

Optimizer Differences

Oracle – local server DB2 – NWRDC $$$-Major changes with 8i-Analyze (with compute or estimate)

- Rule-based - Optimizer_mode = rule-Cost-based - Optimizer_mode = all_rows, first_rows, or choose (default)

Optimizer hints-Or as hints in individual queries /*+all_rows*/ /*+first_rows*/

-Major changes with Version 6

- Runstats-New tables and enhancements to Optimize for n rows (assumes all rows mode)

-Optimizer hints-WHEN_OPTIMIZE (R, B, blank)-OPTHINT='hint-id'

Page 115: OracleVsDB2

04/08/23 115

DB2 Explain Table

Explain process - generates an Explain Report (51 columns in the DB2 Plan Table)

CREATE TABLE FSUDBA.PLAN_TABLE (QUERYNO INTEGER NOT NULL, QBLOCKNO SMALLINT NOT NULL, APPLNAME CHAR (8) FOR SBCS DATA NOT NULL, PROGNAME CHAR (8) FOR SBCS DATA NOT NULL, PLANNO SMALLINT NOT NULL, METHOD SMALLINT NOT NULL, CREATOR CHAR (8) FOR SBCS DATA NOT NULL, TNAME CHAR (18) FOR SBCS DATA NOT NULL, TABNO SMALLINT NOT NULL,

Page 116: OracleVsDB2

04/08/23 116

DB2 Explain Table

ACCESSTYPE CHAR (2) FOR SBCS DATA NOT NULL,

MATCHCOLS SMALLINT NOT NULL,

ACCESSCREATOR CHAR (8) FOR SBCS DATA NOT NULL,

ACCESSNAME CHAR (18) FOR SBCS DATA NOT NULL,

INDEXONLY CHAR (1) FOR SBCS DATA NOT NULL,

SORTN_UNIQ CHAR (1) FOR SBCS DATA NOT NULL,

SORTN_JOIN CHAR (1) FOR SBCS DATA NOT NULL,

SORTN_ORDERBY CHAR (1) FOR SBCS DATA NOT NULL,

SORTN_JOIN CHAR(1) FOR SBCS DATA NOT NULL,

SORTN_ORDERBY CHAR(1) FOR SBCS DATA NOT NULL,

SORTN_GROUPBY CHAR(1) FOR SBCS DATA NOT NULL,

SORTC_UNIQ CHAR(1) FOR SBCS DATA NOT NULL,

Page 117: OracleVsDB2

04/08/23 117

DB2 Explain Table

SORTC_JOIN CHAR(1) FOR SBCS DATA NOT NULL,

SORTC_ORDERBY CHAR(1) FOR SBCS DATA NOT NULL,

SORTC_GROUPBY CHAR(1) FOR SBCS DATA NOT NULL,

TSLOCKMODE CHAR (3) FOR SBCS DATA NOT NULL,

TIMESTAMP CHAR (16) FOR SBCS DATA NOT NULL,

REMARKS VARCHAR (254) FOR SBCS DATA NOT NULL,

PREFETCH CHAR(1) FOR SBCS DATA NOT NULL

WITH DEFAULT,

COLUMN_FN_EVAL CHAR(1) FOR SBCS DATA NOT NULL

WITH DEFAULT,

Page 118: OracleVsDB2

04/08/23 118

DB2 Explain Table

MIXOPSEQ SMALLINT NOT NULL WITH DEFAULT,

VERSION VARCHAR (64) FOR SBCS DATA NOT NULL WITH DEFAULT,

COLLID CHAR (18) FOR SBCS DATA NOT NULL WITH DEFAULT,

ACCESS_DEGREE SMALLINT DEFAULT NULL,

ACCESS_PGROUP_ID SMALLINT DEFAULT NULL,

JOIN_DEGREE SMALLINT DEFAULT NULL,

JOIN_PGROUP_ID SMALLINT DEFAULT NULL,

SORTC_PGROUP_ID SMALLINT DEFAULT NULL,

SORTN_PGROUP_ID SMALLINT DEFAULT NULL,

Page 119: OracleVsDB2

04/08/23 119

DB2 Explain Table

PARALLELISM_MODE CHAR(1) FOR SBCS DATA DEFAULT NULL,MERGE_JOIN_COLS SMALLINT DEFAULT NULL,CORRELATION_NAME CHAR(18) FOR SBCS DATA DEFAULT NULL,PAGE_RANGE CHAR (1) FOR SBCS DATA NOT NULL WITH DEFAULT,JOIN_TYPE CHAR (1) FOR SBCS DATA NOT NULL WITH DEFAULT,GROUP_MEMBER CHAR(8) FOR SBCS DATA NOT NULL WITH DEFAULT,IBM_SERVICE_DATA VARCHAR (254) FOR SBCS DATA NOT NULL WITH DEFAULT,WHEN_OPTIMIZE CHAR(1) FOR SBCS DATA NOT NULL WITH DEFAULT,QBLOCK_TYPE CHAR(6) FOR SBCS DATA NOT NULL WITH DEFAULT,

Page 120: OracleVsDB2

04/08/23 120

DB2 Explain Table

BIND_TIME TIMESTAMP NOT NULL WITH DEFAULT,

OPTHINT CHAR(8) FOR SBCS DATA NOT NULL

WITH DEFAULT,

HINT_USED CHAR(8) FOR SBCS DATA NOT NULL

WITH DEFAULT,

PRIMARY_ACCESSTYPE CHAR(1) FOR SBCS DATA NOT NULL

WITH DEFAULT)

IN DATABASE FSZDEVDB;

Page 121: OracleVsDB2

04/08/23 121

DB2 Explain Report

---------+---------+---------+---------+---------+---------+---------+----

QUERY BLOCK PLAN METH TNAME TABNO

-----+-------- -----+-------- -+---------+---------+---------+---------+---- --

00587 01 01 00 WWW_STUDENT_LOG 01

TYPE MC ANAME

---------+-------------+----

I 02 IXWSL04

--------+---------+---------+---------+---------+--

IO SNU SNJ SNO SNG SCU SCJ SCO SCG PF

--------+---------+---------+---------+---------+--

Y N N N N N N N N

Page 122: OracleVsDB2

04/08/23 122

Oracle Explain Plan Table

Explain Plan generates a Query Plan. We haven’t had to be concerned with the cost of Oracle queries, so we don’t run EXPLAINs on every Oracle sql satement, as we do with DB2. Explain plan table (24 columns) can be created with the utlxplan.sql script.

create table PLAN_TABLE (statement_id varchar2(30),timestamp date,remarks varchar2(80),operation varchar2(30),options varchar2(30),object_node varchar2(128),object_owner varchar2(30),object_name varchar2(30),object_instance numeric,

Page 123: OracleVsDB2

04/08/23 123

Oracle Explain Plan Table

object_type varchar2(30),

optimizer varchar2(255),

search_columns number,

id numeric,

parent_id numeric,

position numeric,

cost numeric,

cardinality numeric,

bytes numeric,

other_tag varchar2(255),

partition_start varchar2(255),

Page 124: OracleVsDB2

04/08/23 124

Oracle Explain Plan Table

partition_stop varchar2(255),

partition_id numeric,

other long,

distribution varchar2(30));


Recommended