DB2 V 9.5 Cook book

download DB2 V 9.5 Cook book

of 468

Transcript of DB2 V 9.5 Cook book

  • 8/14/2019 DB2 V 9.5 Cook book

    1/467

    DB2 LUW V9.5SQL CookbookGraeme Birchall20-Nov-2007

  • 8/14/2019 DB2 V 9.5 Cook book

    2/467

    Graeme Birchall

    2

  • 8/14/2019 DB2 V 9.5 Cook book

    3/467

    DB2 V9.5 Cookbook

    Preface 3

    PrefaceImportant!

    If you didn't get this document directly from my personal website, you may have got an olderedition. The book is changed very frequently, so if you want the latest, go to the source. Also,the latest edition is usually the best book to have, as the examples are often much better. Thisis true even if you are using an older version of DB2.

    This Cookbook is written for DB2 for LUW (i.e. Linux, Unix, Windows). It is not suitable forDB2 for z/OS unless you are running DB2 8 in new-function-mode, or (even better) DB2 9.

    Acknowledgements

    I did not come up with all of the ideas presented in this book. Many of the best examples wereprovided by readers, friends, and/or coworkers too numerous to list. Thanks also to the manypeople at IBM for their (strictly unofficial) assistance.

    Disclaimer & CopyrightDISCLAIMER: This document is a best effort on my part. However, I screw up all the time,so it would be extremely unwise to trust the contents in its entirety. I certainly don't. And ifyou do something silly based on what I say, life is tough.

    COPYRIGHT: You can make as many copies of this book as you wish. And I encourage youto give it to others. But you cannot charge for it (other than to recover reproduction costs), norclaim the material as your own, nor replace my name with another. You are also encouragedto use the related class notes for teaching. In this case, you can charge for your time and mate-rials - and your expertise. But you cannot charge any licensing fee, nor claim an exclusiveright of use. In other words, you can pretty well do anything you want. And if you find theabove too restrictive, just let me know.

    TRADEMARKS: Lots of words in this document, like "DB2", are registered trademarks ofthe IBM Corporation. Lots of other words, like "Windows", are registered trademarks of theMicrosoft Corporation. Acrobat is a registered trademark of the Adobe Corporation.

    Tools Used

    This book was written on a Dell PC that came with oodles of RAM. All testing was done inDB2 9.5. Word for Windows was used to write the document. Adobe Acrobat was used tomake the PDF file.

    Book Binding

    This book looks best when printed on a doubled sided laser printer and then suitably bound.To this end, I did some experiments a few years ago to figure out how to bind books cheaplyusing commonly available materials. I came up with what I consider to be a very satisfactorysolution that is fully documented on page 457.

    Author / Book

    Author: Graeme Birchall Email: [email protected]: http://mysite.verizon.net/Graeme_Birchall/Title: DB2 9.5 SQL Cookbook Date: 20-Nov-2007

  • 8/14/2019 DB2 V 9.5 Cook book

    4/467

    Graeme Birchall

    4

    Author NotesBook History

    This book originally began a series of notes for my own use. After a while, friends began toask for copies, and enemies started to steal it, so I decided to tidy everything up and give itaway. Over the years, new chapters have been added as DB2 has evolved, and as I have foundnew ways to solve problems. Hopefully, this process will continue for the foreseeable future.

    Why Free

    This book is free because I want people to use it. The more people that use it, and the morethat it helps them, the more inclined I am to keep it up to date. For these reasons, if you findthis book to be useful, please share it with others.

    This book is free, rather than formally published, because I want to deliver the best productthat I can. If I had a publisher, I would have the services of an editor and a graphic designer,but I would not be able to get to market so quickly, and when a product changes as quickly as

    DB2 does, timeliness is important. Also, giving it away means that I am under no pressure tomake the book marketable. I simply include whatever I think might be useful.

    Other Free Documents

    The following documents are also available for free from my web site:

    SAMPLE SQL: The complete text of the SQL statements in this Cookbook is available inan HTML file. Only the first and last few lines of the file have HTML tags, the rest is rawtext, so it can easily be cut and paste into other files.

    CLASS OVERHEADS: Selected SQL examples from this book have been rewritten asclass overheads. This enables one to use this material to teach DB2 SQL to others. Usethis cookbook as the student notes.

    OLDER EDITIONS: This book is rewritten, and usually much improved, with each newversion of DB2. Some of the older editions are available from my website. The others canbe emailed upon request. However, the latest edition is the best, so you should probablyuse it, regardless of the version of DB2 that you have.

    Answering Questions

    As a rule, I do not answer technical questions because I need to have a life. But I'm interestedin hearing about interesting SQL problems, and also about any bugs in this book. Howeveryou may not get a prompt response, or any response. And if you are obviously an idiot, don'tbe surprised if I point out (for free, remember) that you are an idiot.

    Software Whines

    This book is written using Microsoft Word for Windows. I've been using this software for

    many years, and it has generally been a bunch of bug-ridden junk. I do confess that it hasbeen mildly more reliable in recent years. However, I could have written more than twice asmuch that was twice as good in half the time - if it weren't for all of the bugs in Word.

    Graeme

  • 8/14/2019 DB2 V 9.5 Cook book

    5/467

    DB2 V9.5 Cookbook

    Book Editions 5

    Book EditionsUpload Dates

    1996-05-08: First edition of the DB2 V2.1.1 SQL Cookbook was posted to my web site.This version was in Postscript Print File format.

    1998-02-26: The DB2 V2.1.1 SQL Cookbook was converted to an Adobe Acrobat fileand posted to my web site. Some minor cosmetic changes were made.

    1998-08-19: First edition of DB2 UDB V5 SQL Cookbook posted. Every SQL statementwas checked for V5, and there were new chapters on OUTER JOIN and GROUP BY.

    1998-08-26: About 20 minor cosmetic defects were corrected in the V5 Cookbook.

    1998-09-03: Another 30 or so minor defects were corrected in the V5 Cookbook.

    1998-10-24: The Cookbook was updated for DB2 UDB V5.2.

    1998-10-25: About twenty minor typos and sundry cosmetic defects were fixed.

    1998-12-03: This book was based on the second edition of the V5.2 upgrade. 1999-01-25: A chapter on Summary Tables (new in the Dec/98 fixpack) was added and

    all the SQL was checked for changes.

    1999-01-28: Some more SQL was added to the new chapter on Summary Tables.

    1999-02-15: The section of stopping recursive SQL statements was completely rewritten,and a new section was added on denormalizing hierarchical data structures.

    1999-02-16: Minor editorial changes were made.

    1999-03-16: Some bright spark at IBM pointed out that my new and improved section onstopping recursive SQL was all wrong. Damn. I undid everything.

    1999-05-12: Minor editorial changes were made, and one new example (on getting mul-tiple counts from one value) was added.

    1999-09-16: DB2 V6.1 edition. All SQL was rechecked, and there were some minor ad-ditions - especially to summary tables, plus a chapter on "DB2 Dislikes".

    1999-09-23: Some minor layout changes were made.

    1999-10-06: Some bugs fixed, plus new section on index usage in summary tables.

    2000-04-12: Some typos fixed, and a couple of new SQL tricks were added.

    2000-09-19: DB2 V7.1 edition. All SQL was rechecked. The new areas covered are:OLAP functions (whole chapter), ISO functions, and identity columns.

    2000-09-25: Some minor layout changes were made.

    2000-10-26: More minor layout changes.

    2001-01-03: Minor layout changes (to match class notes).

    2001-02-06: Minor changes, mostly involving the RAND function.

    2001-04-11: Document new features in latest fixpack. Also add a new chapter on Iden-tity Columns and completely rewrite sub-query chapter.

    2001-10-24: DB2 V7.2 fixpack 4 edition. Tested all SQL and added more examples, plusa new section on the aggregation function.

    2002-03-11: Minor changes, mostly to section on precedence rules.

    2002-08-20: DB2 V8.1 (beta) edition. A few new functions are added. New section ontemporary tables. Identity Column and Join chapters rewritten. Whine chapter removed.

  • 8/14/2019 DB2 V 9.5 Cook book

    6/467

    Graeme Birchall

    6

    2003-01-02: DB2 V8.1 (post-Beta) edition. SQL rechecked. More examples added.

    2003-07-11: New sections added on DML, temporary tables, compound SQL, and userdefined functions. Halting recursion section changed to use user-defined function.

    2003-09-04: New sections on complex joins and history tables. 2003-10-02: Minor changes. Some more user-defined functions.

    2003-11-20: Added "quick find" chapter.

    2003-12-31: Tidied up the SQL in the Recursion chapter, and added a section on themerge statement. Completely rewrote the chapter on materialized query tables.

    2004-02-04: Added select-from-DML section, and tidied up some code. Also managedto waste three whole days due to bugs in Microsoft Word.

    2004-07-23: Rewrote chapter of identity column and sequences. Made DML separatechapter. Added chapters on protecting data and XML functions. Other minor changes.

    2004-11-03: Upgraded to V8.2. Retested all SQL. Documented new SQL features. Somemajor hacking done on the GROUP BY chapter.

    2005-04-15: Added short section on cursors, and a chapter on using SQL to make SQL.

    2005-06-01: Added a chapter on triggers.

    2005-11-11: Updated MQT table chapter and added bibliography. Other minor changes.

    2005-12-01: Applied fixpack 10. Changed my website name.

    2005-12-16: Added notes on isolation levels, data-type functions, transforming data.

    2006-01-26: Fixed dumb bugs generated by WORD. What stupid software. Also wrotean awesome new section on joining meta-data to real data.

    2006-02-17: Touched up the section on joining meta-data to real data. Other minor fixes.

    2006-02-27: Added precedence rules for SQL statement processing, and a description ofa simplified nested table expression.

    2006-03-23: Added better solution to avoid fetching the same row twice. 2006-04-26: Added trigger that can convert HEX value to number.

    2006-09-08: Upgraded to V9.1. Retested SQL. Removed the XML chapter as it is nowobsolete. I'm still cogitating about XQuery. Looks hard. Added some awesome java code.

    2006-09-13: Fixed some minor problems in the initial V9.1 book.

    2006-10-17: Fixed a few cosmetic problems that were bugging me.

    2006-11-06: Found out that IBM had removed the "UDB" from the DB2 product name,so I did the same. It is now just plain "DB2 V9".

    2006-11-29: I goofed. Turns out DB2 is now called "DB2 9". I relabeled accordingly.

    2006-12-15: Improved code to update or delete first "n" rows.

    2007-02-22: Get unique timestamp values during multi-row insert. Other minor changes. 2007-11-20: Finished the DB2 V9.5 edition. Lots of changes!

  • 8/14/2019 DB2 V 9.5 Cook book

    7/467

    DB2 V9.5 Cookbook

    Table of Contents 7

    Table of Contents

    PREFACE.............................................................................................................................. 3

    AUTHOR NOTES .................................................................................................................... 4

    BOOK EDITIONS .................................................................................................................... 5

    TABLE OF CONTENTS ............................................................................................................ 7

    QUICK FIND ........................................................................................................................ 17Index of Concepts......... ................ ................. ................ ................. ................ ................ .................... ......... 17

    INTRODUCTION TO SQL....................................................................................................... 21Syntax Diagram Conventions.............................................................................................................................................. 21SQL Components .............. ................. ................ ................. ................ ................ .................... ................ .... 22DB2 Objects........................................................................................................................................................................ 22DB2 Data Types ................................................................................................................................................................. 24DECFLOAT Arithmetic........................................................................................................................................................ 25Date/Time Arithmetic .......................................................................................................................................................... 27DB2 Special Registers........................................................................................................................................................ 29Distinct Types ..................................................................................................................................................................... 31Fullselect, Subselect, & Common Table Expression. .......... .......... .......... .......... .......... .......... .......... ........... ........... .......... .... 32SELECT Statement............................................................................................................................................................. 33FETCH FIRST Clause ........................................................................................................................................................ 35Correlation Name................................................................................................................................................................ 36Renaming Fields................................................................................................................................................................. 36Working with Nulls .............................................................................................................................................................. 37Quotes and Double-quotes................................................................................................................................................. 38SQL Predicates ................ ................. ................ ................. ................ ................ ................... ................. ...... 38Basic Predicate................................................................................................................................................................... 39Quantified Predicate ........................................................................................................................................................... 39BETWEEN Predicate.......................................................................................................................................................... 40EXISTS Predicate............................................................................................................................................................... 40IN Predicate........................................................................................................................................................................ 41LIKE Predicate.................................................................................................................................................................... 41NULL Predicate .................................................................................................................................................................. 43Special Character Usage.................................................................................................................................................... 43Precedence Rules............................................................................................................................................................... 43Processing Sequence......................................................................................................................................................... 44CAST Expression........ ................ ................ ................ ................. ................ ................ .................... ............ 45VALUES Statement..... ................. ................ ................ ................ ................ ................ .................... ............ 46CASE Expression ............... ................. ................ ................ ................ ................ .................... ................ .... 49CASE Syntax Styles ........................................................................................................................................................... 49Sample SQL ....................................................................................................................................................................... 50Miscellaneous SQL Statements .............. ................ ................. ................ ................ ................ .................. 53Cursor................................................................................................................................................................................. 53Select Into........................................................................................................................................................................... 55Prepare............................................................................................................................................................................... 55Describe ............................................................................................................................................................................. 55Execute............................................................................................................................................................................... 56Execute Immediate ............................................................................................................................................................. 56Set Variable........................................................................................................................................................................ 56

  • 8/14/2019 DB2 V 9.5 Cook book

    8/467

    Graeme Birchall

    8

    Set DB2 Control Structures .................................................................................................................................................57Unit-of-Work Processing......... ................ ................ ................ ................ ................. ................... ................ 57Commit................................................................................................................................................................................57Savepoint ............................................................................................................................................................................58Release Savepoint ..............................................................................................................................................................59Rollback ..............................................................................................................................................................................59

    DATA MANIPULATION LANGUAGE.........................................................................................61 Insert ................ ................ ................ ................ ................ ................. ................ .................... ................ ........ 61Update.......... ................. ................ ................. ................ ................ ................. ................... ................. .......... 65Delete ............... ................ ................. ................ ................ ................. ................ ................... ................ ........ 68Select DML Changes ................. ................ ................ ................. ................ ................. ................... ............. 70Merge ............... ................ ................ ................. ................ ................ ................ .................... ................ ........ 73

    COMPOUND SQL.................................................................................................................79 Introduction............... ................ ................ ................. ................ ................. ................ .................... ............. 79Statement Delimiter.............................................................................................................................................................79SQL Statement Usage ............... ................. ................ ................ ................. ................ ................... ............. 80DECLARE Variables............................................................................................................................................................80FOR Statement ...................................................................................................................................................................81GET DIAGNOSTICS Statement ..........................................................................................................................................81IF Statement........................................................................................................................................................................81ITERATE Statement............................................................................................................................................................82LEAVE Statement ...............................................................................................................................................................83SIGNAL Statement..............................................................................................................................................................83WHILE Statement................................................................................................................................................................83Other Usage ............... ................ ................ ................ ................. ................ ................ .................... ............. 84Trigger.................................................................................................................................................................................85Scalar Function ...................................................................................................................................................................85Table Function.....................................................................................................................................................................86

    COLUMN FUNCTIONS ...........................................................................................................89 Introduction .........................................................................................................................................................................89Column Functions, Definitions......... ................ ................. ................ ................ ................. .................... .... 89ARRAY_AGG......................................................................................................................................................................89AVG.....................................................................................................................................................................................89CORRELATION ..................................................................................................................................................................91COUNT ...............................................................................................................................................................................91COUNT_BIG .......................................................................................................................................................................92COVARIANCE.....................................................................................................................................................................92GROUPING.........................................................................................................................................................................93MAX ....................................................................................................................................................................................93MIN .....................................................................................................................................................................................94Regression Functions..........................................................................................................................................................95STDDEV..............................................................................................................................................................................95SUM....................................................................................................................................................................................96VAR or VARIANCE..............................................................................................................................................................96

    OLAPFUNCTIONS ..............................................................................................................97 Introduction............... ................ ................ ................. ................ ................. ................ .................... ............. 97The Bad Old Days...............................................................................................................................................................97Concepts ................ ................. ................ ................. ................ ................ ................. ................... ................ 98PARTITION Expression.....................................................................................................................................................100Window Definition..............................................................................................................................................................101ROWS vs. RANGE............................................................................................................................................................103ORDER BY Expression.....................................................................................................................................................104Nulls Processing................................................................................................................................................................105OLAP Functions......... ................ ................. ................ ................ ................. ................ ................... ........... 106RANK and DENSE_RANK ................................................................................................................................................106

  • 8/14/2019 DB2 V 9.5 Cook book

    9/467

    DB2 V9.5 Cookbook

    Table of Contents 9

    ROW_NUMBER ............................................................................................................................................................... 110FIRST_VALUE and LAST_VALUE ................................................................................................................................... 117LAG and LEAD................................................................................................................................................................. 118Aggregation ...................................................................................................................................................................... 119

    SCALAR FUNCTIONS ......................................................................................................... 125Introduction....................................................................................................................................................................... 125Sample Data..................................................................................................................................................................... 125Scalar Functions, Definitions ................. ................. ................ ................. ................. .................. ............. 125ABS or ABSVAL ............................................................................................................................................................... 125ACOS ............................................................................................................................................................................... 126ASCII................................................................................................................................................................................ 126ASIN................................................................................................................................................................................. 126ATAN................................................................................................................................................................................ 126ATAN2 .............................................................................................................................................................................. 126ATANH ............................................................................................................................................................................. 126BIGINT.............................................................................................................................................................................. 126BIT Functions.................................................................................................................................................................... 127BLOB................................................................................................................................................................................ 130CARDINALITY.................................................................................................................................................................. 130CEIL or CEILING .............................................................................................................................................................. 130CHAR ............................................................................................................................................................................... 131CHARACTER_LENGTH ................................................................................................................................................... 133CHR.................................................................................................................................................................................. 134CLOB................................................................................................................................................................................ 134COALESCE...................................................................................................................................................................... 134COLLATION_KEY_BIT..................................................................................................................................................... 135COMPARE_DECFLOAT................................................................................................................................................... 136CONCAT .......................................................................................................................................................................... 136COS.................................................................................................................................................................................. 137COSH............................................................................................................................................................................... 137COT.................................................................................................................................................................................. 137DATAPARTITIONNUM..................................................................................................................................................... 137DATE................................................................................................................................................................................ 138DAY.................................................................................................................................................................................. 138DAYNAME........................................................................................................................................................................ 139DAYOFWEEK................................................................................................................................................................... 139DAYOFWEEK_ISO........................................................................................................................................................... 139DAYOFYEAR.................................................................................................................................................................... 140DAYS................................................................................................................................................................................ 140DBCLOB........................................................................................................................................................................... 140DBPARTITIONNUM.......................................................................................................................................................... 141DECFLOAT....................................................................................................................................................................... 141DEC or DECIMAL............................................................................................................................................................. 141DECODE .......................................................................................................................................................................... 142DECRYPT_BIN and DECRYPT_CHAR............................................................................................................................ 142DEGREES........................................................................................................................................................................ 143DEREF ............................................................................................................................................................................. 143DIFFERENCE................................................................................................................................................................... 143DIGITS.............................................................................................................................................................................. 143DOUBLE or DOUBLE_PRECISION.................................................................................................................................. 144ENCRYPT......................................................................................................................................................................... 144EVENT_MON_STATE...................................................................................................................................................... 145EXP .................................................................................................................................................................................. 145FLOAT.............................................................................................................................................................................. 145FLOOR............................................................................................................................................................................. 145GENERATE_UNIQUE ...................................................................................................................................................... 145GETHINT.......................................................................................................................................................................... 147GRAPHIC ......................................................................................................................................................................... 148GREATEST ...................................................................................................................................................................... 148HASHEDVALUE............................................................................................................................................................... 148HEX.................................................................................................................................................................................. 148HOUR............................................................................................................................................................................... 149IDENTITY_VAL_LOCAL ................................................................................................................................................... 149INSERT ............................................................................................................................................................................ 149INT or INTEGER............................................................................................................................................................... 150

  • 8/14/2019 DB2 V 9.5 Cook book

    10/467

    Graeme Birchall

    10

    JULIAN_DAY.....................................................................................................................................................................150LCASE or LOWER............................................................................................................................................................152LEAST...............................................................................................................................................................................152LEFT .................................................................................................................................................................................152LENGTH............................................................................................................................................................................153

    LN or LOG.........................................................................................................................................................................153LOCATE............................................................................................................................................................................153LOG or LN.........................................................................................................................................................................154LOG10...............................................................................................................................................................................154LONG_VARCHAR.............................................................................................................................................................154LONG_VARGRAPHIC.......................................................................................................................................................154LOWER.............................................................................................................................................................................154LTRIM ...............................................................................................................................................................................154MAX ..................................................................................................................................................................................154MAX_CARDINALITY.........................................................................................................................................................155MICROSECOND ...............................................................................................................................................................155MIDNIGHT_SECONDS.....................................................................................................................................................155MIN ...................................................................................................................................................................................156MINUTE ............................................................................................................................................................................156MOD..................................................................................................................................................................................156MONTH.............................................................................................................................................................................156MONTHNAME...................................................................................................................................................................156MULTIPLY_ALT ................................................................................................................................................................157NORMALIZE_DECFLOAT.................................................................................................................................................157NULLIF..............................................................................................................................................................................158NVL...................................................................................................................................................................................158OCTET_LENGTH..............................................................................................................................................................158OVERLAY .........................................................................................................................................................................158PARTITION.......................................................................................................................................................................159POSITION.........................................................................................................................................................................159POSSTR ...........................................................................................................................................................................160POWER.............................................................................................................................................................................160QUANTIZE........................................................................................................................................................................161QUARTER.........................................................................................................................................................................161RADIANS ..........................................................................................................................................................................161RAISE_ERROR.................................................................................................................................................................161RAND................................................................................................................................................................................162REAL.................................................................................................................................................................................165REPEAT............................................................................................................................................................................166REPLACE .........................................................................................................................................................................166RID....................................................................................................................................................................................166RID_BIT ............................................................................................................................................................................167RIGHT...............................................................................................................................................................................168ROUND .............................................................................................................................................................................168RTRIM...............................................................................................................................................................................169SECLABEL Functions .......................................................................................................................................................169SECOND...........................................................................................................................................................................169SIGN .................................................................................................................................................................................169SIN....................................................................................................................................................................................169SINH..................................................................................................................................................................................169SMALLINT.........................................................................................................................................................................170SNAPSHOT Functions......................................................................................................................................................170SOUNDEX ........................................................................................................................................................................170SPACE..............................................................................................................................................................................171SQRT................................................................................................................................................................................171STRIP................................................................................................................................................................................171SUBSTR............................................................................................................................................................................172TABLE...............................................................................................................................................................................173TABLE_NAME...................................................................................................................................................................173TABLE_SCHEMA..............................................................................................................................................................173TAN...................................................................................................................................................................................174TANH ................................................................................................................................................................................174TIME..................................................................................................................................................................................174TIMESTAMP .....................................................................................................................................................................174TIMESTAMP_FORMAT ....................................................................................................................................................175TIMESTAMP_ISO .............................................................................................................................................................175TIMESTAMPDIFF .............................................................................................................................................................175

  • 8/14/2019 DB2 V 9.5 Cook book

    11/467

    DB2 V9.5 Cookbook

    Table of Contents 11

    TO_CHAR......................................................................................................................................................................... 176TO_DATE......................................................................................................................................................................... 176TOTALORDER ................................................................................................................................................................. 176TRANSLATE..................................................................................................................................................................... 177TRIM................................................................................................................................................................................. 178

    TRUNC or TRUNCATE..................................................................................................................................................... 178TYPE_ID........................................................................................................................................................................... 178TYPE_NAME.................................................................................................................................................................... 178TYPE_SCHEMA............................................................................................................................................................... 178UCASE or UPPER............................................................................................................................................................ 178VALUE.............................................................................................................................................................................. 179VARCHAR........................................................................................................................................................................ 179VARCHAR_BIT_FORMAT................................................................................................................................................ 179VARCHAR_FORMAT....................................................................................................................................................... 179VARCHAR_FORMAT_BIT................................................................................................................................................ 179VARGRAPHIC.................................................................................................................................................................. 179WEEK............................................................................................................................................................................... 180WEEK_ISO....................................................................................................................................................................... 180YEAR................................................................................................................................................................................ 180"+" PLUS........................................................................................................................................................................... 181"-" MINUS ......................................................................................................................................................................... 181"*" MULTIPLY ................................................................................................................................................................... 181"/" DIVIDE ......................................................................................................................................................................... 182"||" CONCAT ..................................................................................................................................................................... 182

    USER DEFINED FUNCTIONS ............................................................................................... 183Sourced Functions ............... ................ ................. ................ ................ ................. .................... ............... 183Scalar Functions................. ................ ................ ................. ................ ................. ................... ................ .. 185Description........................................................................................................................................................................ 185Examples.......................................................................................................................................................................... 186Table Functions .............. ................. ................ ................. ................ ................ .................... ................. .... 190Description........................................................................................................................................................................ 190Examples.......................................................................................................................................................................... 191Useful User-Defined Functions .............. ................. ................ ................. ................ ................ ................ 192Julian Date Functions ....................................................................................................................................................... 192Get Prior Date................................................................................................................................................................... 192Generating Numbers......................................................................................................................................................... 194Check Data Value Type.................................................................................................................................................... 195

    ORDER BY,GROUP BY, AND HAVING................................................................................. 199Order By ................ ................ ................ ................ ................. ................ ................ .................... ................ 199Notes................................................................................................................................................................................ 199Sample Data..................................................................................................................................................................... 199Order by Examples........................................................................................................................................................... 200Group By and Having ............... ................ ................ ................ ................ ................ .................... ............. 202Rules and Restrictions...................................................................................................................................................... 202GROUP BY Flavors .......................................................................................................................................................... 203GROUP BY Sample Data ................................................................................................................................................. 204Simple GROUP BY Statements........................................................................................................................................ 204GROUPING SETS Statement........................................................................................................................................... 205ROLLUP Statement.......................................................................................................................................................... 209CUBE Statement............................................................................................................................................................... 213Complex Grouping Sets - Done Easy ............................................................................................................................... 216Group By and Order By .................................................................................................................................................... 218Group By in Join............................................................................................................................................................... 218COUNT and No Rows....................................................................................................................................................... 219

    JOINS ............................................................................................................................... 221Why Joins Matter.............................................................................................................................................................. 221Sample Views ................................................................................................................................................................... 221Join Syntax......... ................ ................ ................. ................ ................ ................ ..................... ................ .. 221Query Processing Sequence ............................................................................................................................................ 223

  • 8/14/2019 DB2 V 9.5 Cook book

    12/467

    Graeme Birchall

    12

    ON vs. WHERE.................................................................................................................................................................223Join Types ............... ................ ................ ................. ................ ................. ................ ................... .............. 224Inner Join ..........................................................................................................................................................................224Left Outer Join...................................................................................................................................................................225Right Outer Join ................................................................................................................................................................227Full Outer Joins.................................................................................................................................................................228Cartesian Product..............................................................................................................................................................232Join Notes .............. ................. ................ ................. ................ ................ ................. ................... .............. 234Using the COALESCE Function ........................................................................................................................................234Listing non-matching rows only .........................................................................................................................................234Join in SELECT Phrase.....................................................................................................................................................236Predicates and Joins, a Lesson.........................................................................................................................................238Joins - Things to Remember..............................................................................................................................................239Complex Joins...................................................................................................................................................................240

    SUB-QUERY ......................................................................................................................243 Sample Tables ..................................................................................................................................................................243Sub-query Flavours ................ ................. ................ ................ ................. ................ ................... .............. 243Sub-query Syntax..............................................................................................................................................................243Correlated vs. Uncorrelated Sub-Queries..........................................................................................................................250Multi-Field Sub-Queries.....................................................................................................................................................251Nested Sub-Queries..........................................................................................................................................................251Usage Examples ................ ................. ................ ................ ................. ................ ................... ................ ... 252True if NONE Match..........................................................................................................................................................252True if ANY Match.............................................................................................................................................................253True if TEN Match.............................................................................................................................................................254True if ALL match..............................................................................................................................................................255

    UNION,INTERSECT, AND EXCEPT .......................................................................................257 Syntax Diagram.................................................................................................................................................................257Sample Views....................................................................................................................................................................257Usage Notes.............. ................. ................ ................ ................. ................ ................. ................... ........... 258Union & Union All ..............................................................................................................................................................258Intersect & Intersect All......................................................................................................................................................258Except, Except All, & Minus...............................................................................................................................................258Precedence Rules .............................................................................................................................................................259Unions and Views..............................................................................................................................................................260

    MATERIALIZED QUERY TABLES ..........................................................................................261 Introduction .......................................................................................................................................................................261Usage Notes.............. ................. ................ ................ ................. ................ ................. ................... ........... 261Syntax Options ..................................................................................................................................................................262Select Statement...............................................................................................................................................................263Optimizer Options..............................................................................................................................................................264Refresh Deferred Tables ...................................................................................................................................................266Refresh Immediate Tables.................................................................................................................................................267Usage Notes and Restrictions ...........................................................................................................................................269Multi-table Materialized Query Tables ...............................................................................................................................270Indexes on Materialized Query Tables ..............................................................................................................................272Organizing by Dimensions.................................................................................................................................................273Using Staging Tables ........................................................................................................................................................273

    IDENTITY COLUMNS AND SEQUENCES.................................................................................275 Identity Columns........... ................ ................ ................ ................ ................ ................ ..................... ........ 275Rules and Restrictions.......................................................................................................................................................276Altering Identity Column Options .......................................................................................................................................279Gaps in Identity Column Values ........................................................................................................................................280IDENTITY_VAL_LOCAL Function.....................................................................................................................................281Sequences.................. ................ ................ ................. ................ ................. ................ ................... ........... 283Getting the Sequence Value..............................................................................................................................................283Multi-table Usage ..............................................................................................................................................................285

  • 8/14/2019 DB2 V 9.5 Cook book

    13/467

    DB2 V9.5 Cookbook

    Table of Contents 13

    Counting Deletes .............................................................................................................................................................. 287Identity Columns vs. Sequences - a Comparison......... .......... .......... .......... .......... ........... .......... .......... ........... .......... ......... 287Roll Your Own ............... ................ ................. ................ ................ ................ ................ .................... ........ 288Support Multi-row Inserts.................................................................................................................................................. 289

    TEMPORARY TABLES ........................................................................................................ 293Introduction................ ................ ................ ................. ................ ................. ................ .................... .......... 293Temporary Tables - in Statement ................ ................. ................. ................ ................. ................... ....... 295Common Table Expression............................................................................................................................................... 296Full-Select......................................................................................................................................................................... 298Declared Global Temporary Tables ............... ................. ................ ................ ................. .................... .... 302

    RECURSIVE SQL .............................................................................................................. 305Use Recursion To ............................................................................................................................................................. 305When (Not) to Use Recursion ........................................................................................................................................... 305How Recursion Works............. ................. ................ ................ ................ ................ .................... ............. 305List Dependents of AAA.................................................................................................................................................... 306Notes & Restrictions ......................................................................................................................................................... 307Sample Table DDL & DML................................................................................................................................................ 307Introductory Recursion ................ ................ ................ ................. ................ ................. .................... ....... 308List all Children #1 ............................................................................................................................................................ 308List all Children #2 ............................................................................................................................................................ 308List Distinct Children......................................................................................................................................................... 309Show Item Level ............................................................................................................................................................... 309Select Certain Levels ........................................................................................................................................................ 310Select Explicit Level.......................................................................................................................................................... 311Trace a Path - Use Multiple Recursions............................................................................................................................ 311Extraneous Warning Message.......................................................................................................................................... 312Logical Hierarchy Flavours........... ................ ................. ................ ................. ................ ................... ....... 313Divergent Hierarchy.......................................................................................................................................................... 313Convergent Hierarchy....................................................................................................................................................... 314Recursive Hierarchy.......................................................................................................................................................... 314Balanced & Unbalanced Hierarchies............ ........... .......... .......... .......... .......... .......... .......... .......... ............ .......... ........... ... 315Data & Pointer Hierarchies................................................................................................................................................ 315Halting Recursive Processing ................. ................ ................ ................. ................ ................... ............. 316Sample Table DDL & DML................................................................................................................................................ 316Stop After "n" Levels ......................................................................................................................................................... 317Stop When Loop Found .................................................................................................................................................... 318Keeping the Hierarchy Clean............................................................................................................................................ 321Clean Hierarchies and Efficient Joins ................ ................. ................ ................. ................. .................. 323Introduction....................................................................................................................................................................... 323Limited Update Solution.................................................................................................................................................... 323Full Update Solution.......................................................................................................................................................... 325

    TRIGGERS......................................................................................................................... 329Trigger Syntax.......... ................ ................ ................ ................ ................ ................. .................... ............. 329Usage Notes ..................................................................................................................................................................... 329Trigger Usage................................................................................................................................................................... 330

    Trigger Examples.......... ................ ................. ................ ................ ................ ................ ..................... ....... 331Sample Tables.................................................................................................................................................................. 331Before Row Triggers - Set Values..................................................................................................................................... 331Before Row Trigger - Signal Error..................................................................................................................................... 332After Row Triggers - Record Data States .......................................................................................................................... 332After Statement Triggers - Record Changes ..................................................................................................................... 333Examples of Usage........................................................................................................................................................... 334

    PROTECTING YOUR DATA.................................................................................................. 337Sample Application .............. ................ ................ ................. ................ ................ ..................... ............... 337Enforcement Tools............................................................................................................................................................ 338

  • 8/14/2019 DB2 V 9.5 Cook book

    14/467

    Graeme Birchall

    14

    Distinct Data Types ...........................................................................................................................................................339Customer-Balance Table...................................................................................................................................................339US-Sales Table.................................................................................................................................................................340Triggers.............................................................................................................................................................................341Conclusion ........................................................................................................................................................................344

    RETAINING A RECORD .......................................................................................................347

    Schema Design ............... ................ ................ ................ ................. ................ ................ .................... ...... 347Recording Changes...........................................................................................................................................................347Multiple Versions of the World...........................................................................................................................................350

    USING SQL TO MAKE SQL................................................................................................357 Export Command.... ................ ................. ................ ................ ................. ................ ................... .............. 357SQL to Make SQL .............................................................................................................................................................358

    RUNNING SQLWITHIN SQL ..............................................................................................361Introduction............... ................ ................ ................. ................ ................. ................ .................... ........... 361Generate SQL within SQL.................................................................................................................................................361Make Query Column-Independent.....................................................................................................................................362Business Uses...................................................................................................................................................................363Meta Data Dictionaries ......................................................................................................................................................364DB2 SQL Functions ................. ................ ................ ................. ................ ................. .................. .............. 364Function and Stored Procedure Used................................................................................................................................364Different Data Types..........................................................................................................................................................365Usage Examples ...............................................................................................................................................................366Java Functions.......... ................ ................. ................ ................. ................ ................ .................... ........... 368Scalar Functions................................................................................................................................................................368Tabular Functions..............................................................................................................................................................369Transpose Function...........................................................................................................................................................372Update Real Data using Meta-Data ................. ................ ................ ................. ................ ................... ..... 379Usage Examples ...............................................................................................................................................................380

    FUN WITH SQL..................................................................................................................385 Creating Sample Data.............. ................ ................ ................. ................ ................. .................. .............. 385Data Generation................................................................................................................................................................385Make Reproducible Random Data.....................................................................................................................................385Make Random Data - Different Ranges.............................................................................................................................386Make Random Data - Varying Distribution.........................................................................................................................386Make Random Data - Different Flavours ...........................................................................................................................387Make Test Table & Data....................................................................................................................................................387Time-Series Processing ............... ................ ................. ................ ................ ................ .................... ........ 389Find Overlapping Rows .....................................................................................................................................................390Find Gaps in Time-Series..................................................................................................................................................391Show Each Day in Gap .....................................................................................................................................................392Other Fun Things............... ................ ................ ................. ................ ................. ................... ................ ... 392Randomly Sample Data.....................................................................................................................................................392Convert Character to Numeric...........................................................................................................................................394Convert Number to Character.......................................................................................