sql functions programmer's reference - buch.de functions programmer’s reference. published by ......

15
SQL Functions Programmer’s Reference

Upload: docong

Post on 09-Jun-2018

286 views

Category:

Documents


0 download

TRANSCRIPT

  • SQL Functions Programmers Reference

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page i

    0764598074.jpg

  • 01_569015 ffirs.qxd 3/29/05 9:44 PM Page ii

  • SQL Functions Programmers Reference

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page i

  • 01_569015 ffirs.qxd 3/29/05 9:44 PM Page ii

  • SQL Functions Programmers Reference

    Arie JonesRyan K. StephensRonald R. Plew

    Robert F. GarrettAlex Kriegel

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page iii

  • SQL Functions Programmers ReferencePublished byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com

    Copyright 2005 by Wiley Publishing, Inc., Indianapolis, Indiana

    Published simultaneously in Canada

    ISBN 13 978-0-7645-6901-2

    ISBN 10 0-7645-6901-5

    Manufactured in the United States of America

    10 9 8 7 6 5 4 3 2 1

    1B/RU/QU/QV/IN

    No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic,mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 UnitedStates Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appro-priate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 CrosspointBlvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at http://www.wiley.com/go/permission.

    LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONSOR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK ANDSPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PAR-TICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THEADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLDWITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OROTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PRO-FESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAM-AGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS ACITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THEPUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDA-TIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAYHAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.

    For general information on our other products and services or to obtain technical support, please contact our Customer CareDepartment within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.

    For technical support, please visit www.wiley.com/techsupport.

    Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in elec-tronic books.

    Library of Congress Cataloging-in-Publication Data:

    SQL functions programmers reference / Arie Jones ... [et al.].

    p. cm.

    Includes bibliographical references and index.

    ISBN 0-7645-6901-5 (paper/website : alk. paper)

    1. SQL (Computer program language) I. Jones, Arie.

    QA76.73.S67S674 2005

    005.133--dc22

    2005002765

    Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trade-marks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and maynot be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., isnot associated with any product or vendor mentioned in this book.

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page iv

    www.wiley.comwww.wiley.com

  • About the Authors

    Arie JonesArie Jones is a senior database administrator for Perpetual Technologies, Inc. (www.perptech.com). He holdsa masters degree in physics from Indiana State University and also works as the chief Web architect/DBAfor the USPFO for Indiana. Aries main specialty is in developing .NET-based database solutions for the gov-ernment. He and his wife and family live outside of Indianapolis, Indiana.

    Ryan K. StephensRyan Stephens is the president and CEO of Perpetual Technologies, Inc. (www.perptech.com), an Indianapolis-based IT firm specializing in database technologies. Ryan has been working with SQL and databases for 15years and has held the positions of project manager, database administrator, and programmer/analyst. Ryanhas been teaching database courses for local universities since 1997 and has authored several internationallypublished books on topics such as database design, SQL, database architecture, database administration, andOracle. Ryan enjoys discovering new ways to optimize the use of technology to streamline business operations,as well as empowering others to do the same. Ryan and his wife live in Indianapolis with their three children.

    Ronald R. PlewRonald R. Plew is vice president and CIO for Perpetual Technologies, Inc. (www.perptech.com) inIndianapolis, Indiana. Ron is a Certified Oracle Professional. He has coauthored several internationallypublished books on SQL and database technology. Ron is also an adjunct professor for VincennesUniversity in Indiana, where he teaches SQL and various database courses. Ron holds a bachelor ofscience degree in business administration/management from Indiana Institute of Technology out of FortWayne, Indiana. Ron recently retired from the Indiana Army National Guard, where he served as aprogrammer/analyst. His hobbies include automobile racing, chess, golf, and collecting Indy 500memorabilia. Ron resides in Indianapolis with his wife Linda.

    Robert F. GarrettBob Garrett is the software development manager at Perpetual Technologies, Inc. (www.perptech.com).Bobs languages of preference are Java, C++, and English. He has extensive experience integrating appli-cations with relational databases. Bob has a degree in computer science and mathematics from PurdueUniversity, and lives with his wife and daughter near Indianapolis.

    Alex KriegelAlex Kriegel is a professional database systems analyst with a major manufacturing firm in Oregon. Hehas more than 10 years of database experience working with Microsoft SQL Server, Oracle, DB2, Sybase,and PostgreSQL both as developer and DBA. Alex has a bachelor of science degree in solid-state physicsfrom State Polytechnic Institute of Minsk, Belarus, and has earned the Microsoft Certified SolutionDeveloper (MCSD) accreditation. He is the author of SQL Bible. Alex wrote the first draft of approxi-mately two-thirds of this book.

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page v

  • Contributing Authors

    Joshua StephensJoshua Stephens is a systems administrator/DBA for Perpetual Technologies, Inc. (www.perptech.com).He has eight years of experience in various IT areas. As a former technical writer and trainer, he contin-ues to enjoy helping others through writing. He holds a bachelor of arts degree in pure mathematics andphysics from Franklin College. He lives in Franklin, Indiana, with his wife and daughter.

    Richard BulleyRichard is a Ferris State University graduate and received a master of arts degree from Ball StateUniversity. He has had 20 years of data processing experience with the United States Air Force and is aUnited States Air Force Reserves Retiree and currently has over six years of experience as a Sybase andMS SQL Server system DBA.

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page vi

  • CreditsAcquisitions EditorJim Minatel

    Development EditorKevin Shafer

    Production EditorGabrielle Nabi

    Technical EditorWiley-Dreamtech India Pvt Ltd

    Copy EditorPublication Services, Inc.

    Editorial ManagerMary Beth Wakefield

    Vice President & Executive Group PublisherRichard Swadley

    Vice President and PublisherJoseph B. Wikert

    Project CoordinatorRyan Steffen

    Graphics and Production SpecialistsApril Farling, Carrie Foster, Denny Hager, Julie Trippetti

    Quality Control TechniciansJoe NiesenJohn Greenough

    Proofreading and IndexingTECHBOOKS Production Services

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page vii

  • I would like to dedicate this book to my wife, Jacqueline, for being understanding and supportive duringthe long hours that it took to complete this book.

    Arie Jones

    For Tina, Daniel, Autumn, and Alivia. You are my inspiration.

    Ryan Stephens

    For Linda

    Ron Plew

    For Becky and Libby

    Bob Garrett

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page viii

  • Acknowledgments

    Shortly after we accepted this project, it became clear how much of a team effort would be needed tomake this book a must-have for anyones SQL library. Fortunately, I have an incredible technical teamthat knows how to come together and get the job done. Most of my thanks go to Arie Jones. Arie steppedup when I needed the most help, unafraid of commitment, confidently accepting another aggressiveassignment. Our author team included Arie Jones, Ron Plew, Bob Garrett, Alex Kriegel, and myself.Contributing authors were Joshua Stephens and Richard Bulley. I cannot say enough about their profes-sionalism and technical proficiency. Thank you for being part of another successful project!

    Probably as no surprise to the Wiley audience, the author team thanks the editorial staff at Wiley, whichis one of the best with whom we have had the pleasure of working. Specifically, we appreciate JimMinatels efforts and confidence in our team, Kevin Shafers strict attention to detail, and the technicaleditorial teams thoroughness. Their dedication, patience, and thoroughness, we believe, reflect directlyon the quality and timely delivery of this book, which would not have been possible without each ofthem, as well as the unmentioned Wiley staff behind the scenes.

    Ryan Stephens and the author team

    01_569015 ffirs.qxd 3/29/05 9:44 PM Page ix

  • 01_569015 ffirs.qxd 3/29/05 9:44 PM Page x

  • Contents

    Acknowledgments ixIntroduction xxxv

    Chapter 1: Exploring Popular SQL Implementations 1

    Introduction to SQL 1Understanding the SQL Standard 2Overview of Vendor Implementations of SQL 2

    Oracle 3IBM DB2 UDB 3Microsoft SQL Server and Sybase 3MySQL 3PostgreSQL 4

    Connecting to SQL Databases 4ANSI SQL Data Types 5Creating SQL Databases 5Querying SQL Databases 7Manipulating Data in SQL Databases 9Summary 11

    Chapter 2: Functions: Concept and Architecture 13

    What Is a Function? 13Simple UNIX Shell Function Example 14Simple SQL Function Example 15

    ANSI SQL Functions 15Built-in Functions 16

    Executing Built-in Functions 17Practical Uses of Functions 17

    Creating, Compiling, and Executing a SQL Function 18Passing Parameters by Value or by Reference 22Scope of a Function 24

    Better Security 25Overloading 25

    Classifying SQL Functions: Deterministic and Non-Deterministic Functions 27Oracle 29IBM DB2 UDB 29

    02_569015 ftoc.qxd 3/29/05 9:43 PM Page xi

  • xii

    Contents

    Microsoft SQL Server 30Sybase 31MySQL and PostgreSQL 31

    Summary 32

    Chapter 3: Comparison of Built-in SQL Functions by Vendor 33

    Types of Functions 33Classifying Built-in SQL Functions 34

    Oracle 35IBM DB2 UDB 36Microsoft SQL Server and Sybase ASE 37MySQL 39PostgreSQL 39

    Overview of Built-in Functions by Vendor 40Summary 48

    Chapter 4: SQL Procedural Extensions and User-Defined Functions 49

    Procedural versus Declarative Languages 49ANSI SQL Guidance for Procedural Extensions to SQL 51SQL Procedural Extensions by Vendor 52

    Oracle PL/SQL 52Microsoft or Sybase Transact-SQL 54IBM Procedural SQL 55MySQL 57PostgreSQL 57

    Summary 58

    Chapter 5: Common ANSI SQL Functions 59

    ANSI Query Syntax 60Aggregate Functions 60

    AVG() 62COUNT() 63MAX() and MIN() 64SUM() 65

    String Functions 65ASCII() 66CHR() or CHAR() 67CONCAT() 67LOWER() and UPPER() 68LENGTH() or LEN() 68REPLACE() 69

    02_569015 ftoc.qxd 3/29/05 9:43 PM Page xii

  • xiii

    Contents

    Mathematical Functions 69ABS() 72ACOS() 73ASIN() 73ATAN() and ATAN2() 74CEIL() or CEILING() and FLOOR() 74COS() 75COSH() 75COT() 75DEGREES() and RADIANS() 76EXP() 76LOG(), LN(), LOG2(), and LOG10() 77MOD() 77PI() 79POWER() 79RAND() 80ROUND() 80SIGN() 81SINH() 82SQUARE() 82SQRT() 83TAN() 83TANH() 83TRUNC() or TRUNCATE() 84

    Miscellaneous Functions 85COALESCE() 85NULLIF() 85

    Summary 86

    Chapter 6: Oracle SQL Functions 87

    Oracle Query Syntax 87Aggregate Functions 90

    AVG() 91CORR() 92COUNT() 93GROUPING() 94MAX() and MIN() 95STDDEV() 95SUM() 96

    Analytic Functions 97

    02_569015 ftoc.qxd 3/29/05 9:43 PM Page xiii