www.it-ebooks.info Beginning Oracle SQL Lex de Haan Daniel Fink Tim Gorman Inger Jørgensen Karen Morton www.it-ebooks.info Beginning Oracle SQL Copyright © 2009 by Lex de Haan, Daniel Fink, Tim Gorman, Inger Jørgensen, Karen Morton All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher ISBN-13 (pbk): 978-1-4302-7197-0 ISBN-13 (electronic): 978-1-4302-7196-3 Printed and bound in the United States of America Trademarked names may appear in this book Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark President and Publisher: Paul Manning Lead Editor: Jonathan Gennick Technical Reviewers: Tim Gorman, Daniel Fink Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes, Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh Coordinating Editor: Jim Markham Copy Editor: Seth Kline Compositor: Bytheway Publishing Services Indexer: Brenda Miller Artist: April Milne Cover Designer: Anna Ishchenko Distributed to the book trade worldwide by Springer-Verlag New York, Inc., 233 Spring Street, 6th Floor, New York, NY 10013 Phone 1-800-SPRINGER, fax 201-348-4505, e-mail orders-ny@springersbm.com, or visit http://www.springeronline.com For information on translations, please contact Apress directly at 2855 Telegraph Avenue, Suite 600, Berkeley, CA 94705 Phone 510-549-5930, fax 510-549-5939, e-mail info@apress.com, or visit http://www.apress.com Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use eBook versions and licenses are also available for most titles For more information, reference our Special Bulk Sales–eBook Licensing web page at http://www.apress.com/info/bulksales The information in this book is distributed on an “as is” basis, without warranty Although every precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work The source code for this book is available to readers from this book’s catalog page at http://www.apress.com The exact link as of this writing is: http://apress.com/book/view/1430271970 www.it-ebooks.info Contents at a Glance Contents at a Glance iii Contents iv About the Authors xvii Acknowledgments xix Introduction xxi Chapter 1: Relational Database Systems and Oracle Chapter 2: Introduction to SQL, AQL*Plus, and SQL Developer 25 Chapter 3: Data Definition, Part I 71 Chapter 4: Retrieval: The Basics 83 Chapter 5: Retrieval: Functions 117 Chapter 6: Data Manipulation .145 Chapter 7: Data Definition, Part II .163 Chapter 8: Retrieval: Multiple Tables and Aggregation 195 Chapter 9: Retrieval: Some Advanced Features 233 Chapter 10: Views .265 Chapter 11: Writing and Automating SQL*Plus Scripts 287 Chapter 12: Object-Relational Features 329 Appendix A: The Seven Case Tables 349 Appendix B: Answers to the Exercises .359 Index 405 iii www.it-ebooks.info CONTENTS Contents Contents at a Glance iii Contents iv About the Authors xvii Acknowledgments xix Introduction xxi Chapter 1: Relational Database Systems and Oracle 1.1 Information Needs and Information Systems 1.2 Database Design Entities and Attributes Generic vs Specific Redundancy Consistency, Integrity, and Integrity Constraints Data Modeling Approach, Methods, and Techniques Semantics Information Systems Terms Review 1.3 Database Management Systems DBMS Components Kernel Data Dictionary Query Languages DBMS Tools iv www.it-ebooks.info CONTENTS Database Applications DBMS Terms Review 1.4 Relational Database Management Systems 10 1.5 Relational Data Structures .10 Tables, Columns, and Rows 11 The Information Principle 12 Datatypes 12 Keys 12 Missing Information and Null Values 13 Constraint Checking 14 Predicates and Propositions 14 Relational Data Structure Terms Review 14 1.6 Relational Operators 15 1.7 How Relational Is My DBMS? 16 1.8 The Oracle Software Environment .17 1.9 Case Tables .19 The ERM Diagram of the Case 19 Table Descriptions 21 Chapter 2: Introduction to SQL, AQL*Plus, and SQL Developer .25 2.1 Overview of SQL 25 Data Definition 26 Data Manipulation and Transactions 26 Retrieval 27 Security 29 Privileges and Roles 29 GRANT and REVOKE 31 2.2 Basic SQL Concepts and Terminology .32 Constants (Literals) 32 v www.it-ebooks.info CONTENTS Variables 34 Operators, Operands, Conditions, and Expressions 34 Arithmetic Operators 35 The Alphanumeric Operator: Concatenation 35 Comparison Operators 35 Logical Operators 36 Expressions 36 Functions 37 Database Object Naming 38 Comments 39 Reserved Words 39 2.3 Introduction to SQL*Plus 39 Entering Commands 40 Using the SQL Buffer 41 Using an External Editor 42 Using the SQL*Plus Editor 43 Using SQL Buffer Line Numbers 46 Using the Ellipsis 48 SQL*Plus Editor Command Review 48 Saving Commands 49 Running SQL*Plus Scripts 51 Specifying Directory Path Specifications 52 Adjusting SQL*Plus Settings 53 Spooling a SQL*Plus Session 56 Describing Database Objects 57 Executing Commands from the Operating System 57 Clearing the Buffer and the Screen 57 SQL*Plus Command Review 57 vi www.it-ebooks.info CONTENTS 2.4 Introduction to SQL Developer 58 Installing and Configuring SQL Developer 58 Connecting to a Database 61 Exploring Objects 62 Entering Commands 63 Run Statement 64 Run Script 65 Saving Commands to a Script 66 Running a Script 67 Chapter 3: Data Definition, Part I 71 3.1 Schemas and Users 71 3.2 Table Creation 72 3.3 Datatypes 73 3.4 Commands for Creating the Case Tables 75 3.5 The Data Dictionary 77 Chapter 4: Retrieval: The Basics 83 4.1 Overview of the SELECT Command 83 4.2 The SELECT Clause 85 Column Aliases 86 The DISTINCT Keyword 87 Column Expressions 87 The DUAL Table 88 Null Values in Expressions 90 4.3 The WHERE Clause 90 4.4 The ORDER BY Clause 91 4.5 AND, OR, and NOT 94 The OR Operator 94 The AND Operator and Operator Precedence Issues 95 vii www.it-ebooks.info CONTENTS The NOT Operator 96 4.6 BETWEEN, IN, and LIKE 98 The BETWEEN Operator 98 The IN Operator 99 The LIKE Operator 100 4.7 CASE Expressions 101 4.8 Subqueries .104 The Joining Condition 105 When a Subquery Returns Too Many Values 106 Comparison Operators in the Joining Condition 107 When a Single-Row Subquery Returns More Than One Row 108 4.9 Null Values .109 Null Value Display 109 The Nature of Null Values 109 The IS NULL Operator 111 Null Values and the Equality Operator 112 Null Value Pitfalls 113 4.10 Truth Tables 114 4.11 Exercises .116 Chapter 5: Retrieval: Functions 117 5.1 Overview of Functions .117 5.2 Arithmetic Functions 119 5.3 Text Functions 121 5.4 Regular Expressions 125 Regular Expression Operators and Metasymbols 126 Regular Expression Function Syntax 127 Influencing Matching Behavior 127 REGEXP_INSTR Return Value 128 viii www.it-ebooks.info CONTENTS REGEXP_LIKE 128 REGEXP_INSTR 129 REGEXP_SUBSTR 130 REGEXP_REPLACE 130 5.5 Date Functions .131 EXTRACT 132 ROUND and TRUNC 133 MONTHS_BETWEEN and ADD_MONTHS 133 NEXT_DAY and LAST_DAY 134 5.6 General Functions 134 GREATEST and LEAST 135 NVL 136 DECODE 136 5.7 Conversion Functions 137 TO_NUMBER and TO_CHAR 138 Conversion Function Formats 139 Datatype Conversion 141 CAST 141 5.8 Stored Functions 142 5.9 Exercises 143 Chapter 6: Data Manipulation .145 6.1 The INSERT Command .146 Standard INSERT Commands 146 INSERT Using Subqueries 149 6.2 The UPDATE Command 151 6.3 The DELETE Command 154 6.4 The MERGE Command .157 6.5 Transaction Processing 159 ix www.it-ebooks.info INDEX sequences and, 185 synonyms and, 186 TRUNCATE command and, 191 data definition commands, 26 data dictionary, 8, 77 access, security and, 77 COMMENT command and, 191 constraint definitions stored in, 173 getting information about views from, 269 semantics and, view column updatability and, 277 data dictionary views, 77–81 abbreviated names for, 79 useful, list of, 80 data independence logical, 17, 26, 273 physical, 17, 178 synonyms and, 188 data integrity, data manipulation, 25, 145–161 commands for, 26 indexes and, 179 inline views and, 281 locking and, 160 read consistency and, 161 testing, 150 transaction processing and, 159 views and, 274–281 data model, semantics of, data modeling, 2, Data Pump, 26 data values, passing from one SQL statement to another, 322, 323 data warehousing, 157, 283 database, defined, database applications, database constraints, database design, 2–7 data modeling for, entities/attributes and, generic vs specific meanings and, maintenance costs and, database links, 188 Database Management System See DBMS database objects naming, 38 viewing structure of, via DESCRIBE command, 57 database technology, benefits of, database users See users databases connecting to via SQL Developer, 61 querying See queries datatypes, 12, 73, 165–167, 329 collection datatypes and, 330 column specification and, 73 conversion functions and, 137–142 datatype conversion and, 141 datatype synonyms and, 165 key, list of, 165 maximum sizes of, 74 user-defined, 329, 339 DATE datatype, 75, 132, 165 date expressions, 132 date functions, 130–134 DATE keyword, 33 DATE literal, 131 Date, Chris, 13, 113 dates, 75, 132–134, 138 NLS_TERRITORY parameter and, 140 specifying in SQL, 33 DAY suffix, 33 DAY TO MINUTE interval, 131 DAY value, 132 DBMS (Database Management System), 7–10 components of, database design and, 2–7 features of, object-relational features of, 329–347 tools for, 9, 18 decimal point, 32 Decision Support Systems (DSS), DECODE function, 135, 136 DEFAULT reserved word, 147, 152 deferrable constraints, 177 DEFERRED option, for deferrable constraints, 177 DEFINE _EDITOR command (SQL*Plus), 49 DEFINE character See ampersand DEFINE command (SQL*Plus) SQL*Plus external editor and, 42 user-defined variables and, 290 DEFINE system variable, 294, 297 DEL command (SQL*Plus), 46, 49 DELETE command, 26, 27, 154–156 subqueries and, 155 updatable join view restrictions and, 276 vs TRUNCATE command, 191 DELETE object privilege, 30 delimiter, SQL*Plus and, 41 409 www.it-ebooks.info INDEX DEPARTMENTS table constraints and, 174 creating, 76 SELECT clause and, 243 DEPTH attribute (DESCRIBE command), 340 derivable data, derivable information, views and, 274 derived tables, 265 desc keyword, 92 DESCRIBE command (SQL*Plus), 57, 79, 146, 340 stored commands and, 143 views and, 269 diagnostic tools, 182 diagram techniques, dict_columns view, 79, 80 DICTIONARY (DICT) view, 78, 80, 81 difference operator, 15, 16, 28 directory path specifications, 52 DISABLE option, for constraints, 170 Display NULL Value AS environment setting, 109 distinct keyword, 87, 105 group functions and, 212, 213 MINUS operator and, 230 nonupdatable views and, 277 SELECT clause, 240 distributed databases, views and, 273 distribution independence, 17 division operator (/), 35 domains, 12 DROP, as keyword, 26 DROP ANY TABLE system privilege, 31 DROP COLUMN clause (ALTER TABLE command), caution for, 168 DROP command, 27 DROP INDEX command, 26 syntax for, 182 DROP SEQUENCE command, 185 DROP STORAGE option (TRUNCATE command), 191 DROP TABLE command, 189 vs DELETE command, 154 vs TRUNCATE command, 191 DROP UNUSED COLUMNS clause (ALTER TABLE command), 168 DROP USER command, 29 DROP VIEW command, 266, 271 DSS (Decision Support Systems), DUAL table, 88, 186 DUAL view, 81 dummy table, 88 duplicate rows, eliminating, 87, 229 duplicate values group functions and, 212 unique indexes and, 180 DUPLICATES option (BREAK command), 313 durations, specifying in SQL, 33 dynamic performance views, 79 dynamic SQL, bind variables as component of, 298 E ECHO system variable, 294 EDIT command (SQL*Plus), 43, 49 editors, using with SQL*Plus, 42 ellipses, 48 ELSE expression, CASE expressions and, 102 embedded use of SQL, 25 EMPLOYEES table constraints and, 174 creating, 75 EMPTY operator, 341 empty sets, 239 empty strings, vs null values, 109 ENABLE option, for constraints, 170 entities, 11 database design and, generic level vs specific occurrence of, naming conventions and, entitity integrity, 5, 12 Entity Relationship Modeling (ERM), 6, 19 ENTMAP option (SET MARKUP command), 319 Environment dialog box, SQL*Plus, 54 equal to operator (=), 36, 90 null values and, 112 equijoins, 198, 204 equivalence classes, 127 ERM (Entity Relationship Modeling), 6, 19 error handling, 325 ESCAPE option, LIKE operator and, 101 EXECUTE command (SQL*Plus), 299 EXECUTE object privilege, 30 executing SQL*Plus scripts, 301 exercises, 116 advanced retrieval functions, 264 aggregation, 231 data definition, 193 functions, 143 multiple tables, 231 410 www.it-ebooks.info INDEX object-relational techniques, 346 queries, 116 SQL*Plus scripts, 326 views, 286 EXISTS operator, 238–243 EXIT command (SQL*Plus), 40, 57, 159 EXIT directive (WHENEVER command), 325 Exit-status directive (WHENEVER command), 326 EXP function, 119, 121 EXPLAIN PLAN tool, 182, 184 Export tool, 26 expressions, 34, 36, 137–142 external editors, using with SQL*PLus, 42 EXTRACT function, 132 F FAILURE exit status, WHENEVER command and, 326 FEEDBACK system variable, 294, 295 file names, directory path specifications and, 52 fill mode, 140 FLASHBACK object privilege, 30 flashback queries, 258–263 FLASHBACK TABLE TO BEFORE DROP, 262 FLASHBACK TABLE command, 190, 262 floating point numbers, 32, 165, 167 FLOOR function, 119, 120 fmt (format arguments), 139 FOLD_AFTER option (COLUMN command), 308 FORCE clause (CREATE VIEW command), 266 FOREIGN KEY constraint, 73, 170–172 foreign key references, CREATE SCHEMA command and, 176 foreign keys, 13 format (fmt) arguments, 139 FORMAT command (SQL*Plus), 55 FORMAT option (COLUMN command), 308 Fortran, database design and, four-valued logic, 113 free variables, 238 FROM clause AS OF TIMESTAMP option and, 260 DELETE command and, 155 inline views and, 244 SELECT command syntax and, 28, 84 subqueries and, 244 tuple variable declaration and, 196 VERSIONS BETWEEN operator and, 262 white space and, 86 FROM component (SELECT command), join operator and, 28 FULL OUTER JOINs, 207 function-based indexes, 180 functions, 37, 117–144 analytical, 252–258 categories of (list), 118 group, 211–220 nested, 117, 213 terminology and, 118 G general functions, 134–137 generic, database design and, GET command (SQL*Plus), 51, 52, 302 file manipulation and, 305 glogin.sql script, 305 GRANT command, 30, 31 views and, 274 greater than operator (]), 36 greater than operator (>), 90 greater than or equal to operator (]=), 36 greater than or equal to operator (>=), 90 GREATEST function, 135 GROUP BY clause, 208–211, 214 advanced features of, 222–226 CONNECT BY operator and, 248 group expressions and, 222 group functions and, 211, 213 grouping on additional columns and, 220 HAVING clause and, 217 multiple-column grouping and, 210 nonupdatable views and, 277 null values and, 210 SELECT command syntax and, 28, 84 START WITH operator and, 248 syntax combinations, SELECT clause and, 216 GROUP BY CUBE command, 223, 225 GROUP BY ROLLUP command, 222, 225 group expressions, 222 “Group function is not allowed here” error message, 218, 219 group functions, 208, 211–220 duplicate values and, 212 group expressions and, 222 null values and, 213 411 www.it-ebooks.info INDEX group separators, numbers and, 32 GROUPING function, 224 grouping sets, 224 GROUPING_ID function, 224, 225 guaranteed access rule, 16 H hash symbol (#), 20 HAVING clause, 217–222 analytical functions and, 257 classic SQL error and, 219 functions and, 117 group functions and, 211 SELECT command syntax and, 28, 84 vs WHERE clause, 218 HEAD option (SET MARKUP command), 319 HEADER option (SET MARKUP command), 319 HEADING option (COLUMN command), 308 HEADING system variable, 294 HEADSEP system variable, 294 hierarchical data, 247, 247–252 hierarchical queries hierarchical operators for, 250 result sorting and, 251 high-level insert, update, and delete operations, 17 histograms, 125 HISTORY table constraints and, 176 creating, 76 horizontal comparisons, 135 HOST command (SQL*Plus), 57 HOUR value, 132 HTML, SQL*Plus and, 318–321 I I command (INPUT command), 45, 46, 49 IMMEDIATE option, for deferrable constraints, 177 implicit datatype conversion, 118 implicit user-defined variables, 291 Import tool, 26 IN operator, 99, 342, 239–241 negation option and, 99 subqueries and, 104, 233 inconsistency of data, IND view, 79, 81 INDEX object privilege, 30, 31 indexes, 178–182 bitmap, 180 creating, 179–181 function-based, 180 managing, 181 SQL statement performance and, 179 unique, 180 information, missing, 13, 17, 24 information principle, 12 information rule, 16 information systems, 1, INITCAP function, 122, 123 INITIALLY IMMEDIATE option, for constraints, 177 inline constraints, 164, 170, 172 inline views, 244, 247, 281 vs views, 273 INPUT command (SQL*Plus), 45, 46, 49 input parameters, 322 INSERT command, 26, 146–151 adding rows to table, 26 CREATE TABLE AS SELECT command and, 164 subqueries and, 147, 149 updatable join view restrictions and, 276 views and, 278 INSERT object privilege, 30 instead-of triggers, 278 INSTR function, 122 INSTRB function, 123 integrity, information systems and, integrity constraints, 8, 17 checking, 14 information systems and, integrity independence, 17 interactive use of SQL, 25 internationalization function-based indexes and, 181 NLS_DATE_LANGUAGE and, 138 NLS_LANGUAGE parameter and, 138 INTERSECT operator, 228–231, 277 intersection entities, 20 intersection operator, 15, 16, 28 INTERVAL datatype, 75, 132, 165 INTERVAL keyword, 33 INTERVAL literal, 131 IS NOT EMPTY operator, 343 IS NULL operator, 111, 112 412 www.it-ebooks.info INDEX J Java Development Kit (JDK), 59 JDeveloper, 9, 19, 145 JDK (Java Development Kit), 59 JOIN USING command, 204 join condition, 202 JOIN keyword, 202 JOIN operator, 16, 28, 239–241 join views, updatable, 276, 281 JOIN ON command, 202 joining condition, 105, 107 joins, 197–208 CROSS joins and, 205 equijoins and, 198, 204 grouping results of, 214 natural joins and, 203 non-equijoins and, 199 outer joins and, 205–208 self-joins and, 201 syntax for, 202, 205 three or more tables and, 200 JUSTIFY option (COLUMN command), 308 K kernel, 8, 18 key preserved tables, 276 keys, 12 LIKE operator, 100, 101 LIKE option (COLUMN command), 308 line numbering, 45 LINESIZE system variable, 294 LIST command (SQL*Plus), 41–43, 48 literals See constants LN function, 119, 121 localization function-based indexes and, 181 NLS_DATE_LANGUAGE and, 138 NLS_LANGUAGE parameter and, 138 LOCALTIMESTAMP system variable, 34 locking, 32, 160 LOG function, 119, 121 logical data independence, 17, 26 views and, 273 logical design, 6, 19 logical level, modeling information needs and, logical operators, 36, 94–98 operator precedence and, 95 login.sql script, 305 LOGOUT command (SQL*Plus), 57 LONG system variable, 295 LOWER function, 122, 123 LPAD function, 122, 124 enhancing readability via, 249 LTRIM function, 122 M L L command (LIST command), 41–43, 48 L1 command, 43 LAG function, 255 LAST_DAY function, 132, 134 layout conventions, 199 LEAD function, 255 leap year, 134 LEAST function, 135 LEFT OUTER JOINs, 207 legacy considerations, DECODE function and, 136 LENGTH function, 122, 123 LENGTHB function, 123 less than operator ([), 36 less than operator (