Oracle SQL Jumpstart with Examples will be a very useful reference andshould be a hit for anyone who may be using Oracle SQL.. Addition-ally, the examples in the book provide a good refe
Trang 2Oracle SQL
Jumpstart with Examples
Trang 3This page intentionally left blank
Trang 4Oracle SQL
Jumpstart with Examples
Gavin Powell Carol McCullough-Dieter
AMSTERDAM • BOSTON • HEIDELBERG • LONDON NEW YORK • OXFORD • PARIS • SAN DIEGO•
SAN FRANCISCO • SINGAPORE • SYDNEY • TOKYO
Trang 5Elsevier Digital Press
200 Wheeler Road, Burlington, MA 01803, USALinacre House, Jordan Hill, Oxford OX2 8DP, UKCopyright © 2005, Elsevier Inc All rights reserved
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, or otherwise, without the prior written permission of the publisher Permissions may be sought directly from Elsevier’s Science & Technology Rights Department in Oxford, UK: phone: (+44) 1865 843830, fax: (+44) 1865 853333, e-mail: permissions@elsevier.com.uk You may also complete your request on-line via the Elsevier homepage (http://elsevier.com), by selecting “Customer Support” and then “Obtaining Permissions.”
Recognizing the importance of preserving what has been written, Elsevier prints its books on acid-free paper whenever possible
Library of Congress Cataloging-in-Publication Data
Application submitted
ISBN: 1-55558-323-7
British Library Cataloguing-in-Publication Data
A catalogue record for this book is available from the British Library
For information on all Digital Press publications visit our Web site at www.digitalpress.com and www.bh.com/digitalpress
04 05 06 07 08 09 10 9 8 7 6 5 4 3 2 1Printed in the United States of America
Powell_title.fm Page 4 Friday, July 30, 2004 10:10 AM
Trang 9viii Table of Contents
Database 10g 45
powellTOC.fm Page viii Thursday, July 29, 2004 9:57 PM
Trang 11x Table of Contents
powellTOC.fm Page x Thursday, July 29, 2004 9:57 PM
Trang 1210.3.3.3 Full Outer Join 22410.3.4 Self-Join 225
Trang 13xii Table of Contents
15.2.1 Locks 318
powellTOC.fm Page xii Thursday, July 29, 2004 9:57 PM
Trang 1415.4.1 Updating One Row 331
Trang 15xiv Table of Contents
powellTOC.fm Page xiv Thursday, July 29, 2004 9:57 PM
Trang 1619.3.2 Creating Constraint Views 429
Trang 17xvi Table of Contents
21.1.5 More Indexing Refinements 483
powellTOC.fm Page xvi Thursday, July 29, 2004 9:57 PM
Trang 1824 Basic PL/SQL 531
Trang 19xviii Table of Contents
powellTOC.fm Page xviii Thursday, July 29, 2004 9:57 PM
Trang 20As a consultant with more than 12 years of experience working with Oracledatabases on a daily basis, reviewing this book was a unique and enjoyableexperience The SQL language is without doubt one of the most criticaldatabase skills and it is best learned by example This book addresses thatcrucial need Mr Powell does an excellent job of clarifying the concepts byusing meaningful and easy to understand examples Frankly, I have not come across any other book on SQL that is as good a compilation of SQL concepts in a single source.
Oracle SQL Jumpstart with Examples will be a very useful reference andshould be a hit for anyone who may be using Oracle SQL This bookshould become very popular not only with Developers and DBAs but alsoDatabase Managers, Designers and System Managers Even busy executivescan use the book to quickly write queries on an occasional basis Addition-ally, the examples in the book provide a good reference for functional peo-ple, (such as systems engineers and project leaders,) who want a betterunderstanding of the true capabilities of Oracle SQL, allowing for betterarticulation and understanding of user and system requirements
One comes across very few books that make a significant difference inthe fundamental understanding of a subject This is one such book if youwant to understand a core database skill – Oracle SQL This book deserves
a place in your secret library and you will find it a great reference not onlyfor learning SQL but also for learning data relationships, data organization,data analysis possibilities and so forth I feel that the title, Oracle SQLJumpstart with Examples, might be too simplistic to describe the content.Read on, you will find the real value hidden inside this book
– Ravi Sharma—Senior Principal Consultant
Trang 21This page intentionally left blank
Trang 22Welcome to Oracle SQL Jumpstart with Examples!The title of this book was originally Oracle SQL Reference, but duringthe writing process, we set our hearts on the new title Oracle SQL Jumpstart
ref-erence manual simply by the nature of its structure and content However,
it is a reference manual with much added usefulness The book contains anabsolute plethora of properly tested example Oracle SQL code
In my years as a developer and database administrator, I have oftenfound that the quickest solution to a knotty coding problem is resolved byfinding simple working examples Therefore this book is targeted at data-base administrators (DBAs), developers, designers, and managers, both tell-ing and showing how to solve problems with Oracle SQL This book isapplicable to anyone who uses Oracle SQL on a daily basis or periodically,
be it for questions about data, application development, finding problems,fine-tuning those problems, or otherwise
This book is full of working examples All examples have been tested and
Exam-ples applicable to Oracle Database 9i are tested in an Oracle9i database aswell as an Oracle10g database Because of the nature of Oracle SQL resid-ing and executing from within an Oracle database, there should be no oper-ating system differences or dependencies
Note: Different operating systems and platforms may require different cle database releases, but it is still unlikely that there will be any differenceswith respect to Oracle SQL
This book is also written to include Oracle SQL contained in both cle Database 10g and Oracle Database 9i Whenever you see that
Trang 23Ora-xxii Preface
indicates an Oracle Database 10g update or enhancement The differencesbetween Oracle Database 10g and Oracle Database 9i are easy to see in thisbook Many Oracle installed sites still run Oracle Database 9i, and perhapseven Oracle Database 8i and earlier versions This means you can use thisbook now and continue to use it when you upgrade to 10g in the future.This book is unique Because I am an experienced techie myself, I tend
to write what I would like to read Never in my career of pulling Oraclebooks off a shelf and paging through them have I found a book with asmany examples, covering as many different aspects of Oracle SQL Not totoot my own horn, but this book is written as a book that people like mewould want to read because it is written by me, for me and my own per-sonal use To reiterate, this book is useful not only as a reference manual forOracle SQL but also as a basis for rapidly solving coding problems Simplylook it up and copy the example!
In addition, this book also contains chapters covering Oracle SQL asapplied to XML in Oracle, some PL/SQL basics, Oracle Partitioning, plus
All of the scripts written to create the MUSIC database that is usedthroughout this book are found in Appendix A In addition, you can findthe scripts listed on a simple menu on my website at the following URL:1
So what is this book about? This book is about all aspects of OracleSQL, both for DBAs and developers Essentially this book is all about Ora-cle SQL with some interesting additions such as XML, basic PL/SQL pro-gramming, and the basic facts about Oracle Database underlyingarchitecture
Preface.fm Page xxii Thursday, July 29, 2004 9:58 PM
Trang 24Ora-What is the approach in this book? The approach in this book is topresent syntax, and then explain and prove by example So there are twoways in which this book is organized and written that make it unique amongall other Oracle SQL titles First, it is organized like an Oracle SQL referencemanual Second, it is chock full of tested, verified, working examples, cover-ing nearly every aspect of Oracle SQL possible This book is also uniquebecause it does not gloss over details to save paper; it’s all here Readers ofcomputer books are constantly looking for simple examples that actuallywork so they do not have to spend time thinking about solutions for prob-lems The examples in this book are all proofed on Oracle Database 10g.
Why is this book needed? This book is needed because many OracleSQL texts simply present facts without adequate example proof A bookcontaining a thorough analysis of Oracle SQL, plus some of its toys andtricks, is missing from bookshelves and the warehouses of online bookretailers This book fills the void
Who would benefit from reading this book? Anyone using Oraclesoftware, and specifically Oracle SQL users, would benefit from readingthis book This book contains something for everyone from entry level tomore senior experienced Oracle DBAs and programmer/developers, across
a whole range of Oracle SQL tools and methods
What Is in This Book?
Chapter 1 Introduction to Oracle SQL
This chapter discusses relational data modeling history, Normalization,Denormalization, and the origins of SQL and different SQL tools Alsoincluded are Entity Relationship Diagrams for the MUSIC schema TheMUSIC schema is used throughout this book for examples The MUSICschema includes both transactional (OLTP) tables plus fact-dimensionaldata warehouse tables The database does not contain large amounts ofdata Quantity would be important for an Oracle SQL tuning book but not
an Oracle SQL book.2
Trang 25xxiv Preface
Chapter 2 New Features of Oracle SQL
This chapter covers new Oracle SQL and PL/SQL features for both OracleDatabase 10g and Oracle Database 9i
Chapter 3 Oracle Database Architecture
This chapter examines the basic architecture of Oracle Database, includingthe Oracle Instance, datafile physical architecture, database startup andshutdown, followed by brief descriptions of some advanced feature optionssuch as Oracle Partitioning and replication
Chapter 4 The SELECT Statement
Here you will be introduced to the SELECT statement and different querytypes from the mundane to the obscure There is also some analysis onsome basic queries using simple facets of Oracle SQL such as the DUALtable, DISTINCT, and NULLs
Chapter 5 Filtering Rows
This chapter looks at filtering using the WHERE clause, including a briefexamination of expression conditions, logical operators, and Top-N queries
Chapter 6 Sorting Rows
The ORDER BY clause is used for sorting data in various different ners
man-Chapter 7 Operators, Conditions, and Pseudocolumns
Containing referential facts about operators, conditions, and umns in a single chapter is essential This is necessary not only for refer-ence purposes but also as a way of drawing facts together during thereading process
pseudocol-Chapter 8 SQL*Plus and iSQL*Plus Reporting
This chapter covers advanced environmental and formatting settings forusing SQL*Plus and iSQL*Plus
Chapter 9 Single Row Functions
Single row functions used in queries operate as expressions once on eachrow retrieved
Preface.fm Page xxiv Thursday, July 29, 2004 9:58 PM
Trang 26Preface xxv
Chapter 10 Joining Tables
The purpose of a join is to retrieve data from a relational structure in a able or more usable format The result is that joining tables can be fairlycomplex, with various different types of joins possible
read-Chapter 11 Grouping and Summarizing Data
Grouping and summarizing data is complex, involving various types ofgrouping functions from simple aggregation to complex statistical analysis,and OLTP type activities and even multidimensional spreadsheet and mod-eling formats
Chapter 12 Subqueries
Subqueries are perhaps one of the most complex aspects of Oracle SQL.Subqueries can be used for simplification and tuning of Oracle SQL code
Chapter 13 Unusual Query Types
Unusual query types encompass less used and specialized types of queries,including composite queries, hierarchical queries, version flashbacks, andparallel queries
Chapter 14 Expressions
There are many types of simple expressions Expressions are an integral part
of many aspects of Oracle SQL command structure Additionally, thischapter covers two factors new to Oracle Database 10g: Regular Expressionsand the Oracle Expression Filter
Chapter 15 Data Manipulation Language (DML)
DML is the part of Oracle SQL allowing changes to data in an Oracle base Commands include INSERT, UPDATE, DELETE, MERGE, andspecial transactional control commands
data-Chapter 16 Datatypes and Collections
Datatypes range from simple datatypes containing simple numbers toobject reference pointers and collections Oracle SQL collection functionsare also included in this chapter
Trang 27xxvi Preface
Chapter 17 XML in Oracle
Oracle SQL allows for generation and manipulation of XML documents inOracle Database This chapter introduces various aspects of using XML inOracle SQL
Chapter 18 Tables
Tables are the primary and central structure for containing data in a tional database As a result, table syntax and use is fairly complex Thischapter begins a series of chapters covering Oracle Database object use andmanipulation
Con-Chapter 21 Indexes and Clusters
Indexes are special performance-increasing options used as subsets of tabledata sets, often sorted and organized with special high-speed searchingfunctionality such as binary search trees Clusters group sets of datatogether physically for use as preconstructed high-speed access data sources
Chapter 22 Sequences and Synonyms
A sequence is a special Oracle Database object used to maintain sequentialcounters Sequences perform much better than manual counters Synonymsprovide a way to allow reference of database objects across different schemasand even different databases
Trang 28Preface xxvii
Sample Database Used in This Book
The sample database used in this book is called the MUSIC schema TheMUSIC schema contains a small amount of data with both OLTP and cli-ent-server type transactional and data warehouse dimensional/fact tables.Details on the MUSIC schema are covered with explanation and entityrelationship diagrams (ERDs) in Chapter 1 and schema creation scripts inAppendix A Scripts are available from a simple menu on my Web site atwww.oracledbaexpert.com/oracle/OracleSQLJumpstartWithExamples/index.html
Let’s get started
Trang 29This page intentionally left blank
Trang 30For my wife and daughter who tolerated my nightly and often daily vigils atthe keyboard, and to my favorite cat for not trying to sit on the keyboardtoo often
—Gavin Powell
Many thanks to Gavin Powell for spear heading this project His hard work
is evident throughout this fine book And, as always, thanks to my band, Patrick, and son, Blue, for putting up with me even when I stay uplate and ignore them to meet a deadline
hus-—Carol McCullough-Dieter
Trang 31This page intentionally left blank
Trang 32What software do you need to have in order to use this book?
What are the tools for executing SQL?
Sample tables you use in the book
This chapter will examine data modeling, the origins of SQL, softwarerequirements, plus SQL tools and how to use them Finally, we will presentthe MUSIC schema, which is used throughout this book Let’s begin with alittle history
The history of databases is essentially the history of different data modelingtechniques Data modeling techniques have evolved over the last 50 yearsfrom use of simple file systems to relational, object, and object-relationalmodels Figure 1.1 shows the evolution of data modeling techniques
File System Operating system files or “flat” text files There is nological overlay structure