18
ORACLE Oracle Press TM ORACLE8: The Complete Reference George Koch Kevin Loney Osborne McGraw-Hill Berkeley New York St. Louis San Francisco Auckland Bogota Hamburg London Madrid Mexico City Milan Montreal New Delhi Panama City Paris Säo Paulo Singapore Sydney Tokyo Toronto

ORACLE8: The Complete Reference - GBV

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

ORACLE Oracle Press TM

ORACLE8: The Complete Reference

George Koch

Kevin Loney

Osborne McGraw-Hill

Berkeley New York St. Louis San Francisco Auckland Bogota Hamburg London Madrid Mexico City Milan Montreal New Delhi Panama City Paris Säo Paulo Singapore Sydney Tokyo Toronto

Contents

ACKNOWLEDGMENTS, XXVII INTRODUCTION, XXIX

PARTI Critical Database Concepts

1 Sharing Knowledge and Success 3 The Cooperative Approach 6 Everyone Has "Data" 7 The Familiar Language of ORACLE 9

Tables of Information 9 Structured Query Language 10 A Simple ORACLE Query 11 Why It Is Called Relational 13

Some Common, Everyday Examples 15 A 100-Year-Old Example 17

2 The Dangers in a Relational Database 21 Is It Really as Easy as They Say? 22 What Are the Risks? 23 The Importance of the New Vision 24

Changing Environments 25 Codes, Abbreviations, and Naming Standards 26

Why Is Coding Used Instead of English? 27 The Benefit of User Feedback 28

How to Reduce the Confusion 29 Normalization 30 English Names for Tables and Columns 38 English Names for the Data 41

Case in Names and Data 42 Normalizing Names 43 Seizing the Opportunity 43

PART II

SQL: Going from Beginner to Expert

3 The Basic Parts of Speech in SQL 47 Style 50 Using SQL to select Data from Tables 51 select, from, where, and order by 55 Logic and Value 57

Single Value Tests 58 LIKE 62

Simple Tests Against a List of Values 65 Combining Logic 68

Another Use for where—Subqueries 70 Single Values from a Subquery 71 Lists of Values from a Subquery 72

Combining Tables 74 Creating a View 77

Expanding the View of View 79

4 The Basics of Object-Relational Databases 83 Do I Have to Use Objects? 84 Why Should I Use Objects? 85 Everybody Has Objects 86

Abstract Datatypes 87 Nested Tables 88 Varying Arrays 89 Large Objects 89 References 90 Object Views 90 Naming Conventions for Objects 92

A Common Object Example 93 The Structure of a Simple Object 95 Inserting Records into CUSTOMER 98 Selecting from Abstract Datatypes 99

Object-Oriented Analysis and Design 102 Going Forward 104

5 Basic SQLPLUS Reports and Commands Building a Simple Report 110

remark 114 set headsep 114 ttitle and btitle 114 column 115 break on 118 compute sum 119 set linesize 120 set pagesize 120 set newpage 121 spool 122 /* */ 123 Some Clarification on Column Headings

Other Features 124 Command Line Editor 125 set pause 129 save 130 editing 130 host 131 Adding SQLPLUS Commands 131 start 133

Checking the SQLPLUS Environment 133 Building Blocks 136

6 Getting Text Information and Changing It Datatypes 140 What Is a String? 141 Notation 143 Concatenation (II) 144 How to Cut and Paste Strings 146

RPADandLPAD 146 LTRIM and RTRIM 147 Combining Two Functions 149 Adding One More Function 152 LOWER, UPPER, and INITCAP 153 LENGTH 155 SUBSTR 155 INSTR 159

order by and where with String Functions 166 SOUNDEX 167 National Language Support 169

Review 170

7 Playing the Numbers 173 The Three Classes of Number Functions 1 74 Notation 176 Single-Value Functions 177

Addition, Subtraction, Multiplication, and Division (+, -, *, and/) 178

NULL 178 NVL—NULL-Value Substitution 1 79 ABS—Absolute Value 181 CEIL 181 FLOOR 181 MOD 182 POWER 182 SQRT—Square Root 183 EXP, LN, and LOG 183 ROUND and TRUNC 184 SIGN 186 SIN, SINH, COS, COSH, TAN, and TANH 186

Group-Value Functions 186 NULLs in Group-Value Functions 187 Examples of Single- and Group-Value Functions 189 AVG, COUNT, MAX, MIN, and SUM 190 Combining Group-Value and Single-Value Functions 190 STDDEV and VARIANCE 193 DISTINCT in Group Functions 193

List Functions 195 Finding Rows with MAX or MIN 196 Precedence and Parentheses 198 Review 200

8 Dates: Then, Now, and the Difference 203 Date Arithmetic 204

SysDate 205 The Difference Between Two Dates 206 Adding Months 209 Subtracting Months 209 GREATEST and LEAST 210 NEXT_DAY 211 LAST DAY 214

MONTHS_BETWEEN Two Dates 214 Combining Date Functions 215

ROUND and TRUNC in Date Calculations 216 TO_DATE and TO_CHAR Formatting 21 7

The Most Common TO_CHAR Error 225 NEVVJIME—Switching Time Zones 226 TCLDATE Calculations 227

Dates in where Clauses 230 Dealing with the Year 2000 232

9 Conversion and Transformation Functions 235 Elementary Conversion Functions 239

Automatic Conversion of Datatypes 242 A Warning About Automatic Conversion 246

Specialized Conversion Functions 246 Transformation Functions 247

TRANSLATE 247 DECODE 248

Review 250

10 Grouping Things Together 253 The Use of group by and having 256

Adding an order by 259 Order of Execution 261

Views of Groups 262 Renaming Columns with Aliases 264

The Power of Views of Groups 266 Logic in the having Clause 268 order by with Columns and Group Functions 270 Join Columns 271

where, having, group by, and order by 272

I I When One Query Depends upon Another 275 Advanced Subqueries 276

Correlated Subqueries 279 Coordinating Logical Tests 283 EXISTS and Its Correlated Subquery 285

Outer Joins 287 Replacing NOT IN with an Outer Join 288 Replacing NOT IN with NOT EXISTS 290

UNION, INTERSECT, and MINUS 292 IN Subqueries 298 UNION 298 INTERSECT 301

MINUS 302 Restrictions on UNION, INTERSECT, and MINUS 303

12 Some Complex Possibilities 307 Creating a Complex View 308

A View of a Group 310 A View of the Total 310 The Combined View 311

Family Trees and connect by 313 Excluding Individuals and Branches 318 Traveling Toward the Roots 321 The Basic Rules 323

Using Views within the from Clause 324

13 Building a Report in SQLPLUS 327 Advanced Formatting 328

Formatting Problems with Numbers 329 break on 330 Order of Columns in break on 330 break on Row 334 Adding Views 334 Columns Used with ttitle and btitle 334 More on break and compute 339

set termout off and set termout on 345 Variables in SQLPLUS 345

Other Places to Use Variables 349 Numeric Formatting 349 Using mask.sql 351 Using Buffers to Save SQLPLUS Commands 353

spooling Current Definitions 356 show all and spooling 356 Folding onto New Lines 357

fold_after and fold_before 358 Additional Reporting Controls 359

14 Changing Data: insert, update, and delete 361 insert 362

inserting a Time 363 insert with select 364

rollback, commit, and autocommit 366 Implicit commit 367 Auto rollback 367

delete 367

update 371 update with Embedded select 372 update with NULL 374

15 Advanced Use of Functions and Variables 377 Functions in order by 378 Bar Charts and Graphs 378 Using TRANSLATE 383

Eliminating Characters 383 Cleaning Up Dollar Signs and Commas 384

Complex Cut and Paste 386 Counting String Occurrences Within Larger Strings 392 Variables and Spooled Substitution 393

Some Additional Facts About Variables 398 Related set Commands 399

16 DECODE—Amazing Power in a Single Word 401 if, then, else 402 Example: Aging Invoices 403

Collecting Clients Together 406 Flipping a Table onto Its Side 409 Using MOD in DECODE 412 order by and RowNum 415 Columns and Computations in then and else 416 Greater Than, Less Than, and Equal To in DECODE 418

17 Creating, Dropping, and Altering Tables and Views 423 Creating a Table 424

Character Width and NUMBER Precision 425 Rounding During Insertion 428 Constraints in create table 429 Naming Constraints 432

Dropping Tables 433 Altering Tables 434

The Rules for Adding or Modifying a Column 436 Creating a View 437

Stability of a View 437 order by in Views 439 Creating a Read-Only View 440

Creating a Table from a Table 441 Creating an Index-Only Table 443 Using Partitioned Tables 444

Creating a Partitioned Table 445

Indexing Partitions 446 Managing Partitioned Tables 447 Querying Directly from Partitions 448

By What Authority? Users, Roles, and Privileges 452

Creating a User 452 Password Management 453 Three Standard Roles 455 Format for the grant Command 456 Revoking Privileges 456

What Users Can Grant 457 Moving to Another User with connect 459 create synonym 463 Using Ungranted Privileges 463 Passing on Privileges 463 Creating a Role 465 Granting Privileges to a Role 466 Granting a Role to Another Role 466 Adding a Password to a Role 468 Removing a Password from a Role 469 Enabling and Disabling Roles 469 Revoking Privileges from a Role 470 Dropping a Role 470 Granting update to Specific Columns 471 Revoking Privileges 471 Security by User 471 Granting Access to the Public 473

Granting Limited Resources 474

Changing the ORACLE Surroundings Indexes 478

Creating an Index 480 Enforcing Uniqueness 482 Creating a Bitmap Index 483 When to Create an Index 484 When Indexes Are Ignored 485 Variety in Indexed Columns 485 How Many Indexes to Use on a Table 486 Placing an Index in the Database 487 Rebuilding an Index 488

Tablespace and the Structure of the Database 489 create tablespace 493

Clusters 495 How the Tables Are Stored 496

Sequences 498

20 SQLPLUS 501 Generating Code for a Query 502 Loading Variables 509

Changing Variable Values 511 Using Variables with ttitle 511 Character Strings and Dates 511

Creating and Nesting Start Files and Commands 512 Using Host Processes 516

Review 516

21 Accessing Remote Data 519 Database Links 520

How a Database Link Works 520 Using a Database Link for Remote Queries 521 Using a Database Link for Synonyms and Views 523 Using a Database Link for Remote Updates 524 Syntax for Database Links 526

Using Synonyms for Location Transparency 529 Using the User Pseudo-column in Views 530 Dynamic Links: Using the SQLPLUS copy Command 533 Connecting to a Remote Database 535 Management Tools: Oracle*Names 536

22 An Introduction to PL/SQL 54I PL/SQL Overview 542 Declarations Section 543 Executable Commands Section 546

Conditional Logic 548 Loops 550 goto Statements 560

Exception Handling Section 561

23 Triggers 567 Required System Privileges 568 Required Table Privileges 568 Types of Triggers 569

Row-Level Triggers 569 Statement-Level Triggers 569 BEFORE and AFTER Triggers 570 INSTEAD OF Triggers 570 Valid Trigger Types 571

Trigger Syntax 571 Combining Trigger Types 574 Setting Inserted Values 576 Maintaining Duplicated Data 577 Customizing Error Conditions 578 Naming Triggers 580

Enabling and Disabling Triggers 580 Replacing Triggers 582 Dropping Triggers 582

24 Procedures 585 Required System Privileges 586

Executing Procedures 587 Required Table Privileges 589 Procedures vs. Functions 589 Procedures vs. Packages 589 create procedure Syntax 590 create function Syntax 592

Referencing Remote Tables in Procedures 594 Debugging Procedures 595 Creating Your Own Functions 596 Customizing Error Conditions 598 Naming Procedures 600

create package Syntax 600 Initializing Packages 603

Viewing Source Code for Existing Procedural Objects 605 Compiling Procedures, Functions, and Packages 606 Replacing Procedures, Functions, and Packages 607 Dropping Procedures, Functions, and Packages 607

25 Implementing Types, Object Views, and Methods 61 I Revisiting Abstract Datatypes 612

Security for Abstract Datatypes 613 Indexing Abstract Datatype Attributes 616

Implementing Object Views 618 Manipulating Data via Object Views 622 Using INSTEAD OF Triggers 623

Methods 627 Syntax for Creating Methods 628 Managing Methods 630

26 Collectors (Nested Tables and Varying Arrays) 633 Varying Arrays 634

Creating a Varying Array 634

Describing the Varying Array 636 Inserting Records into the Varying Array 638 Selecting Data from Varying Arrays 639

Nested Tables 642 Inserting Records into a Nested Table 644 Querying Nested Tables 647

Management Issues for Nested Tables and Varying Arrays 652 Managing Large Collections 652 Variability in Collectors 653 Location of the Data 654

27 Using Large Objects (LOBs) in ORACLE8 657 Available Datatypes 658 Specifying Storage for LOB Data 660 Manipulating and Selecting LOB Values 663

Initializing values 663 insert with Subqueries 665 Updating LOB Values 666 Using DBMSJ-OB to Manipulate LOB Values 667 Deleting LOBS 688

28 Snapshots 691 Snapshots Functionality 692 Required System Privileges 693 Required Table Privileges 693 Simple vs. Complex Snapshots 694 Read-Only vs. Updatable Snapshots 695 create snapshot Syntax 696

ROVVID vs. Primary Key-based Snapshots 700 Local and Remote Objects Created 701

Refreshing Snapshots 704 Automatic Refreshes 704 Manual Refreshes 705 Using Snapshot Refresh Groups 707

Snapshots vs. Triggers 711 create snapshot log Syntax 712

Required System Privileges 713 Local and Remote Objects Created 713

Viewing Information about Existing Snapshots 714 Altering Snapshots and Snapshot Logs 716 Dropping Snapshots and Snapshot Logs 718

29 Using ConText for Text Searches 721 Adding Text to the Database 722

Querying Text from the Database 724 ConText Queries 725 Available ConText Query Expressions 726 Searching for an Exact Match of a Word 726 Searching for an Exact Match of Multiple Words 728 Searching for an Exact Match of a Phrase 731 Searches for Words that Are Near Each Other 732 Using Wildcards During Searches 732 Searching for Words that Share the Same Stem 733 Searching for Fuzzy Matches 734 Searches for Words that Sound like Other Words 735 Combining Search Methods 737

Configuring the ConText Option 740

30 Configuring the ConText Option 743 Setting Up the Database for Text Searches 744

init.ora File Modifications 748 Roles Required 749

Setting Up the Table for ConText Queries 749 Displaying and Altering Preferences 751 Creating Text Indexes 754

Optimizing the Text Indexes 759 Loading Data 759

Two-Step Queries 759 Using Linguistic Services 762

31 Advanced Object-Oriented Concepts in ORACLE8 767 Row Objects vs. Column Objects 768 Object Tables and OlDs 769

Inserting Rows into Object Tables 770 Selecting Values from Object Tables 771 Updates and Deletes from Object Tables 772 The REF Operator 773 Using the DEREF Operator 773 The VALUE Operator 777 Invalid References 778

Object Views with REFs 778 A Quick Review of Object Views 779 Object Views Involving References 780

Object PL/SQL 784 Objects in the Database 787

PART III The Hitchhiker's Guide to the ORACLE8 Data Dictionary The Hitchhiker's Guide to the ORACLE8 Data Dictionary . . . . A Note About Nomenclature 793 The Road Maps: DICTIONARY (DICT) and DICT_COLUMNS

793 Things You Select from: Tables (and Columns), Views, Synonyms,

and Sequences 795 Catalog: USER_CATALOG (CAT) 795 Objects: USER_OBJECTS (OBJ) 796 Tables: USER_TABLES (TABS) 797 Columns: USER_TAB_COLUMNS (COLS) 799 Views: USER_VIEWS 802 Synonyms: USER_SYNONYMS (SYN) 805 Sequences: USER_SEQUENCES (SEQ) 806

Constraints and Comments 807 Constraints: USER_CONSTRAINTS 807 Constraint Columns: USER_CONS_COLUMNS 809 Constraint Exceptions: EXCEPTIONS 811 Table Comments: USER_TAB_COMMENTS 812 Column Comments: USER_COL_COMMENTS 813

Indexes and Clusters 814 Indexes: USERJNDEXES (IND) 814 Indexed Columns: USER_IND_COLUMNS 816 Clusters: USER_CLUSTERS (CLU) 818 Cluster Columns: USER_CLU_COLUMNS 819

ORACLE8-Specific Objects 819 Abstract Datatypes 820 LOBs 823

Database Links and Snapshots 824 Database Links: USER_DB_LINKS 824 Snapshots: USER_SNAPSHOTS 825 Snapshot Logs: USER_SNAPSHOT_LOGS 827

Triggers, Procedures, Functions, and Packages 828 Triggers: USER_TRIGGERS 829 Procedures, Functions, and Packages: USER_SOURCE

830 Space Allocation and Usage, Including Partitions 832

Tablespaces: USER_TABLESPACES 832

Space Quotas: USER_TS_QUOTAS. 833 Segments and Extents: USER_SEGMENTS and

USER_EXTENTS 834 Partitions 836 Free Space: USER_FREE_SPACE 839

Users and Privileges 839 Users: USERJJSERS 840 Resource Limits: USER_RESOURCE_LIMITS 840 Table Privileges: USER_TAB_PRIVS 841 System Privileges: USER_SYS_PRIVS 842

Roles 842 Auditing 844 Monitoring: The V$ Dynamic Performance Tables 846 Miscellaneous 847

CHAINED_ROWS 848 PLAN_TABLE 848 Interdependencies: USER_DEPENDENCIES and IDEPTREE

849 DBA-only Views 850 Trusted ORACLE 850 SQL*LOADER Direct Load Views 850 National Language Support (NLS) Views 850 Libraries 851

PART IV Designing for Productivity

33 Good Design Has a Human Touch 855 Understanding the Application Tasks 856

Outline of Tasks 859 Understanding the Data 862

The Atomic Data Models 864 The Atomic Business Model 864

The Business Model 864 Data Entry 866 Query and Reporting 866 Review 867

34 Performance and Design 871 Denormalization and Data Integrity 873

Meaningful Keys 874 Real Denormalization 877 Rows, Columns, and Volume 879

Memory Binding 880 The Kitchen Junk Drawer 881 Should You Do Any of This? 881

The Computation Table 882 Review 882

35 The Ten Commandments of Humane Design 885 Toward Object Name Normalization 886

Level-Name Integrity 886 Foreign Keys 890 Singularity 891 Brevity 893 Object Name Thesaurus 894

Intelligent Keys and Column Values 895 The Commandments 896

36 The Hitchhiker's Guide to the ORACLE Optimizer 899 Which Optimizer? 900 Operations That Access Tables 901

TABLE ACCESS FULL 901 TABLE ACCESS BY ROVVID 901 Related Hints 902

Operations That Use Indexes 903 INDEX UNIQUE SCAN 904 INDEX RANGE SCAN 904 When Indexes Are Used 905 Combining Output from Multiple Index Scans 910 Related Hints 913 Additional Tuning Issues for Indexes 914

Operations That Manipulate Data Sets 915 Ordering Rows 916 Grouping Rows 917 Operations Using RowNum 919 UNION, MINUS, and INTERSECT 920 Selecting Rows for update 926 Selecting from Views 927 Selecting from Subqueries 930 Related Hints and Parameters 931 Additional Tuning Issues 932

Operations That Perform Joins 932 How ORACLE Handles Joins of More than Two Tables

933 MERGE JOIN 933 NESTED LOOPS 936

HASH JOIN 939 Processing Outer Joins 940 Related Hints 941 Additional Tuning Issues 946

Displaying the Execution Path 948 Using set autotrace on 948 Using explain plan 953

Miscellaneous Operations 955 Filtering Rows 955 Queries That Use connect by Clauses 956 Queries That Use Sequences 957 Queries That Use Database Links 958 Queries That Use Clusters 959 Related Hints 959 Additional Tuning Issues 960

Review 962

PARTV

Alphabetical Reference

37 Alphabetical Reference 965 What This Alphabetical Reference Includes 966 What This Alphabetical Reference Does Not Include 966 General Format of Entries 966 The Order of the Listings 968

PART VI

Appendix

A Tables Used in this Book 1223 Using the Tables in this Book 1224 The activity.sql Start File 1224 The math.sql Start File 1225 The ADDRESSJTY Type 1227 The ANIMAL_TY Type 1227 The PERSON_TY Type 1228 The TOOLS_VA Type 1228 The ADDRESS Table 1228 The AREAS Table 1229 The ASOF Table 1229 The BIRTHDAY Table 1229 The BORROWER Table 1230 The BREEDER Table 1230

The BREEDING Table 1230 The CD Table 1231 The COMFORT Table 1231 The COMMA Table 1232 The CUSTOMER Table 1232 The EMPTY Table 1233 The HOCKEY Table 1233 The HOLIDAY Table 1233 The INVOICE Table 1234 The LEDGER Table 1235 The LOCATION Table 1247 The LODGING Table 1248 The LONGTIME Table 1248 The MAGAZINE Table 1249 The MATH Table 1249 The NAME Table 1249 The NEWSPAPER Table 1250 The NUMBERTEST Table 1250 The PAY Table 1250 The PAYDAY Table 1251 The PROPOSAL Table 1251 The PROSPECT Table 1251 The RADIUS_VALS Table 1252 The ROSE Table 1252 The SHIPPING Table 1252 The SKILL Table 1252 The STOCK Table 1252 The TROUBLE Table 1254 The TWONAME Table 1254 The WEATHER Table 1255 The WORKER Table 1255 The WORKERSKILL Table 1255

Index 1257