• Save
DB2 DOCUMENT
Upcoming SlideShare
Loading in...5
×
 

DB2 DOCUMENT

on

  • 1,417 views

DB2 DOCUMENT

DB2 DOCUMENT

Statistics

Views

Total Views
1,417
Views on SlideShare
1,417
Embed Views
0

Actions

Likes
5
Downloads
76
Comments
4

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

14 of 4 Post a comment

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • Hi Nirmal,

    This very nice document.could u plz send the document to nandakumar.devaraj@gmail.com. Thanks in advance.


    Regards,
    Nandakumar
    Are you sure you want to
    Your message goes here
    Processing…
  • hi nirmal...could u plz send the document to mohan.phaneendra@gmail.com...thanks in advance
    Are you sure you want to
    Your message goes here
    Processing…
  • its vry nice document.
    can u send the document to adari.raviteja@gmail.com
    pls send ASAP
    Are you sure you want to
    Your message goes here
    Processing…
  • hi nirmal...could u plz send the document to mohan.phaneendra@gmail.com...thanks in advance
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    DB2 DOCUMENT DB2 DOCUMENT Document Transcript

    • DB2 DB2DB2 HO VER 0.3 1
    • DB2 Table of Contents ...........................................................................................................................................................1Table of Contents..............................................................................................................................................2INTRODUCTION TO DB2.............................................................................................................................5 1.1 Data Base Management System.............................................................................................................5 1.1.1) Relational Data Base Management System....................................................................................5 1.2) D B 2.....................................................................................................................................................5 1.2.1) Structured Query Language (SQL)................................................................................................5 1.3) How does a COBOL program use DB2 services..................................................................................6 1.3.1) Host Variables................................................................................................................................6 1.3.2) SQL Communication Area.............................................................................................................6 1.3.3) SQL statements...............................................................................................................................6 1.4) Handling a request.................................................................................................................................6 SYSTEM STRUCTURE.................................................................................................................................8 2.1) Major Components................................................................................................................................8 2.1.1) System Services..............................................................................................................................8 2.1.2) Locking Services............................................................................................................................8 2.1.3) Database Services...........................................................................................................................8 2.1.3.1 ) Precompiler............................................................................................................................9 2.1.3.2) Bind.........................................................................................................................................9 2.1.3.3) Runtime Supervisor.................................................................................................................9 2.1.3.4) Data Manager..........................................................................................................................9 2.1.3.5) Buffer Manager.......................................................................................................................9 2.1.4) Distributed Data Facility................................................................................................................9 2.2) Detailed Control Flow.........................................................................................................................10 2.2.1) Syntax Checking...........................................................................................................................11 2.2.2 ) Optimization................................................................................................................................11 2.2.3) Package Generation......................................................................................................................11 2.2.4.) Authorization checking...............................................................................................................11 2.3) Packages Plans and Collections..........................................................................................................12 DATA TYPES AND OPERATORS............................................................................................................13 3.1) Data Types...........................................................................................................................................13 3.1.1)Numeric data.................................................................................................................................13 3.1.2) String Data....................................................................................................................................13 3.1.3) Date/Time.....................................................................................................................................13 3.2) Operators and Expressions..................................................................................................................13 3.3) Scalar Functions..................................................................................................................................14 DB2 DATA STRUCTURES...............................................................................................................16 4.1) Introduction.........................................................................................................................................16 4.2) Database..............................................................................................................................................16 4.3 ) Table Spaces.......................................................................................................................................16 4.3.1 ) Simple Table Space.....................................................................................................................16 4.3.2) Partitioned Table Space................................................................................................................17 4.3.3) Segmented Table Space................................................................................................................17 4.4) DB2 Stored Tables..............................................................................................................................17 4.5) Index ...................................................................................................................................................18 4.6) Index Spaces........................................................................................................................................19 4.7) Storage Groups....................................................................................................................................19 4.8) Views...................................................................................................................................................19 4.9) Alias.....................................................................................................................................................20 4.10) The hierarchy of DB2 objects...........................................................................................................20INTEGRITY...................................................................................................................................................21 5.1) Introduction.........................................................................................................................................21 5.2) Primary key.........................................................................................................................................21 5.2.1) Definition......................................................................................................................................21DB2 HO VER 0.3 2
    • DB2 5.3) Entity Integrity....................................................................................................................................22 5.4) Foreign Keys.......................................................................................................................................22 5.4.1) Definition......................................................................................................................................22 5.5) Referential Integrity............................................................................................................................22 5.6) DELETE rules.....................................................................................................................................22STRUCTURED QUERY LANGUAGE........................................................................................................24 6.1) Introduction.........................................................................................................................................24 6.2) Types of SQL......................................................................................................................................24DATA DEFINITION LANGUAGE..............................................................................................................25 7.1) Introduction.........................................................................................................................................25 7.2) CREATE TABLE................................................................................................................................25 7.2.1 ) CREATE TABLE Using LIKE...................................................................................................26 7.3 ) ALTER TABLE.................................................................................................................................26 7.4 ) DROP TABLE...................................................................................................................................26 7.6 ) INDEXES...........................................................................................................................................27 7.6.1 ) CREATE INDEX........................................................................................................................27 7.6.2 ) DROP INDEX.............................................................................................................................27DATA MANIPULATION LANGUAGE......................................................................................................28 8.1 ) Introduction........................................................................................................................................28 8.2 ) SELECT.............................................................................................................................................28 8.2.1) Simple Retrieval...........................................................................................................................28 8.2.2) Qualified retrieval.........................................................................................................................29 8.2.3 ) Retrieval with Ordering..............................................................................................................29 8.2.4 ) Retrieval using BETWEEN and IN.............................................................................................29 8.2.5 )Retrieval using LIKE....................................................................................................................30 8.2.6) Retrieval involving NULL...........................................................................................................30 8.3 ) JOIN Queries......................................................................................................................................31 8.3.1 ) Simple Equijoin..............................................................................................................................31 8.3.3 ) Greater than Join.........................................................................................................................31 8.3.4 )Join query with additional conditions..........................................................................................31 8.3.5 ) Joining a table to itself.................................................................................................................31 8.4 ) SUBQUERIES...................................................................................................................................32 8.4.1 ) Simple Subquery.........................................................................................................................32 8.4.2) Correlated Subquery.....................................................................................................................32 8.4.3 ) Scalar Comparison Operator.......................................................................................................33 8.5 ) The Existential Qualifier....................................................................................................................33 8.6 ) Quantified Comparisons.....................................................................................................................33 8.7 ) Column Functions..............................................................................................................................34 8.8 ) GROUP BY........................................................................................................................................34 8.9 ) Use of HAVING.................................................................................................................................34 8.10 ) UNION.............................................................................................................................................35 8.11 ) INSERT............................................................................................................................................35 8.12 ) UPDATE..........................................................................................................................................36 8.13) DELETE............................................................................................................................................36THE CATALOG............................................................................................................................................37 9.1 ) Introduction........................................................................................................................................37 9.2) SYSTABLES.......................................................................................................................................37 9.3 ) SYSCOLUMNS ................................................................................................................................37 9.4 ) SYSINDEXES....................................................................................................................................37 9.5 ) QUERYING THE CATALOG..........................................................................................................37 9.6 ) ALIASES AND SYNONYMS..........................................................................................................38VIEWS............................................................................................................................................................39 10.1 ) Introduction......................................................................................................................................39 10.2) VIEW DEFINITION.........................................................................................................................39 10.3) RETRIEVAL Operations..................................................................................................................39 10.4) UPDATE Operations.........................................................................................................................40DB2 HO VER 0.3 3
    • DB2SECURITY AND AUTHORIZATION.........................................................................................................41 11.1 ) Introduction......................................................................................................................................41 11.3 ) GRANT AND REVOKE.................................................................................................................41 11.4 ) The GRANT OPTION.....................................................................................................................41EMBEDDED SQL..........................................................................................................................................42 12.1 ) Introduction......................................................................................................................................42 12.2 ) Preliminaries.....................................................................................................................................42 12.3 ) Operations Involving CURSORS.....................................................................................................43 12.3.1 )DECLARE .................................................................................................................................44 12.3.2 )OPEN .........................................................................................................................................44 12.3.3)FECTCH......................................................................................................................................44 12.3.4)CLOSE........................................................................................................................................44 12.3.5)WITH HOLD clause...................................................................................................................45TRANSACTION PROCESSING...................................................................................................................46 13.1) Introduction.......................................................................................................................................46 13.2) COMMIT and ROLLBACK.............................................................................................................46 13.3) Three CONCURRENCY PROBLEMS............................................................................................47 13.3.1)The LOST UPDATE problem.....................................................................................................47 13.3.2)The UNCOMMITED DEPENDENCY problem........................................................................47 13.3.3)The INCONSISTANT ANALYSIS problem..............................................................................48 13.4) Solution. ...........................................................................................................................................50 13.5) Locking Facilities..............................................................................................................................51 13.5.1) LOCK TABLE...........................................................................................................................51 13.5.2) The ISOLATION parameter......................................................................................................51 13.5.2.1)CURSOR STABILITY........................................................................................................51 13.5.2.2) REPETABLE READ..........................................................................................................51 13.5.3)LOCK SIZE.................................................................................................................................52 13.5.4) The ACQUIRE/RELEASE parameters......................................................................................52 13.6) DEADLOCK.....................................................................................................................................52DYANAMIC SQL..........................................................................................................................................53 14.1)Introduction........................................................................................................................................53 14.2) PREPARE/EXECUTE......................................................................................................................53 14.3) EXECUTE IMMEDIATE.................................................................................................................54ADMINISTRATION FACILITIES...............................................................................................................55 15.1) Introduction.......................................................................................................................................55 15.2) DB2 INTERACTIVE INTERFACE.................................................................................................55 15.2.1) SPUFI.........................................................................................................................................56 15.2.2) DCLGEN....................................................................................................................................56 15.2.3)Program Preparation....................................................................................................................56 15.2.4)Precompile...................................................................................................................................56 15.2.5) Bind / Rebind / Free...................................................................................................................56 15.2.5) RUN............................................................................................................................................57 15.2.6) DB2 Commands ........................................................................................................................57 15.2.7)Utilities........................................................................................................................................57 15.2.8)Catalog Visibility........................................................................................................................57 15.2.9) DB2I Defaults.............................................................................................................................57 15.2.10) EXIT.........................................................................................................................................57 15.3) EXPLAIN..........................................................................................................................................57 15.4) Database utilities...............................................................................................................................58DB2 HO VER 0.3 4
    • DB2 INTRODUCTION TO DB21.1 Data Base Management System A Data Base, which consists of some collection of persistent data that is used by the applicationsystems of some given enterprise. These are designed and managed to store large quantities of information.A Data Base Management System (DBMS) is a software package that manages the data stored indatabases. Data base approach will help to maintain data independence, avoid redundancy, inconsistencyand also provide better security. Thus DBMS provide an environment that is both convenient and efficientto use in retrieving and storing data base information.1.1.1) Relational Data Base Management System A Relational Data Base System presents all information in form of tables. Tables consist of rowsand columns. This concept is in close correspondence with mathematical concept of relations and hence thename.1.2) D B 2 DB2 an abbreviation for DataBase 2, is a Relational DataBase Management System(RDBMS) thatruns on IBM mainframe computers under MVS operating system. Prior to DB2 there was a hierarchic DataBase Management System (DBMS) for MVS called IMS (Information Management System). DB2 is oneof the most successful DBMS for MVS.1.2.1) Structured Query Language (SQL) This is the language by which request to DB2 are made.DB2 supports SQL, which providesfacilities for application programming as well as for data base management. SQL is both ANSI and ISOstandard. In fact it is the language used to access all relational databases. The statements, which make up SQL are commonly categorized in to Data Definition Language(DDL), Data Manipulation Language (DML), and Control statements. DBA uses DDL for defining variousobjects. Application programmers uses DML to work with DB2. Control statements are used to handleauthorization to various resources.DB2 HO VER 0.3 5
    • DB21.3) How does a COBOL program use DB2 services When DB2 is used through COBOL, SQL statements are to be included in the program. Followingare the three things that are to be included when using DB2 in COBOL programs Host variables, SQLcommunication Area, and SQL statements.1.3.1) Host Variables These are used for retrieving and putting data into DB2 tables. Host variables have to be definedin the program, which is used to receive the data DB2 returns and from which DB2 can get the data toupdate tables. They are called host variables because they reside in the storage owned by host program.1.3.2) SQL Communication Area DB2 provides the feedback about the success of each operation by Storing information in SQLCA.So in COBOL program SQLCA have to be included.1.3.3) SQL statements SQL statements actually does the data base work required by the program. SQLstatements can be embedded into a programming language. These SQL statements are not understood by C,COBOL etc. So before compiling the program, a preliminary process (Precompiler) must pull out the SQLstatements.1.4) Handling a requestDB2 HO VER 0.3 6
    • DB2 When a request to update the database comes to DB2 from the user. The application managerpasses the userid to DB2. DB2 will check for the authorization of the user. It maintains a catalog to seewhether the user is authorized. If not authorized DB2 will return a code indicating it has refused the requestdue to unauthorized user id. There are multiple concurrent processing handled by DB2. To avoid a possibleconfusion DB2 puts a lock on data. DB2 maintains a log which keeps record about everything that is doneto the data. DB2 always writes to the log before writing to the data after the successful updation it willmark a COMMIT to the log. Since the update is completed DB2 releases the lock and the operationcompleted successfullyDB2 HO VER 0.3 7
    • DB2 SYSTEM STRUCTURE2.1) Major Components There are four major components, each of which divides into a number of subcomponents. Theyare• The system service component• The locking services• The database services• The distributed data facility component2.1.1) System Services The system services supports the system operations. This handles DB2 system related tasksincluding controlling connections to other MVS subsystems, handling system startup, shutdown andoperator communications, managing system log, gathering system-wide statistics, performance auditingand accounting informations etc. The system logs are data sets used to record the information for recovering the user and systemdata in the event of system failure. The logs are of two types; active log and archive log.2.1.2) Locking Services Locking services are provided by an IMS Resource Lock Manager (IRLM), which is a general-purpose locking manager. This is used to control the concurrent access to DB2 data.2.1.3) Database Services This is used to retrieval and updation of database i.e. implements the functions of SQL. Thisincludes five subcomponents. They are:• Precomipler• Bind• Runtime Supervisor• Data Manager• Buffer ManagerDB2 HO VER 0.3 8
    • DB22.1.3.1 ) Precompiler This is a preprocessor for host programming languages. Precompiler analyses the host languagesource module, stripping out the SQL statements and replace them by host language CALL statements. Theprecompiler produces two output files. The first is intermediate source program, Which contains theCOBOL statements. The original SQL statements in the program will be commented out so that COBOLcompiler ignores them. Second file produced by precompiler called Data Base Request Module (DBRM).2.1.3.2) Bind This is used to bind a DBRM to produce a package and also it binds together a list of packages toproduce an application plan. The package can be thought as a set of internal control structures, representingthe compiled form of original SQL statements in the DBRM. Collections are a set of logically related packages, which does not have a physical existence. Allthe packages used in a given application are assigned to the same collection. Host language compiler,which compiles the modified source code to produce the Object module for the host language.2.1.3.3) Runtime Supervisor This is resident in the main storage during the execution and it overseas the execution of job.When the SQL statements are executed, control first goes to runtime supervisor, which uses the controlinformations in the plan to request appropriate operations on the part of Data manager.2.1.3.4) Data Manager This is a very sophisticated access method. It performs the normal access method functions likesearch, retrieval etc. It also invokes the other system components to invoke locking ,I/O operations etc.2.1.3.5) Buffer Manager This is a component responsible for transferring data between external storage and memory. Ituses several methods to optimize its performance so that amount of I/O can be reduced.2.1.4) Distributed Data Facility This component called DDF, which provide Distributed database support. It has to work withother subsystems to attain this facility.DB2 HO VER 0.3 9
    • DB22.2) Detailed Control FlowThis section will explain how to prepare and execute DB2 embedded application program. After preparingthe program with embedded DB2 statements it has to be precompiled first. This is because the hostlanguage compiler does not understand the embedded DB2 statements. The precompiler replaces all SQLstatements with CALL statements. The SQL statements will be commented out. Precompiler uses SQLstatements to build a DBRM, which is stored in a partitioned dataset. DBRM contains edited form of SQLDB2 HO VER 0.3 10
    • DB2statements together with some additional informations. So the output of precompilation is modified sourcecode and DBRM. Modified source code is compiled and linkedited in normal way by using the host language compiler.Bind is really an optimizing compiler. It will convert SQL statements into optimized internal form. Its inputis DBRM and output is a package. The major functions performed by bind are• Syntax checking• Optimization• Package generation• Authorization checking2.2.1) Syntax Checking Bind examines the SQL statements for syntax errors.2.2.2 ) Optimization Bind includes an optimizer to choose for each SQL statement an optimal access strategy forimplementing that statement. For example when the user wants to access some data the access path isselected by the optimizer. Bind will generate a code that is tightly bound to optimizer’s choice of path.2.2.3) Package Generation This is the actual process of building the package.2.2.4.) Authorization checking Bind checks for authorization. It check for whether the user is allowed to perform the operationsrequested on DBRM and also whether allowed to assign packages applicable to packages collection. Bind also performs the plan bind. The input of this process is a list of packages. Output is anapplication plan, which is stored in DB2 directory. This also done some authorization checking such aswhether the owner is authorized to execute all application packages. At the time of execution both load module (from modified source code) and application plan (fromDBRM) to be used. The load module is loaded to memory and it stars execution. When it reaches the firstcall to DB2 language interface module it passes the control to runtime supervisor. The runtime supervisorretrieves the application plan from DB2 directory and loads it into memory. Then the control is passed toDB2 HO VER 0.3 11
    • DB2Data manager, which performs the necessary operations on the data and passes the result back to theprogram.2.3) Packages Plans and Collections Package is a compiled form of DBRM. Plan is a list of packages. Plan may consist of more thanone packages. So if a given DBRM has to be recompiled, the appropriate package has to be bind not theentire plan. If multiple plans involve the same DBRM, that can be compiled once and the correspondingpackage can be referenced multiple times instead of binding the DBRM each time. Collections is a logical grouping of packages. It is even possible to add a new package to a planwithout binding it. This is by using the concept of collections. When a plan is bound the input can be acollections. This is equivalent to adding all packages in that collection. Including packages in the collectioncan be done after plan is bound. Whatever packages in the collection while plan is executed is considered tobe a part of the plan.DB2 HO VER 0.3 12
    • DB2 DATA TYPES AND OPERATORS3.1) Data TypesDB2 supports the following scalar data types3.1.1)Numeric dataINTEGER Full word binary integer, 31 bits and signSMALLINT Half word binary integer, 15 bits and signDECIMAL(p,q) Packaged decimal with p digit and sign. Decimal point at q digit from rightFLOAT(p) Floating point number3.1.2) String DataCHARACTER(n) Fixed length string of ‘n’ 8bit characters. Maximum value of n is 254VARCHAR(n) Varying length string up to ‘n’ 8bit characters Max value of ‘n’ is 4K/32KGRAPHIC(n) Fixed length string of ‘n’ 16bit characters Max value of ‘n’ is 127VARGRAPHIC(n) Varying length string upto ‘n’ 16bit characters. Max value of ‘n’ is 24K/16K3.1.3) Date/TimeDATE Eight unsigned packed decimal occupying 4 bytes YYYYMMDDTIME 6 unsigned packed decimal occupying 3 bytes HHMMSSTIMESTAMP Sequence of 20 unsigned packed decimal digits YYYYMMDDHHMMSSNNNNNN3.2) Operators and ExpressionsDB2 provide a number of scalar operators that can be used in making scalar expressions.DB2 HO VER 0.3 13
    • DB2Numeric Operators DB2 supports numeric operators such as +,-,/,* These can be used with date,time,timestamp etcComparisons =,>,<.<>,>=,<=, Even two dates can be comparedConcatenation || This is used to concatenate two character or two graphic strings A scalar expression consists of scalar operands to produce another scalar value. These can appearin SQL statements with SELECT, HAVING, WHERE etc. There are six types of scalar expressions. Theyare Numeric, Character, Graphic, date, time,and timestamp.E.g. Numeric Expression STATUS WEIGHT = WEIGHT*23 E.g. Character string PNAME INITIALS || LASTNAME3.3) Scalar Functions Scalar functions applied to a single column or expressions and operate on single value. The resultwill be transformed version of column or expression. These can be executed in theSELECT,WHERE,HAVING etc.CHAR Converts DB2 time,date,timestamp,decimal to characterDATE Converts a value to a DB2 date. It can be a positive integer, timestamp etc.DAY Returns day portion of DB2 timestampDAYS Converts DB2 timestamp into number of days since jan1 0001DECIMAL Converts numeric value to a decimalDIGITS Converts a number to a string of digits. Truncate - signFLOAT Converts numeric to a floating point valueHEX Converts a value to hexadecimalHOUR Returns hour portion of time, timestamp etc.INTEGER Converts a number to an integer. Truncate decimal pointLENGTH Returns length of any column which may be nullNULLIF Returns null if two expressions are equal. If not return first expressionMICROSECOND Returns microsecond portion of timestampMINUTE Returns minute portion of a time stampMONTH Returns the month portion of a time stampSECOND Returns the second portion of timestampSTRIP Removes leading and trailing blanks from a scalar expressionSUBSTR Returns a specified portion of a character stringDB2 HO VER 0.3 14
    • DB2TIME Converts a value to a DB2 timeVARGRAPHIC Converts a character string to a graphic stringYEAR Returns year portion of date, timestamp etc.VALUE For a null column returns a value instead of nullDB2 HO VER 0.3 15
    • DB2 DB2 DATA STRUCTURES4.1) Introduction In MVS environment, the relational database manager itself is considered as a subsystem. Foreach subsystem there are some system objects. DB2 data structures are treated to as DB2 objects. EachDB2 object is used to support the structure of the data being stored. This section will detail about variousDB2 objects.4.2) Database A database is a collection of logically related objects such as tables together with their associatedindex and the spaces which contain these tables, and index. It thus consists of a set of tablespaces togetherwith a set of index spaces. For a stored tables all its associated index must be wholly contained in a singledatabase. Objects are grouped together in a database for operational reasons. Operator can make thedatabase available or unavailable for processing. Database is logical and the data can be contained in singledisk or a set of disk.4.3 ) Table Spaces A table space can be thought as a logical (Not in physically adjacent areas) address space use tohold tables. It is at the tablespace level that storage is actually allocated. The maximum size of tablespace is64GB and it is divided into pages, which are written to or read from a DASD at the time of an operation.There is no limit for number of tablespace in a database or number of databases. Table Space can bedivided into three types• Simple• Partitioned• Segmented4.3.1 ) Simple Table Space A simple table space can contain one or more stored tables but one is the best option. Since morethan one logically related tables are present, records for different tables can be clustered together toimprove the access times. But in the case of sequential search the system will be slowed down as it has toDB2 HO VER 0.3 16
    • DB2search not only the stored records of the required table but also of the other tables that happen to be mixedup with first one. So one table per table space is the most satisfactory arrangement for simple table space.4.3.2) Partitioned Table Space This is used to store very big tables with large number of rows. In such tables it is operationallydifficult to handle the entire table as one unit. A partitioned table space contains one stored table,partitioned. Individual partitions are independent so that they can be recovered independent of each other.4.3.3) Segmented Table Space This also contains more than one stored tables. But here it will not support cross table clusteringi.e. do not allow the records of different tables to be interleaved on a single page as in simple table space.Table space is divided in to segments. No segment is allowed to contain records from more than one table.Sequential access to a particular table is more efficient. This can handle variable length records. So theseare more efficient as compared to simple table space.4.4) DB2 Stored Tables This is a stored representation of a base table. It consists of a set of stored records, one for eachdata row in the base table. A stored record is not identical to corresponding row of base table. It consist of abyte string which include• A stored record prefix containing control information• Up to N storage fields where ‘N’ is the number of columns of base table• A length prefix for the field which are of variable length• A null indicator prefix indicating nulls• An encoded value of the actual dataThere is no gap between the fields. The varying fields contain only the actual value. All internally storedrecords are addressed by RID or Record ID. RIDs are unique within the containing table space. From thefigure shown RID contain two parts: The page number and the byte offset from the bottom of the page toidentify the required slot.DB2 HO VER 0.3 17
    • DB24.5) Index An index can be defined as a DB2 tool used to locate the row that contains a given value. When aspecific row is required DB2 reads the index finds the pointer to that row and then read the page containsthe row. So Indexing provides uniform and predictable performance for retrieval operations. Index consist of three levels: a root page, intermediate pages, leaf pages. The leaf level contains anentry for each distinct value for the indexed field. Intermediate level contains an entry for each leaf page.Thus root page, intermediate page, leaf page provides a direct and fast access to indexed data. A storedtable can have any number of associated index and hence any number of logical ordering on it.DB2 HO VER 0.3 18
    • DB24.6) Index Spaces An index space is used to store an index. The correspondence between index and index space isalways one to one. An index space is created automatically when an index is created. Index spaces can berecognized and recovered independently.4.7) Storage Groups A storage group is a named collection of DASD volumes. Each table space and an index spacenormally have a storage group associated with it. Within each storage group data is stored by using VSAMLinear Data Set (LDS).4.8) Views This is a virtual table that consisting of SQL SELECT statements to access data from one or moretables. A view never stores the data. When user wants to access the view, SQL statement that defines theview will be executed and the user gets the result. So these can be called as a users table whereas the datareside in the actual tables on which the view is based. This provides a simplified coding and more securityas the data, which are not required, will be omitted from the view.DB2 HO VER 0.3 19
    • DB24.9) Alias A locally defined name for table or a view, in the same local DB2 system or in a remote DB2system. Alias gives DB2 location independence because an alias can be created for a table at a remote site,thereby freeing the user from specifying the site that contains the data. Alias can be used as a global onebecause it can be used by anyone.4.10) The hierarchy of DB2 objects. The following figure demonstrates the hierarchy of various DB2 objects.DB2 HO VER 0.3 20
    • DB2 INTEGRITY5.1) Introduction The term integrity is used in database contexts to refer to accuracy, validity or correctness of datain the database. This is very important and is handled by system than by user. Integrity constraints to bespecified during database definition. This will be stored in catalog and will be used by the system duringvarious operations. DB2 includes two general integrity rules. These are brought into picture using two keyscalled primary key and foreign key.5.2) Primary key Primary key is a unique identifier for the table. Even that can be composite i.e. more columns canbe combined together to form a unique key. But in a table there can be more than one unique identifier. Inthat case table has multiple candidate keys out of which only one will be the primary key and the otherscalled alternate keys. Primary keys are very important as it provide the basic row level addressingmechanism. Thus by using the primary key system can pinpoint some specific rows in a required table.5.2.1) Definition Primary key can be defined when the base table created through CREATE TABLE or can beadded to an existing table through ALTER TABLE. Every column participating in primary key must beexplicitly declared as NOT NULL. After creating the primary key appropriate unique index has to bedefined. This index called primary index enforces the uniqueness of primary key. To an existing table primary key can be added using ALTER TABLE command. A suitableunique index must already exist for ALTER TABLE to succeed, and also the column for primary keyshould be declared as NOT NULL.E.g. CREATE TABLE NTP (EMPNO CHAR(5) NOT NULL, EMPNAME CHAR(20) , PRIMARY KEY (EMPNO)); CREATE UNIQUE INDEX IND1 ON NTP(EMPNO);It is also possible to remove the primary key from an existing table.E.g. ALTER TABLE NTP DROP PRIMARY KEY;DB2 HO VER 0.3 21
    • DB25.3) Entity Integrity Entity integrity rule specifies that Primary key should be unique and it should not accept a NULLvalue. This is because these values serve to identify the entire row. In the case of composite primary keyeach individual value of the primary key should be wholly non null.5.4) Foreign Keys A foreign key is a column in one table that matches values to the primary key in another table. Theforeign key can also be null. Each value of the foreign key must match with a corresponding value ofprimary key. The table, which contains the foreign key, is called referencing table and the table whichcontain the corresponding primary key is called referenced or target table.5.4.1) Definition The foreign key can be defined when the base table is created using CREATE TABLE. It can alsobe added to or deleted from an existing table using ALTER TABLE. It is not necessary to create an indexon foreign key.E.g. CREATE TABLE EMP (EMP# CHAR(5) NOT NULL, EMPNAME CHAR(20) , PRIMARY KEY (EMP#) FOREIGN KEY FK1 (EMPNO) REFERENCES NTP); ALTER TABLE EMP DROP FOREIGN KEY FK1;5.5) Referential Integrity Referential constraint limits a set of foreign key values to a set of primary key values. Soreferential integrity enforces referential constraints. So the database must not contain an unmatched foreignkey value.5.6) DELETE rules. When a row contains the primary key is deleted necessary changes to be occurred for the matchingforeign keys. There are three options for this: CASCADE, SET NULL, RESTRICT• CASCADE when the target row is deleted from target table the row which contain the foreign key of referencing table also get deleted.DB2 HO VER 0.3 22
    • DB2• SETNULL When the target row is deleted the foreign key will be set to null.• RESTRICT The delete is restricted.This rule to be specified when defining the foreign key. Default is RESTRICT.E.g. CREATE TABLE EMP (EMP# CHAR(5) NOT NULL, EMPNAME CHAR(20) , PRIMARY KEY (EMP#) FOREIGN KEY FK1 (EMPNO) REFERENCES NTP ON DELETE CASCADE);DB2 HO VER 0.3 23
    • DB2 STRUCTURED QUERY LANGUAGE6.1) Introduction SQL is used by DB2 for operating on database. In this programmer has to specify what data hewant to retrieve and not how to do it. In SQL a single request can be formulated in a number of differentbut functionally equivalent ways. For example a nested query can always be converted to an equivalentjoin. SQL is a nonprocedural language. An SQL manipulation statement can operate on a table and theresult can be obtained on another table. One retrieval statement can retrieve multiple rows or one updatecan update can change multiple rows. This feature is called relational closure, which makes relationaldatabase much easier.6.2) Types of SQL SQL can be categorized based on functionality. On the basis of this, it is divided into three• The Data Control Language(DCL) provide the control statements that govern data security• The Data Definition Language(DDL) for creating and maintaining the data structure• The Data Manipulation Language(DML) for accessing and modifying the data Another way to classify SQL is by execution type. There are two types• The production where the SQL is planned and executed. Here all the requirements are well known• The ad-hoc where its undefined until an immediate need is identified Another classification is based on the existence.• Embedded SQL where the SQL statements are embedded in program• Stand-alone where only SQL statements are used. No program required SQL can also be categorized based on Dynamism• Dynamic SQL is that which is changeable at runtime. This can be either typed from the terminal at runtime or can be constructed by application programs algorithms• Static SQL is unchangeable at runtime. This will be embedded in application programs.DB2 HO VER 0.3 24
    • DB2 DATA DEFINITION LANGUAGE7.1) Introduction Data definition statements can be divided into two broad classes: Logical and Physical. The enduser will be normal using the logical statements. The DDL statements are CREATE, ALTER, DROP. Thefollowing table summarizes these operations on various DB2 objects DB2 Objects CREATE ALTER DROP Storage Group Y Y Y Database Y N Y Tablespace Y Y Y Table Y Y Y Index Y Y Y View Y N YIn this section logical statements are covered in detail. The principal logical DDL statements areCREATE TABLE, ALTER TABLE, DROPTABLE,CREATE VIEW, DROP VIEW, CREATEINDEX,DROP INDEX.7.2) CREATE TABLE This creates the base table. A base table consists of rows and columns to define physicalcharacteristics of data to be stored. The format is CREATE TABLE <table name> (column definition [, column definition]... [, Primary key definition] [,alternate key definition] [,foreign-key definition ]) [,other parameters];The table name which is user defined gives a unique identity to the table. The column definition can takethe form column data-type [NOT NULL/NOT NULL WITH DEFAULT/UNIQUE]The square brackets are used to show that they are optional. System will take the default values whereapplicable.E.g. CREATE TABLE S ( S# CHAR(5) NOT NULL, SNAME CHAR(20) NOTNULL WITH DEFAULT, STATUS SMALLINT NOT NULL WITH DEFAULT, CITY CHAR(15) ,DB2 HO VER 0.3 25
    • DB2 PRIMARY KEY (S#));Eg2. CREATE TABLE P ( P# CHAR(6) NOT NULL, PNAME CHAR(20) NOTNULL WITH DEFAULT, COLOR CHAR(6) NOTNULL WITH DEFAULT, WEIGHT SMALLINT NOT NULL WITH DEFAULT, CITY CHAR(15) , PRIMARY KEY (P#));Eg3. CREATE TABLE SP ( S# CHAR(5) NOT NULL, P# CHAR(6) NOT NULL, QTY SMALLINT);7.2.1 ) CREATE TABLE Using LIKE A new table can be created with the same shape as some existing table using the option LIKE. Butthe new table created will not inherit Primary key, Alternate key, Foreign key definitions.E.g. CREATE TABLE SCOPY LIKE S;This is same as CREATE TABLE SCOPY ( S# CHAR(5) NOT NULL, SNAME CHAR(20) NOTNULL WITH DEFAULT, STATUS SMALLINT NOT NULL WITH DEFAULT, CITY CHAR(15));7.3 ) ALTER TABLE An existing table can be altered by using ALTER TABLE. For example a new column can beadded to an existing table.E.g. ALTER TABLE NTP ADD EMPLEVEL SMALLINT;This statement adds a column to the extreme right in the table NTP. This should not be declared asNOTNULL. But ALTER cannot change the width or data type of an existing column.7.4 ) DROP TABLE An existing table can be deleted using this option. The specified table is deleted from the system.All indexes, views etc defined on this table will be dropped.E.g. DROP TABLE NTP;DB2 HO VER 0.3 26
    • DB27.6 ) INDEXES Indexes can be created and dropped using DDL statements. Any number of indexes can be createdon a base table. The two DDL statements are CREATE INDEX and DROP INDEX.7.6.1 ) CREATE INDEX The format for create is as followsCREATE [UNIQUE] INDEX <index name>ON <table name> (column[order],column[order);The order refers to the order of the column, which has two values ASC,DESC represents ascending anddescending order. Default is ASC. Once the index is created it is maintained by the data manager.E.g. CREATE UNIQUE INDEX IND1 ON EMP (EMP# DESC);7.6.2 ) DROP INDEX This is used to delete an index and the corresponding entry will be deleted from the catalog.E.g. DROP INDEX IND1;DB2 HO VER 0.3 27
    • DB2 DATA MANIPULATION LANGUAGE8.1 ) Introduction There are four SQL statements for manipulating the data that has been loaded into the tables. Theyare SELECT,INSERT,UPDATE,and DELETE. SELECT retrieves the data,UPDATE changes the existingvalues, DELETE removes rows from the table, INSERT adds new rows into the table. This section gives adetailed description of all the four DML statements.8.2 ) SELECT SELECT is used to retrieve the data from the base table. The format isSELECT [ALL/DISTINCT] <column names>FROM <table name>[WHERE <conditional expression>][GROUP BY <column names> ][HAVING <conditional expression>][ORDER BY <column names>];The result of the above query will be another table derived from the base table.8.2.1) Simple RetrievalE.g. SELECT EMP#, EMPNAME, EMPLEVEL FROM EMP;This query selects all the rows of table EMP. An alternate way of selecting the entire table is using *E.g. SELECT * FROM EMP;To retrieve some specific columns that column names can only me mentioned in SELECTE.g. SELECT EMP# FROM EMP;To eliminate duplicate rows DISTINCT can be used in SELECT statementE.g. SELECT DISTINCT EMPNAME FROM EMP;To retrieve computed values, it can be given on SELECT statement.E.g. SELECT EMP#, EMPLEVEL + 1 FROM EMP; The resultant table will be containing thecomputed value.DB2 HO VER 0.3 28
    • DB28.2.2) Qualified retrievalA specific record can also be retrieved using some conditions. The conditional expression followingWHERE can be simple comparison or multiple comparisons.E.g. SELECT * FROM EMP WHERE EMP# = ‘1001’ ;E.g2. SELECT * FROM EMP WHERE EMP# = ‘1000’ AND EMPNAME = ‘UMA’ ;8.2.3 ) Retrieval with Ordering Resultant table obtained as a result of a query can be in an ordered form. For this ORDER BY hasto be used with SELECT.E.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMPLEVEL = ‘7’ ORDER BY EMPNAME DESC;Here the required sequence is arranged. The ORDER BY can take either ASC or DESC. ASC is default.E.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMPLEVEL = ‘7’ ORDER BY 2 , DESC;Here this will produce the same result as above . 2 refer to second column of the resultant table.8.2.4 ) Retrieval using BETWEEN and INTo retrieve the values between some specified ranges BETWEEN is used.E.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMP# BETWEEN ‘7000’ AND ‘8000’ ;The same result can be produced by another queryE.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMP# >= ‘7000’ AND EMP# <= ‘8000’ ;NOT BETWEEN can also be used to exclude a specific range. IN is used in the similar fashion where theindividual comparisons ORed.E.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMP# IN ( ‘8000’, ‘8001’, ‘8002’);This will produce the same result asE.g. SELECT EMP#,EMPNAMEDB2 HO VER 0.3 29
    • DB2 FROM EMP WHERE EMP# = ‘8000’ OR EMP# = ‘8001’ OR EMP# = ‘8002’ ;NOT IN can also be used to exclude the specific values.8.2.5 )Retrieval using LIKE LIKE can be used to search for a specific character or a string or a character within a string. Butwhen using the LIKE• The ‘-‘ stands for a single character.• The % character stands for any sequence of N characters• All other character stands for themselvesE.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMPNAME LIKE ‘ J%’ ;This will retrieve all rows having EMPNAME starting with J.E.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMPNAME LIKE ‘%J%’ ;This will retrieve all rows having J anywhere in the EMPNAME.E.g. SELECT EMP#,EMPNAME FROM EMP WHERE EMPNAME LIKE ‘---J’ ;This will retrieve the rows with EMPNAME having 4 characters with J as ending one. Not LIKE can alsobe used as in previous cases.8.2.6) Retrieval involving NULL To retrieve the rows involving NULL valuesE.g. SELECT S# FROM S WHERE CITY IS NULL;IS NULL ore IS NOT NULL can be used. But it is illegal to use CITY = NULL.DB2 HO VER 0.3 30
    • DB28.3 ) JOIN Queries This is generally used to retrieve data from more than one table.8.3.1 ) Simple Equijoin The comparison operator will be ‘=’ in this case.E.g. Consider two tables S and P. SELECT S.*, P.* FROM S, P WHERE S.CITY = P.CITY;Resultant table will include a Cartesian product of all the rows having the city same. The above query canalso be written asEg2. SELECT * FROM S, P WHERE S.CITY = P.CITY;8.3.3 ) Greater than Join This is the case where > is used instead of =E.g. SELECT * FROM S, P WHERE S.CITY > P.CITY;8.3.4 )Join query with additional conditions In the WHERE statement more conditions can be added using AND or ORE.g. SELECT * FROM S, P WHERE S.CITY = P.CITY AND S.STATUS > 20;More number of tables can also be used. When using it all the table names have to be included in theFROM statement and Conditions have to be modified accordingly.8.3.5 ) Joining a table to itself This query involves joining a table to itself. So here two references of same table are used. Heretwo range variables A,B are used. These variables ranges over that specified table only.E.g. SELECT A.S#, B.S#DB2 HO VER 0.3 31
    • DB2 FROM S A,S B WHERE A.CITY = B. CITY;8.4 ) SUBQUERIES Subqueries are nested SELECT. SELECT FROM WHERE is nested within another suchexpression.8.4.1 ) Simple Subquerye.g. SELECT S# FROM S WHERE CITY IN (SELECT CITY FROM P WHERE P# = ‘P2’);This will evaluate the nested subquery first. It will get the value of CITY.E.g. If for P2 the CITY= PARISThen the above query will be same as SELECT S# FROM S WHERE CITY IN (‘PARIS’);The subquery, which is shown above, can be rewritten with a join also. Multiple levels of nesting can alsobe included. In the above example in second WHERE another nesting can be added.8.4.2) Correlated Subquery This is a type of subquery in which the inner and outer select statements are executedsimultaneously.E.g., SELECT SNAME FROM S WHERE ‘P2’ IN ( SELECT P# FROM SP WHERE S# = S. S#);Here inner nested query requires the variable S# from table S, whose value changes when the systemexamines the table S. For example initial value S1 is selected. From the inner SELECT value of P#corresponding to S1 are obtained. Then it evaluates the outer query. The corresponding SNAME will beselected. Thus the processing for S1 will be completed. Then it selects the next value of S# from the table Sand the processing continues. A correlated subquery is one, which whose values depend on some variablethat receives its value from outer query. Thus both the queries are simultaneously executed. So such asubquery has to be evaluated repeatedly instead of once.DB2 HO VER 0.3 32
    • DB2Even in the correlated subquery inner and outer queries can refer to the same tableE.g. SELECT A. P# FROM SP A WHERE A.P# IN ( SELECT B.P# FROM SPB WHERE B.S# = A.S#);8.4.3 ) Scalar Comparison Operator When using the subquery scalar comparison operators such as =,> etc can also be used.E.g. SELECT S# FROM S WHERE CITY = ( SELECT CITY FROM S WHERE S# = ‘S1’);8.5 ) The Existential Qualifier In existentially qualified condition ‘EXISTS (SELECT....FROM....) ‘ , the expression evaluatestrue only when the subquery produces some result. It can be made clear from an exampleE.g. SELECT SNMAE FROM S WHERE EXISTS (SELECT * FROM SP WHERE S# = S.S# AND P# = ‘P2’);Consider the first SNAME. Let it be SMITH with S#=S1. For SMITH to appear in resultant tableexistence test to evaluate to true. It checks for rows with S#= S1 and P# = P2. If it find some rows thenthe subquery evaluates true. So the SNAME correspond to that S# can appear in resultant table.So the EXISTS in SQL evaluates to true if subquery argument returns a nonempty set.NOT EXISTS can also be used in a similar fashion.8.6 ) Quantified Comparisons A quantified comparison operator consists of a scalar comparison operator like = , >, etc followedby ANY or ALL.E.g. SELECT PNAME FROMPWHEREWEIGHT>ALL ( SELECT WEIGHT FROM P WHERE COLOR = ‘BLUE’);Here the subquery returns the weight of all parts with color blue. The outer SELECT returns the rows withvalues greater than all the values of previous result.Eg2. SELECT S# FROM S WHERE CITY = ANYDB2 HO VER 0.3 33
    • DB2 (SELECT CITY FROM P );8.7 ) Column Functions Column (Aggregate ) functions, compute from a group of rows, a single value. This providescapability to aggregate data so as to perform statistical calculations across many rows with one SQLstatement. The column functions are AVG Average of the values in the column SUM Sum of the values in the column COUNT Number of values in the column MAX Largest value in the column MIN Smallest value in the columnEg1. SELECT COUNT(*) FROM S;This gives the number of rows in the table S.Eg2. SELECT COUNT (DISTINCT(S#)) FROM S;This won’t count repetitions.Eg3. SELECT MAX(WEIGHT) FROM P;Eg4. SELECT MIN(WEIGHT) FROM P;Eg5. SELECT SUM(QTY) FROM SP;8.8 ) GROUP BY Using this table can be grouped for taking some aggregate values.E.g. SELECT P#, SUM(QTY) FROM SP GROUP BY P#;This query will give each value of P# along with the sum of QTY for that specific value of P#.Eg2. SELECT P#, SUM(QTY), MAX(QTY) FROM SP WHERE S# <> ‘S1’ GROUP BY P#;8.9 ) Use of HAVING When using GROUP BY, to specify condition HAVING is used. So in short HAVING is togroups is what WHERE is to rows.E.g. SELECT P#DB2 HO VER 0.3 34
    • DB2 FROM SP GROUP BY P# HAVING COUNT(*) > 1;8.10 ) UNION The UNION operates on two sets of rows and combines them together into a single set. Two setsof rows must be union compatible. i.e. the two original sets must be of the same shape.E.g. SELECT P# FROM P WHERE WEIGHT > 16 UNION SELECT P# FROM SP WHERE S# = ‘S2’ ;The duplicate rows will always be eliminated. But if the user wants all the rows to be retrieved he has touse UNION ALLE.g. SELECT P# FROM P WHERE WEIGHT > 16 UNION ALL SELECT P# FROM SP WHERE S# = ‘S2’ ;Any number of SELECT can be UNIONed together. If OREDER BY clause is used it should come as apart of final SELECT only. In simple equijoin it select the matching rows only. But if any user want bothmatching and unmatching rows from any table (Outer Join) UNION ALL can be used.E.g. SELECT S.*,SP.P# FROM S,SP WHERE S.S# = SP.S# UNION ALL SELECT S.* ,’ ‘ FROM S WHERE NOT EXISTS (SELECT * FROM SP WHERE SP.S# = S.S#);8.11 ) INSERT This is used to insert data in to the table created. The format is INSERT INTO <tablename> [(col1)[col2,col3,..])] VALUES (literal[literal....])The values can also be obtained from executing some subqueries.E.g. INSERT INTO P VALUES (‘P1’ , ‘CINTHOL’ , ‘YELLOW’ , 10, ‘MADRAS’);This is case where the column names can be omitted as such since one entire row is inserted.E.g. INSERT INTO P (P#, CITY, WEIGHT)DB2 HO VER 0.3 35
    • DB2 VALUES (‘P7’, ‘ATHENS’ , 24);This is the case where the values of whole row are not inserted. So Selectively values can be inserted.E.g. INSERT INTO P (P#) SELECT P# FROM SP WHERE S#= ‘S1’;Here we are not directly entering the values but they are selected from table SP.8.12 ) UPDATE The UPDATE statement has the general form UPDATE <tablename> SET <column = value> [WHERE <condition>]This is used to update for the values in the tableE.g. UPDATE P SET COLOR = ‘YELLOW’, WEIGHT = WEIGHT + 5, CITY=NULL WHERE P# = ‘P2’ ;This query will update the values as given where value of P# is P2.E.g. UPDATE SP SET QTY = 0 WHERE ‘LONDON’ = ( SELECT CITY FROM S WHERE S.S# = SP. S#) ;This uses a subqueruy8.13) DELETE The DELETE is used to remove row or rows that satisfy the specific condition.E.g. DELETE FROM S WHERE S# = ‘S5’ ; This is a single row delete as the specific condition is given. Multiple rows can also be deletedusing a single queryE.g. DELETE FROM SP WHERE QTY > 300 ;Subquery can also be used similar to previous cases.DB2 HO VER 0.3 36
    • DB2 THE CATALOG9.1 ) Introduction DB2 catalog can be treated as a system database that contains information about various objectssuch as base tables, views etc. Catalog in a DB2 system consists of various system tables. User caninterrogate catalog using standard facilities of SQL language. In DB2 system the catalog consist of 38system tables. Some of these catalog tables are described below9.2) SYSTABLES This catalog table contains a row for every base table in the entire DB2 system. It include theinformations such as NAME of the table, CREATED BY give the user who created the table, CREATORwhich mentions the owner of the table and many other fields.NAME CREATED BY CREATOR COLCOUNT OTHERINFOSS JACOB JACOB 4 ------------P JACOB JACOB 5 -------9.3 ) SYSCOLUMNS This catalog table contains a row for every column of each table of the system.NAME TBNAME TBCREATOR COLTYPE ------------S# S JACOB CHAR -------------SNAME S JACOB CHAR -------------------- ----- -------- --------- --------------9.4 ) SYSINDEXES This catalog table contains a row for every index in the system.NAME CREATED BY CREATOR TBNAME TBCREATOR ----------------nameofindex JACOB JACOB S JACOB -------------- ----------- ---------- -- ----------- --------------9.5 ) QUERYING THE CATALOG The catalog can be queried using SQL statementsDB2 HO VER 0.3 37
    • DB2E.g. SELECT TBNAME, TBCREATOR FROM SYSIBM.SYSCOLUMNS WHERE NAME = ‘S#’ ; These can also be used for specific case where in a user wanted to find the total number of tablescreated by him. ThenE.g. SELECT COUNT(*) FROM SYSIBM.SYSTABLES WHERE CREATED BY = ‘ JACOB’ ;The catalog cannot be updated using INSERT UPDATE and DELETE operations.9.6 ) ALIASES AND SYNONYMS Alias is an alternate name for a base table. These will help to access the table very easily. Forexample if user A create a table X and user B wants to access that table then the fully qualified nameshould be givenE.g. SELECT * FROM A.X;But if user B can create an alias and use itE.g. CREATE ALIASE T1 FOR A.X; SELECT * FROM T1;Will give the same result as in the first case. Even a third user can also use the same alias by giving a fullyqualified nameE.g. SELECT * FROM B.T1;These can be removed by using DROP statement.E.g. DROP ALIASE T1;A synonym is similar to an alias. But the basic difference is that it is private to the user who creates it. Alsosynonym unlike alias cannot refer to remote tables.E.g. CREATE SYNONYM S1 FOR A.X;This can only be used by user who creates it. Also the table should not be remote. Removing theSYNONYM can be done byE.g. DROP SYNONYM S1;DB2 HO VER 0.3 38
    • DB2 VIEWS10.1 ) Introduction A view is a virtual table that consists of SQL SELECT statements, which can access the data frombase tables. A view never stores the data. But when the view is accessed the SQL statements are executedto access the data. So the view can access data from more than one table. These views provide with severaladvantages. They allow same data to be seen by different users in different ways. The users perception issimplified because by using a view he can select only those columns that are required. More security can begiven as all the columns that are not visible in the view. View also provides with logical dataindependence.10.2) VIEW DEFINITION The general syntax is CREATE VIEW < name> [ ( column[---] ) ] AS <subquery> ;E.g. CREATE VIEW VIEW1 (P#, PNAME , CITY) AS SELECT P#, PNMAE, CITY FROM P WHERE COLOR = ‘RED’ ;This will create a view with name A.VIEW1 where A is the CREATOR of the view. When the abovesubquery is executed the subquery is not executed but simply stored in the catalog (SYSVIEWS) under thespecified name.The view can be dropped by using DROP option.E.g. DROP VIEW VIEW1;Then for the specified view the definition will be removed from the catalog. But when a base table isdropped all view defined on the base table will be automatically dropped. There is no ALTER viewstatement.10.3) RETRIEVAL Operations Retrieval operations on a view will be converted into equivalent operations on a base table. But insome case like when a user tries to create a view column which is derived from something other than asimple column of the base table it can fail.E.g. CRETE VIEW PQ (P#, TOTQTY) AS SELECT P# , SUM(QTY) FROM SP GROUP BY P# ;DB2 HO VER 0.3 39
    • DB2 SELECT AVG(TOTQTY) FROM PQ;This if by simple merging process will give SELECT AVG (SUM(QTY)) FROM SP GROUP BY P#;This will fail as SQL will not allow aggegrate functions to be nested. So instead of this what DB2 does ismaterializing the view. For exampleE.g. CREATE TABLE TEMPPQ (P#, TOTQTY); INSERT INTO TEMPPQ (P#, TOTQTY) SELECT P#,SUM(QTY) FROM SP GROUP BY P# ; SELECT AVG(TOTQTY) FROM TEMPPQ ; DROP TABLE TEMPPQ ;So in this case nesting of aggregate functions does not occur.10.4) UPDATE Operations Not all views are updatable. This is because a view can be selected from more than one base table.Also there are chances to affect the various integrity relations. So in such case views are not updateable.But if in some views we will be able to preserve the tables integrity relations then they are updateable.DB2 HO VER 0.3 40
    • DB2 SECURITY AND AUTHORIZATION11.1 ) Introduction The security has to be given for protecting against unauthorized disclosure alteration etc in thedatabase. Each individual user is assigned an authorization id and all the tables that are created by the userwill be owned by this id. Authorization subsystem which allows users having certain privilege toselectively grant those privilege to others. There are different types of privileges• Table privilege which allows the user to perform operations on tables• Plan privilege which are concerned with authorization to execute a given PLAN• Data base privileges which is concerned with operations such as CREATE table in a Data base• User privilege which authorize the use of storage objects namely storage groups, tablespace and buffer pools• System privilege for the operations such as creation of new database.11.3 ) GRANT AND REVOKE For performing a particular operations user must hold the appropriate authority or privilege. Thesetwo commands are associated with granting and revoking of privileges.The syntax of the grant statements is GRANT privileges [ON [type] objects ] to users;E.g. GRANT SELECT ON TABLE S TO <userid>;Similarly the revoke statements can be used to revoke privileges.E.g. REVOKE SELECT ON TABLE S FROM <userid>;11.4 ) The GRANT OPTION If a privilege is granted to user A using GRANT OPTIONS, then user A can grant the sameprivilege to user B.E.g. GRANT SELECT ON TABLE S TO A WITH GRANT OPTION;Then user A can grant the same privilege to user BE.g. GRANT SELECT ON TABLE S TO B WITH GRANT OPTION.Now if the grant options to User A is revoked by a revoke command it will have a cascading effect i.e. allthe associated privileges granted by A to various users will also be revoked.DB2 HO VER 0.3 41
    • DB2 EMBEDDED SQL12.1 ) Introduction SQL statements can also be used in application program. So such SQL statements which areincluded in the host language program are called Embedded SQL statements. The host languages thatcurrently supported by DB2 are PL/I, COBOL,FORTAN,C,SYSTEM/370 Assembler language.12.2 ) Preliminaries.• Embedded SQL statements should be prefixed by EXEC SQL. And should be terminated by a termination symbol(e.g. END EXEC).• An executable statements can appear wherever an executable host language can appear.• SQL statements can include references to host variables. Host variables should be prefixed by a colon which helps to identify them from SQL column names. These host variables used should declared in BEGIN DECLARE SECTION and terminated by END DECLARE SECTION.• Host variables can appear in SQL data manipulation language where literals are permitted.(E.g. INTO clause in SELECT, WHERE and HAVING clause where values to be compared etc.)• Any table used in the program can be declared by means of an EXEC SQL DECLARE TABLE to make the program more self-documenting.• SQLCODE AND SQLSTATE are two special host variables to get the feedback information after the SQL query executed. A SQLCODE zero means that statement executed successfully. If a positive value then statements executed with some exceptional conditions and a negative value means that the statement did not execute successfully. The SQLSTATE values consists of two character ‘class code ‘ followed by three character ‘subclass code’ .This will also helps to know whether the SQL statements are executed successfully. So to find the status every SQL statement in the program should be followed by a test on SQLCODE or SQLSTATE.• SQLCA or SQL Communication Area can be included so that it contains the declarations for both SQLCODE and SQLSTATE. So either use INCLUDE SQLCA or declare SQLCODE and SQLSTATE explicitly• Embedded SQL SELECT statement requires INTO clause specifying the host variable so that values retrieved from database can be assigned. These host variables should have a data type compatible with the SQL data type of columns from which the values are retrieved. Host variables and database can have same name.E.g. EXEC SQL SELECT STATUS,CITYDB2 HO VER 0.3 42
    • DB2 INTO :STATUS, : CITY FROM S WHERE S# = ‘S5’ END-EXEC; This will select the values of STATUS and CITY in to the host variables and SQLCODE will beset to 0. If there is no row with S#= S5 then SQLCODE will be set to 100. If there is more than a row withS# = S5 then the program will show an error with SQLCODE negative. If the values retrieved to be null,the user has to include an indicator variable. For example if STATUS is NULL thenE.g. EXEC SQL SELECT STATUS,CITY INTO :STATUS INDICATOR :STATUSIND, : CITY FROM S WHERE S# = ‘S5’ END-EXEC; If the value to be retrieved to be NULL the indicator value will be set to -1 and host variableremains unchanged. Indicator variable should be declared as 15-bit signed binary integers.E.g. EXEC SQL INSERT INTO P(P#, PNAME, WEIGHT) VALUES (:PNO, :PNAME, :WEIGHT) END-EXEC;Eg1. EXEC SQL UPDATE S SET STATUS = STATUS + : NEWSTAT WHERE CITY = ‘LONDON’ END-EXEC;12.3 ) Operations Involving CURSORS In the case of singleton SELECT only one row has to be selected and the retrieved values will bemoved into host variable. But in some cases more number of rows have to be selected. DB2 applicationprograms uses cursor to navigate through a set of rows returned by an embedded SQL SELECT statement.Cursor is declared, opened, rows are fetched from cursor one row at a time and cursor is closed.Four distinct operations or cursors areDB2 HO VER 0.3 43
    • DB212.3.1 )DECLARE Declare defines the cursor, gives it a name unique to the program in which it is embedded andassigns and SQL statement to the cursor name. The DECLARE statement does not execute the SQLstatement but merely defines it.12.3.2 )OPEN Open is an executable statement. It reads the SQL search fields, execute the SQL statement andsometimes builds the resultant table. It does not assign values to host variables.12.3.3)FECTCH Returns the data from the resultant table one at a time to the specified host variables. If theresultant table is not built at cursor open time, it is built one by one. When cursors are used for retrievingmultiple rows FETCH statement should be coded in a loop. When no more rows to be retrieved FETCHstatement should return an SQLCODE of +100.12.3.4)CLOSE This statement releases all statements used by cursor.E.g. WORKING-STORAGE SECTION. 01 MORE ROWS PIC X VALUE ‘Y’. EXEC SQL DECLARE CURSOR C1 FOR SELECT S# ,SNAME,STATUS FROM S WHERE CITY = ‘LONDON’ END-EXEC. PROCEDURE DIVISION. - - EXEC SQL OPEN C1DB2 HO VER 0.3 44
    • DB2 END-EXEC. IF SQLCODE < 0 PERFORM ERR-PARA. PERFORM PARA1 UNTIL MORE ROWS = ‘N’. EXEC SQL CLOSE C1 END-EXEC. ERR-PARA. -- -- PARA1. EXEC SQL FETCH C1 INTO :S#, :SNAME, :STATUS END-EXEC. IF SQLCODE = +100 MOVE ‘N’ TO MORE ROWS. IF SQLCODE < 0 PERFORM ERR-PARA.More number of cursors can be opened at any time. There is no limit to the number of cursors permitted perapplication program. The cursor should be declared first before doing any processing on it. Update andDelete can also be done. These are CURRENT forms of UPDATE and DELETE but it cannot be usedwhen UNION,GROUP BY,ORDRER BY,DISTINCT etc are used. Also this is not used in the case ofsubqueries.E.g. EXEC SQL DELETE FROM S WHERE CURRENT OF C1 END-EXEC.12.3.5)WITH HOLD clause. When a COMMIT is issued by program all open cursors will be closed unless WITH HOLDoption should be specified. So the current position of cursor can be saved.E.g. EXEC SQL DECLARE CURSOR C2 WITH HOLD FOR SELECT S#,SNAME FROM S WHERE CITY = ‘LONDON’ END-EXEC.DB2 HO VER 0.3 45
    • DB2 TRANSACTION PROCESSING13.1) Introduction A Transaction is a term used to specify the logical unit of work. This can involve any number ofupdates in between. Thus it is a sequence of several operations which converts one consistent state ofdatabase into another, without necessarily preserving the consistency in between. Generally explaining ifone transaction reaches its normal termination with all the steps in between working properly, then theupdation will be made permanent. Instead if some SQL ERROR or some system failure occurs, everychanges made will be erased. So it can be said that either full updation or no updation at all,but partialupdation cannot be made. These are taken care by system component called Transaction Manager. Whenever an UPDATE is done it is not done on the database. If something goes wrong withsystem, updation may be revoked either by program or by system. The data in such condition is called astentative until either of these happens• COMMIT• ROLLBACKThese two are not really database operations like SELECT and UPDATE. They are instructions toTransaction Manager. A term Synchronization point will be used (Abbreviated as SYNCHPOINT) whichrepresents the level between two consecutive transactions.13.2) COMMIT and ROLLBACK Any updation made in the system is guarantied once it is committed. This could be by way of anexplicit COMMIT given by the program or it could be given by the system, when the task normallyterminates i.e. A successful end of a transaction is signaled as a synchpoint is established. By the way ofCOMMIT statement all open cursors will be closed and all record locks will be released. The SQL COMMIT statement takes the form COMMIT [work]; ROLLBACK can also be given explicitly in the program or will be issued by the system when thetask abnormally terminates. Here all updations done after the previous SYNCHPOINT will not be saved todatabase. Here again all open cursors are closed and record locks are released. The syntax is ROLLBACK[work];DB2 HO VER 0.3 46
    • DB213.3) Three CONCURRENCY PROBLEMS DB2 being a shared system allows numerous users to access the same database simultaneously.Any such kind of system requires some kind of control mechanism to ensure that concurrent transaction donot interfere with each others operation. There are essentially three ways in which things can go wrong.They are• The lost update problem• The uncommitted dependency problem• The inconsistent analysis problem13.3.1)The LOST UPDATE problem Here Consider the two transactions A and B. From the figure given Transaction A retrieves row Rat time t1. Transaction B retrieves row R at t2. Now Transaction A updates row R at time t3. AgainTransaction B updates row R at t4. So transition A’s update is lost at time t4 because Transaction Boverwrites it. So this describes the lost update problem.TRANSACTION A TIME `TRANSACTION B ------ T0 -------------FECTCH R T1 ------------- --------- T2 FETCH RUPDATE R T3 ------------ ----------- T5 UPDATE R13.3.2)The UNCOMMITED DEPENDENCY problem This occurs when one transaction is allowed to retrieve a row that has been updated by anothertransaction and has not yet been committed to database by other transaction.TRANSACTION A TIME `TRANSACTION B ------ T0 ------------- T1 UPDATE RFETCH R T2 ------------ T3 ROLLBACKDB2 HO VER 0.3 47
    • DB213.3.3)The INCONSISTANT ANALYSIS problem The figure shows two transactions A and B operating on an account ACC1.Transaction A issumming an account balance and transaction B is transferring an amount 10 from ACC3 to ACC1. Theresult produced by A is incorrect. So if A writes back the result into database it would leave the database inan inconsistent state. Since A has seen an inconsistent state of database it has performed an inconsistentanalysis. But this cannot be an uncommitted dependency as B commits all updates before A sees ACC3.13.4) Solution. For solving the concurrency issues technique called Locking is used. The idea of locking is thatwhen transaction needs to update an object it puts a lock on that object. The effect of this is to lock theother transactions out of the object thereby preventing any changes on it. These locks can be either sharedlock or exclusive lock.DB2 HO VER 0.3 48
    • DB213.5) Locking Facilities. Though DB2 provides implicit locking mechanism locking can also be done by explicitdeclarations.13.5.1) LOCK TABLE The syntax isE.g. LOCK TABLE SP IN SHARE MODE.Eg1. LOCK TABLE P IN EXCLUSIVE MODE. Where the table should be a base table and not a view. This command acquires an S or X lock onthe entire table as per the command given. Acquiring such lock may not be instantaneous since the programwill have to wait for a time, when all table level locks will be removed. Once this is done table level lockswill be made and if it is a shared one then the other transactions will be able to get shared locks on anylevels.13.5.2) The ISOLATION parameter The ISOLATION parameter on BIND command specifies, isolation level for the application planbeing bound. The two options are• REPETABLE READ• CURSOR STABILITY13.5.2.1)CURSOR STABILITY If a transaction obtains addressability to a particular record by setting a cursor to point to it andacquires a lock on that record. This lock is in the shared mode and now without updating it, the cursorremoves the addressability i.e. the lock here will be in S mode and it does not change to X mode. Now thislock can be released without waiting for the synchpoint in the case of CS being used. So CS provide moreconcurrency.13.5.2.2) REPETABLE READ Cursor Stability though giving more concurrency is not advisable from thetheoretical point of view. So Repeatable Read is made as the default and that is more preferable. RepeatableRead holds the record level S lock (Shareable Lock) until the next synchpoint similar to the X lock. Theproblem here is that the record may be changed by another transaction without the notice of the changebeing made, as explained in the lost update problem. But this can be avoided by the Isolation levelDB2 HO VER 0.3 49
    • DB2Repeatable Read. Here if a transaction obtains an addressability to record under CS and if there is apossibility that the transaction may update the record, i.e. the cursor is defined FOR UPDATE, then DB2issues a Update Lock (ULOCK) for the transaction instead of the X lock. If a transaction holds a U lockand another transaction requests for a U lock or X lock the request will be put in the wait state. If the firsttransaction updates the record, the U lock will be changed to X lock else it will be released when theaddressability is removed. The advantage here is formation of dead locks may be avoided.13.5.3)LOCK SIZE For a given table space, the lock size can be specified as PAGE, TABLE, TABLESPACE or ANYdepending on the factor in the CREATE or ALTER TABLE SPACE operation. When TABLE is specified,locking will be in the table level and when PAGE is specified, locking will be in the page level, when ANYis specified DB2 itself decides which unit of locking would be optimum. Mostly DB2 acquires page levellock initially and when the number of page level lock reaches a installation specified threshold value, thenDB2 escalates the level locking to a higher factor.13.5.4) The ACQUIRE/RELEASE parameters These parameters in the bind statement specifies when a table space level lock will have to beacquired or released. For ACQUIRE possible specifications are USE And ALLOCATE, for RELEASE itis COMMIT and DEALLOCATE. USE means that the Lock is acquired on the first use and ALLOCATEmeans that the locks are allocated when the program begins execution. COMMIT means that the tablespace level locks are released at each synch point, and in DEALLOCATE the locks will be held until theprogram terminates.13.6) DEADLOCK It appears when two or more transactions are simultaneously in the wait state when one transactionwaits for the resource held by another while the other waits for the resource held by the first transaction.When such a condition occurs, there is no other alternative except to detect it and break it. The breakingpart involves choosing one of the deadlock transaction as the victim and either rolling it back or asking itrole back. This releases the deadlock.DB2 HO VER 0.3 50
    • DB2 DYANAMIC SQL14.1)Introduction Dynamic SQL consists of a set of embedded SOL facilities, that are provided specifically to allowthe construction of generalized on line application. There may be a necessity some times to construct therequired SQL statements dynamically and then to bind and create those constructive statementsdynamically. DB2I is a generalized on-line application, which can accept any valid SQL statements . It usesthe facility of Dynamic SQL to construct suitable SQL statements corresponding to its input, bind andexecute this statements and to return messages and results back to the terminal.There are different types of Non SELECT Dynamic SQL statements. They are• PREPARE/ EXECUTE• EXECUTE IMMEDIATE14.2) PREPARE/EXECUTEThis class of Dynamic SQL uses PREPARE and EXECUTE to issue SQL statements. Non SELECTDynamic SQL cannot issue a SELECT statement.Eg1.WORKING-STORAGE SECTION.--EXEC SQL INCLUDE SQLCA END-EXEC.01 STRING-VAR. 02 STRING-VAR-LEN PIC S9(4) COMP. 02 STRING-VAR-TEXT PIC X(100).PROCEDURE DIVISION.MOVE 39 TO STRING-VAR-LEN.MOVE “DELETE FROM TAB1 WHERE DEPTNO = ‘A00’” TO STRING-VAR-TEXT.EXEC SQL PREPARE STMT1 FROM :STRING-VARDB2 HO VER 0.3 51
    • DB2END-EXEC.EXEC SQL EXECUTE STMT1END-EXEC.14.3) EXECUTE IMMEDIATE EXECUTE IMMEDIATE which combines the functions of both PREPARE and EXECUTEstatements.E.g. WORKING-STORAGE SECTION.--EXEC SQL INCLUDE SQLCA END-EXEC.01 STRING-VAR. 02 STRING-VAR-LEN PIC S9(4) COMP. 02 STRING-VAR-TEXT PIC X(100).PROCEDURE DIVISION.MOVE 39 TO STRING-VAR-LEN.MOVE “DELETE FROM TAB1 WHERE DEPTNO = ‘A00’” TO STRING-VAR-TEXT.EXEC SQL EXECUTE IMMEDIATE : STRING-VAR END-EXEC.DB2 HO VER 0.3 52
    • DB2 ADMINISTRATION FACILITIES15.1) Introduction This falls into two categories. They are facilities for database and facilities for systemadministration. The database administration involves the design implementation and maintenance ofindividual DB2 database and associated application. Two DB2 features that can assist these tasks areDB2I and EXPLAIN facility. The system administration covers the installation, monitoring, tuning andcontrol of overall DB2 system itself.15.2) DB2 INTERACTIVE INTERFACE Almost all functions of DB2 are available online through the DB2 interactive interface. Thisprovides the ability to execute SQL statements interactively and to invoke pre-written applicationprograms. Apart from this they also have ability to issue operator commands, the ability to invoke databaseutilities and the ability to prepare application programs for execution. Though DB21 is the normal mode ofoperation, it is always possible to use batch. TSO supports both batch and online application. The onlineapplication work under the control of ISPF. DB2I itself is a TSO online application, which provides theability to execute SQL statements interactively by means of a component call SPUFI (SQL Processor UsingFile Input). The following are the sequence of events for invoking DB2I 1. LOGON to TSO in the normal way 2. From ISPF Primary option menu, select DB21 optionHere we get the DB21 main menu with• SPUFI• DCLGEN• Program Preparation• Pre-compile• Bind / Rebind / Free• RUN• DB2 Commands• Utilities• Catalog visibilityDB2 HO VER 0.3 53
    • DB2• DB2I Defaults• Exit15.2.1) SPUFI This reports the interactive execution of SQL statements from TSO terminals. The idea here is thatthe user can create a text file containing one or more SQL statements then execute the statement throughSPUFI and then use ISPF browse to browse the result.15.2.2) DCLGEN This allows the user to invoke the Declaration Generator program. This is the program that createsembedded SQL, DECLARE TABLE statements and corresponding host language structure declarationsfrom table description in the catalog. The output from this is stored as a modules of a PDS which could becopied by the include statement or to put up in the program itself.15.2.3)Program Preparation This allows the user to perform any of the following or all of the following functions.• Precompilation• Compilation or assembly• Linkage editor processing• Bind processing• Program execution (TSO application only)15.2.4)Precompile This is effective only for the precompile step of the program preparation .15.2.5) Bind / Rebind / FreeBIND creates the application plan from one or more DBRMS. The following parameters may be specified.• If the new plan is to replace the existing one• The AUTH ID that is to own the plan if that ID is different from the ID of the user entering the bind command.The isolation level RR & CS specifies the lock acquisition and release times for the plans.DB2 HO VER 0.3 54
    • DB2REBIND rebinds the existing plan. It is not a replace version of the bind command. Here the input for therebind command is the previous plan but not the DBRM.15.2.5) RUN RUN allows the user to execute a previously prepared application program.15.2.6) DB2 Commands This allows the user to enter system operator commands like START DATABASE, STOPDATABASE etc.15.2.7)Utilities This allows the user to invoke various utilities15.2.8)Catalog Visibility Catalog Visibility menu allows certain queries to be formulated against DB2 catalog with outdirect use of SQL.15.2.9) DB2I Defaults This menu allows the user to set certain defaults for DB2I session15.2.10) EXIT This option allows the user to come out of DB2I session.15.3) EXPLAIN This allows the user to obtain information regarding the operators choice for the access strategyspecified for the SQL statement.E.g. EXPLAIN PLAN FOR SELECT SNO, NAMEDB2 HO VER 0.3 55
    • DB2 FROM TAB WHERE CITY = PUNE15.4) Database utilities The DB2 database utilities are all online utilities and can be invoked online without stopping theexecution of DB2 system. Some of them are.• CHECK This utility checks a table space to find if there are any referential integrity violation. Records if found to contain any unmatched foreign key value, the table space will be in the check pending state.• COPY This utility creates a full or incremental back-up copy of the table space. An incremental copy is a copy of the pages that have changed since the previous change• LOAD This utility loads data from a sequential data set into one or more tables with one or more partitions of a specified table space.• MERGE COPY This utility merges a full copy and one or more incremental copies to produce a upto date full copy.• MODIFY This is used to perform maintenance operation recovery information in the DB2 catalog.• RECOVER This uses the most recent full copy, any subsequent incremental copies, and any subsequent log data to recover one or more table space partitions or pages after a media failure• REPAIR This can be used to reset conditions like check pending.• REPORT This produces some reports that are useful in connection with managing database recovery process• RUNSTATS This computes statistics on specified stored data and writes them to the system catalog.• STOSPACE This gathers information regarding the amount of space allocated to a given set of table space and indexes and stores them in a DB2 catalog.DB2 HO VER 0.3 56