DB2 Certification Using SQL DB2
Objectives After completing this unit, you should be able to: To describe database objects To examine the DB2 implementation of SQL Data Definition Language(DDL) Data Manipulation Language(DML) Advanced SQL
DB2 Object Hierarchy Instance 1 dbm configuration file Database 1 Catalog Log Database 2 Catalog Log DB config file DB config file Table1 Table2 Table3 Table2 Index1 View1 Index1 View1 BLOBs View2 Index2 View3
DB2 Data Types Data Types Numeric Date/Time Decimal Integer Double String date Time Timestamp Smallint Integer Double Byte Graphic Binary Character Vargraphic BLOB Char VarChar CLOB DBCLOB
Large Objects - The Need Action News DB2 By The Book B inary L arge OB ject C haracter L arge OB ject D ouble B yte C haracter L arge OB ject DB2
Large Objects - Memory Consideration PGM... short indv; long salary;... REFERENCE? DATA MOVEMENT? UP TO 2GB *Single Record can hold 24GB
User-Defined Types - The Need Need to establish context for values DB2 enforced typing But... I was only doing a hundred! SPEED 100 LIMIT CANADA USA SPEED 65 LIMIT
User-Defined CREATE DISTINCT TYPE Types POUND - Definition AS INTEGER WITH COMPARISONS CREATE DISTINCT TYPE KILOGRAM AS INTEGER WITH COMPARISONS CREATE TABLE person (f_name varchar(30), weight_p POUND NOT NULL, weight_k KILOGRAM NOT NULL ) SELECT F_NAME FROM PERSON WHERE weight_p > POUND(30) SELECT F_NAME FROM PERSON WHERE weight_p > weight_k FAILS
Selecting the Correct Data Type Question Is the data fixed in length? Is the data variable in length? Do you need to sort(order) the data? Is the data to be used in arithmetic operations? Does it contain decimal? Does the data have a specific meaning (beyond DB2 base datatype)? DataType CHAR VARCHAR CHAR, VARCHAR, CLOB, DBCLOB DECIMAL, DOUBLE, INTEGER, SMALLINT DECIMAL, DOUBLE UDT
Using SQL Basic SQL Data Definition Language (DDL) DB2
Physical Database Layout Database Manager Instance database1 database2 Table 1 Tablespace A Table 2 Table 3 Tablespace B Table 4 Tablespace A Table 1 Table 2 Table spaces are a logical layer created within catabase Tables are created within table spaces Two types of table spaces: SMS and DMS
Object Definition You can CREATE or DROP the following objects:- Table View Alias UDF Trigger Event Monitor Index UDT Table Space But you can only ALTER :- Table Table Space
Schema and Catalog What is a Schema name? Fully-qualified table name "schemaname.tablename" Following schema names reserved SYSCAT, SYSIBM, SYSSTAT Avoid schema names beginning with SYS Enforced with triggers, UDFs, and UDTs If Database object does not specify a schema name Table qualified with current authorization ID
SYS Schemas SYSIBM Base catalogs SYSCAT - SELECT GRANT to PUBLIC Catalog Read-Only Views SYSSTAT Updateable Catalog Views - Influence the Optimizer SYSFUN User-Defined Functions
Create Table Connect to database first You must have SYSADM, DBADM or CREATETAB privilege connect to eddb create table artists (artno smallint not null, name varchar(50) with default 'abc', classification char(1) not null, bio clob(100k) logged, picture blob( 2M) not logged compact) in dms01 index in dms02 long in dms03
Creating Views Must have SYSADM, DBADM, CONTROL or SELECT on each base table Data for view not stored separately SYSCAT.VIEWS, SYSCAT.VIEWDEP, SYSCAT.TABLES CONNECT TO TESTDB CREATE VIEW DEPTSALARY AS SELECT DEPTNO, DEPTNAME, SUM(SALARY) AS TOTSAL FROM PAYROLL GROUP BY DEPTNO,DEPTNAME CREATE VIEW EMPSALARY AS SELECT EMPNO, EMPNAME, SALARY FROM PAYROLL, PERSONNEL WHERE EMPNO=EMPNUMB AND SALARY > 30000.00 SELECT * FROM DEPTSALARY DEPTNO DEPTNAME TOTSAL ------ ----------------- ---------- 10 MANUFACTURING 1000000.00 20 ADMINISTRATION 300000.00 30 MARKETING 250000.00...
Creating Indexes Must have SYSADM, DBADM, CONTROL or INDEX privilege on table create unique index itemno on albums (itemno) create index item on stock (itemno) SYSCAT.INDEXES and SYSCAT.INDEXAUTH
Referential Integrity Referential Constraints are established with the:- Primary Key clause Foreign Key clause References Clause in the CREATE/ALTER TABLE statements create table artists (artno... primary key (artno) foreign key dept (workdept) references department on delete no action) in DMS01
Using SQL Basic SQL Data Manipulation Language (DML) DB2
Basic SQL The SQL Language has been developed around 4 basic verbs:- SELECT INSERT UPDATE DELETE
SELECT SELECT is the QUERY element of the language. Queries come many styles:- Full Table scans Limited Columns or Rows retrieved Cartesian Product Join Union with :- derived columns sub-query etc...
INSERT / UPDATE / DELETE Data can be modified using this verbs. INSERTS & DELETES can single or multiple row You can also use sub-select to determine values INSERT's may also be done to a subset of columns provided omitted columns allow nulls UPDATES come in 3 main varieties :- Full table Searched with a WHERE clause Positioned using a CURSOR in a program
Using SQL Advanced SQL DB2
Triggers Triggers can be fired by :- INSERTs UPDATEs DELETEs
Trigger Usage A trigger can be fired before or after an event. A trigger is used for :- VALIDATION Similar to constraints but more flexible CONDITIONING Allows new data to be modified/conditioned to a predefined value. INTEGRITY Similar to RI but more flexible
Trigger (AFTER) A trigger is defined to set the value of the column pass_fail dependent on the score attained. CREATE TRIGGER passfail AFTER INSERT ON test_taken REFERENCING NEW AS N FOR EACH ROW MODE DB2SQL UPDATE test_taken SET PASS_FAIL = CASE WHEN N.SCORE >= (SELECT CUT_SCORE FROM TEST WHERE NUMBER = N.NUMBER) THEN 'P' WHEN N.SCORE < (SELECT CUT_SCORE FROM TEST WHERE NUMBER = N.NUMBER) THEN 'F' END WHERE N.CID = CID AND N.TCID = TCID AND N.NUMBER = NUMBER AND N.DATA_TAKEN = DATA_TAKEN
Trigger (BEFORE) The triggers are defined to prevent a booking either before 09:00 or after 17:00. CREATE TRIGGER pre9 NO CASCADE BEFORE INSERT ON test_taken REFERENCING NEW AS N FOR EACH ROW MODE DB2SQL WHEN (N.START_TIME < '09:00:00') SIGNAL SQLSTATE '70003' ('Cannot assign seat before 09:00!') CREATE TRIGGER aft5 NO CASCADE BEFORE INSERT ON test_taken REFERENCING NEW AS N FOR EACH ROW MODE DB2SQL WHEN (N.START_TIME + (SELECT SMALLINT(LENGTH) FROM test WHERE NUMBER = N.NUMBER) MINUTES > '17:00:00') SIGNAL SQLSTATE '70004' ('Cannot assign seat after 17:00!')
Recursive SQL A recursive SQL statement is used when an SQL repeatedly uses the resulting set to determine further results. eg. bill-of-materials or routing information
Recursive SQL 1 2 3 WITH path (origin, destiny, distance, stops) AS( SELECT f.origin, f.destiny, f.distance FROM flights f WHERE origin='germany' UNION ALL SELECT p.origin, f.destiny, p.distance+f.distance, p.stops+1 FROM flights f, path p WHERE p.destiny=f.origin) SELECT origin, destiny, distance, stops FROM path
Recursive SQL (Result set) ORIGIN DESTINY DISTANCE STOPS ---------- ------------------- ----------------- ------------- SQL0347W The recursive common table expression 'DB2.PATH' can contain an infinite loop. SQLSTATE=01605 Germany New York 8000 0 Germany Chicago 8700 0 Germany Toronto 9000 1 Germany Chicago 10500 1 Germany Austin 11300 2...
User-Defined Defaults DB2 has a defined default for DB2 data types but you can set your own. Create table artists (artno smallint not null, name varchar(50) with default 'abc', classification char(1) not null, bio clob(100k) logged, picture blob( 2M) not logged compact) in dms01 If the column was an UDT, you must use a casting function with the constant
Check Constraints These will enforce data integrity at a table level. Once defined every update/insert will have to conform otherwise it will fail. Create table artists (artno smallint not null, name varchar(50) with default 'abc', classification char(1) not null, bio clob(100k) logged, picture blob( 2M) not logged compact) CONSTRAINT classify CHECK (classification in ('C','E','P','R')) in dms01 If some rows do not meet the constraint then it will fail. You can turn off checking and then add the constraint but the table will be placed in CHECK PENDING. To modify a constraint you have drop & add new constraint.
Unit Summary Having completed this unit, you should be able to: To describe database objects To examine the DB2 implementation of SQL Data Definition Language(DDL) Data Manipulation Language(DML) Advanced SQL