Oracle SQL Developer
Oracle SQL Developer
Oracle SQL Developer
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
<strong>Oracle</strong> <strong>SQL</strong> <strong>Developer</strong>Online HelpRelease 1.0 Early AdopterFebruary 2006This is a single PDF document containing the online helptopics for <strong>Oracle</strong> <strong>SQL</strong> <strong>Developer</strong>. It is provided merely as aconvenience; you are still encouraged to use the help withinthe <strong>SQL</strong> <strong>Developer</strong> user interface to obtain immediate andcontext-relevant information.
<strong>SQL</strong> <strong>Developer</strong> Online Help, Release 1.0 Early AdopterCopyright © 2005, 2006, <strong>Oracle</strong>. All rights reserved.Primary Author:Chuck MurrayThe Programs (which include both the software and documentation) contain proprietary information; theyare provided under a license agreement containing restrictions on use and disclosure and are also protectedby copyright, patent, and other intellectual and industrial property laws. Reverse engineering, disassembly,or decompilation of the Programs, except to the extent required to obtain interoperability with otherindependently created software or as specified by law, is prohibited.The information contained in this document is subject to change without notice. If you find any problems inthe documentation, please report them to us in writing. This document is not warranted to be error-free.Except as may be expressly permitted in your license agreement for these Programs, no part of thesePrograms may be reproduced or transmitted in any form or by any means, electronic or mechanical, for anypurpose.If the Programs are delivered to the United States Government or anyone licensing or using the Programs onbehalf of the United States Government, the following notice is applicable:U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical datadelivered to U.S. Government customers are "commercial computer software" or "commercial technical data"pursuant to the applicable Federal Acquisition Regulation and agency-specific supplemental regulations. Assuch, use, duplication, disclosure, modification, and adaptation of the Programs, including documentationand technical data, shall be subject to the licensing restrictions set forth in the applicable <strong>Oracle</strong> licenseagreement, and, to the extent applicable, the additional rights set forth in FAR 52.227-19, CommercialComputer Software—Restricted Rights (June 1987). <strong>Oracle</strong> Corporation, 500 <strong>Oracle</strong> Parkway, Redwood City,CA 94065The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherentlydangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup,redundancy and other measures to ensure the safe use of such applications if the Programs are used for suchpurposes, and we disclaim liability for any damages caused by such use of the Programs.<strong>Oracle</strong>, JD Edwards, PeopleSoft, and Retek are registered trademarks of <strong>Oracle</strong> Corporation and/or itsaffiliates. Other names may be trademarks of their respective owners.The Programs may provide links to Web sites and access to content, products, and services from thirdparties. <strong>Oracle</strong> is not responsible for the availability of, or any content provided on, third-party Web sites.You bear all risks associated with the use of such content. If you choose to purchase any products or servicesfrom a third party, the relationship is directly between you and the third party. <strong>Oracle</strong> is not responsible for:(a) the quality of third-party products or services; or (b) fulfilling any of the terms of the agreement with thethird party, including delivery of products or services and warranty obligations related to purchasedproducts or services. <strong>Oracle</strong> is not responsible for any loss or damage of any sort that you may incur fromdealing with any third party.
Contents1 <strong>SQL</strong> <strong>Developer</strong> Concepts and Usage1.1 <strong>SQL</strong> <strong>Developer</strong> User Interface................................................................................................... 1-11.1.1 Menus for <strong>SQL</strong> <strong>Developer</strong>.................................................................................................. 1-41.2 Database Objects ......................................................................................................................... 1-61.2.1 Database Links ..................................................................................................................... 1-61.2.2 Directories............................................................................................................................. 1-61.2.3 Functions............................................................................................................................... 1-71.2.4 Indexes................................................................................................................................... 1-71.2.5 Materialized Views.............................................................................................................. 1-71.2.6 Materialized View Logs...................................................................................................... 1-81.2.7 Packages ................................................................................................................................ 1-81.2.8 Procedures ............................................................................................................................ 1-81.2.9 Recycle Bin............................................................................................................................ 1-91.2.10 Sequences.............................................................................................................................. 1-91.2.11 Synonyms (Public and Private) ......................................................................................... 1-91.2.12 Tables..................................................................................................................................... 1-91.2.13 Triggers .............................................................................................................................. 1-111.2.14 Types................................................................................................................................... 1-111.2.15 Users (Other Users) .......................................................................................................... 1-111.2.16 Views .................................................................................................................................. 1-111.3 Database Connections ............................................................................................................. 1-111.4 Entering and Modifying Data ................................................................................................ 1-131.5 Running and Debugging Functions and Procedures ......................................................... 1-141.6 Using the <strong>SQL</strong> Worksheet....................................................................................................... 1-161.6.1 <strong>SQL</strong>*Plus Statements Supported and Not Supported in <strong>SQL</strong> Worksheet................ 1-181.6.2 Script Runner..................................................................................................................... 1-191.6.3 Execution Plan................................................................................................................... 1-191.6.4 DBMS Output Pane .......................................................................................................... 1-201.6.5 OWA Output Pane ........................................................................................................... 1-201.7 Using <strong>SQL</strong>*Plus ........................................................................................................................ 1-211.8 Using Snippets to Insert Code Fragments............................................................................ 1-211.9 Reports....................................................................................................................................... 1-221.9.1 About Your Database reports ......................................................................................... 1-231.9.2 Database Administration reports ................................................................................... 1-231.9.3 Table reports...................................................................................................................... 1-241.9.4 PL/<strong>SQL</strong> reports................................................................................................................. 1-25iii
1.9.5 Security reports ................................................................................................................. 1-251.9.6 XML reports....................................................................................................................... 1-261.9.7 Jobs reports ........................................................................................................................ 1-261.9.8 Streams reports ................................................................................................................. 1-261.9.9 All Objects reports ............................................................................................................ 1-271.9.10 Data Dictionary reports ................................................................................................... 1-271.9.11 User Defined reports ........................................................................................................ 1-271.10 <strong>SQL</strong> <strong>Developer</strong> Preferences.................................................................................................... 1-281.10.1 Environment...................................................................................................................... 1-281.10.2 Accelerators ....................................................................................................................... 1-291.10.3 Code Editor........................................................................................................................ 1-301.10.4 Database Connections...................................................................................................... 1-311.10.5 Debugger............................................................................................................................ 1-321.10.6 Documentation.................................................................................................................. 1-321.10.7 Extensions .......................................................................................................................... 1-331.10.8 File Types ........................................................................................................................... 1-331.10.9 Global Ignore List ............................................................................................................. 1-331.10.10 PL/<strong>SQL</strong> Compiler............................................................................................................. 1-341.10.11 Proxy................................................................................................................................... 1-341.10.12 <strong>SQL</strong> Formatter................................................................................................................... 1-341.11 <strong>SQL</strong> <strong>Developer</strong> User Information: Location ........................................................................ 1-341.12 Using the Help.......................................................................................................................... 1-351.13 Supplementary <strong>Oracle</strong> Database Information ..................................................................... 1-352 Tutorial: Creating Objects for a Small Database2.1 Creating a Table (Books)............................................................................................................ 2-12.2 Creating a Table (Patrons) ......................................................................................................... 2-32.3 Creating a Table (Transactions) ................................................................................................ 2-42.4 Creating a Sequence.................................................................................................................... 2-62.5 Creating a View........................................................................................................................... 2-72.6 Creating a PL/<strong>SQL</strong> Procedure.................................................................................................. 2-82.7 Debugging a PL/<strong>SQL</strong> Procedure ............................................................................................. 2-92.8 Using the <strong>SQL</strong> Worksheet for Queries.................................................................................. 2-102.9 Script for Creating and Using the Library Tutorial Objects .............................................. 2-113 Dialog Boxes for Creating/Editing Objects3.1 Add Extension ............................................................................................................................. 3-13.2 Apply Filter.................................................................................................................................. 3-13.3 Check for Updates ...................................................................................................................... 3-23.4 Choose Directory......................................................................................................................... 3-23.5 Create/Edit New Object ............................................................................................................ 3-23.6 Create/Edit/Select Database Connection............................................................................... 3-23.7 Select Connection........................................................................................................................ 3-33.8 Select Library ............................................................................................................................... 3-43.9 Create Library.............................................................................................................................. 3-43.10 Export/Import Connection Descriptors.................................................................................. 3-43.11 Create/Edit Database Link........................................................................................................ 3-4iv
3.12 Create/Edit Index ....................................................................................................................... 3-53.13 Create PL/<strong>SQL</strong> Function, Procedure, or Package.................................................................. 3-63.14 Create/Edit Sequence................................................................................................................. 3-63.15 Create/Edit Synonym ................................................................................................................ 3-73.16 Create Table (quick creation) .................................................................................................... 3-83.17 Create/Edit Table (with advanced options) ........................................................................... 3-93.18 Create Trigger........................................................................................................................... 3-173.19 Create Type (User-Defined) ................................................................................................... 3-183.20 Create/Edit User Defined Report.......................................................................................... 3-183.21 Create/Edit User Defined Report Folder ............................................................................. 3-193.22 Create/Edit View..................................................................................................................... 3-193.23 Configure File Type Associations.......................................................................................... 3-223.24 Edit Value (Table Column Data) ........................................................................................... 3-223.25 Export (Selected Objects or Object Types)............................................................................ 3-223.26 Export Table Data .................................................................................................................... 3-233.27 Externally Modified Files........................................................................................................ 3-233.28 Filter Object Types ................................................................................................................... 3-233.29 Find/Replace Text ................................................................................................................... 3-243.30 Go to Line Number.................................................................................................................. 3-243.31 Go to Line Number: Error....................................................................................................... 3-243.32 Load Preset Key Mappings..................................................................................................... 3-243.33 Open File ................................................................................................................................... 3-243.34 Recent Files ............................................................................................................................... 3-243.35 Run/Debug PL/<strong>SQL</strong>............................................................................................................... 3-253.36 Create/Edit Breakpoint........................................................................................................... 3-253.37 Save/Save As............................................................................................................................ 3-263.38 Save Files ................................................................................................................................... 3-263.39 Unable to Save Files................................................................................................................. 3-263.40 Save Style Settings ................................................................................................................... 3-263.41 <strong>SQL</strong> History List....................................................................................................................... 3-273.42 <strong>SQL</strong>*Plus Location ................................................................................................................... 3-274 Database Objects: Usage Information4.1 Overview of Managing Objects ................................................................................................ 4-14.2 Managing Tables......................................................................................................................... 4-24.2.1 Column Data Types............................................................................................................. 4-24.2.2 Column Default Values....................................................................................................... 4-34.2.3 Ensuring Data Integrity With Constraints ....................................................................... 4-34.2.4 Column Constraints ............................................................................................................ 4-44.2.5 Table-Level Constraints ...................................................................................................... 4-44.2.5.1 Primary Key................................................................................................................... 4-54.2.5.2 Unique Key.................................................................................................................... 4-54.2.5.3 Check Constraint .......................................................................................................... 4-54.2.5.4 Foreign Key ................................................................................................................... 4-64.3 Managing Indexes....................................................................................................................... 4-64.3.1 Creating Indexes for Use with Constraints...................................................................... 4-74.3.2 Index Types .......................................................................................................................... 4-7v
4.3.2.1 Normal ........................................................................................................................... 4-74.3.2.2 Ascending and Descending ........................................................................................ 4-74.3.2.3 Column and Function-based....................................................................................... 4-74.3.2.4 Single Column and Concatenated ............................................................................. 4-74.3.3 Guidelines for Creating Indexes........................................................................................ 4-84.3.3.1 Index the Correct Tables and Columns..................................................................... 4-84.3.3.2 Limit the Number of Indexes for Each Table ........................................................... 4-94.3.3.3 Choose the Order of Columns in Composite Indexes............................................. 4-94.3.3.4 Drop Indexes That Are No Longer Required ....................................................... 4-104.4 Managing Views ...................................................................................................................... 4-104.5 Managing Sequences ............................................................................................................... 4-104.6 Managing Synonyms............................................................................................................... 4-115 Data Types: Usage Information5.1 Overview of Data Types ............................................................................................................ 5-15.2 Storing Character Data............................................................................................................... 5-15.2.1 What are the Character Data Types? ................................................................................ 5-15.2.2 Choosing Between the Character Data Types ................................................................. 5-25.3 Storing Numeric Data ................................................................................................................ 5-25.3.1 What Are the Numeric Data Types?................................................................................. 5-25.3.2 Using NUMBER Data Types.............................................................................................. 5-35.3.3 Using Floating-Point Number Formats............................................................................ 5-45.3.3.1 BINARY_FLOAT .......................................................................................................... 5-55.3.3.2 BINARY_DOUBLE....................................................................................................... 5-55.4 Storing Datetime Data................................................................................................................ 5-55.4.1 Using DATE and TIMESTAMP Data Types.................................................................... 5-55.4.1.1 Using the DATE Data Type ........................................................................................ 5-55.4.1.2 Using the TIMESTAMP Data Type............................................................................ 5-65.4.1.3 Using the TIMESTAMP WITH TIME ZONE Data Type........................................ 5-65.4.1.4 Using the TIMESTAMP WITH LOCAL TIME ZONE Data Type......................... 5-65.4.1.5 Representing the Difference Between Datetime Values ......................................... 5-65.4.2 Manipulating the DATE and TIME Formats ................................................................... 5-66 <strong>SQL</strong>: Usage Information6.1 Overview of <strong>SQL</strong>......................................................................................................................... 6-16.1.1 Features of <strong>SQL</strong> .................................................................................................................... 6-16.1.2 Types of <strong>SQL</strong> Statements.................................................................................................... 6-26.2 Retrieving Data With Queries................................................................................................... 6-26.2.1 Displaying Data Using the SELECT Statement............................................................... 6-26.2.2 Using Character Literals in <strong>SQL</strong> Statements.................................................................... 6-36.2.2.1 Quoting Character Literals.......................................................................................... 6-36.2.3 Using a Column Alias to Change Headings When Selecting Data .............................. 6-46.2.4 Restricting Data Using the WHERE Clause..................................................................... 6-46.2.5 Sorting Data Using the ORDER BY Clause...................................................................... 6-56.2.6 Displaying Data From Multiple Tables ............................................................................ 6-66.3 Manipulating Data With <strong>SQL</strong> Statements............................................................................... 6-76.3.1 Adding Data With the INSERT Statement....................................................................... 6-7vi
6.3.2 Updating Data With the UPDATE Statement ................................................................. 6-86.3.3 Deleting Data With the DELETE Statement .................................................................... 6-86.4 Transaction Control Statements................................................................................................ 6-86.4.1 Committing Transaction Changes..................................................................................... 6-96.4.2 Rolling Back a Transaction ................................................................................................. 6-96.5 Using Pseudocolumns, Sequences, and <strong>SQL</strong> Functions..................................................... 6-106.5.1 Using Pseudocolumns With <strong>SQL</strong> ................................................................................... 6-106.5.2 Using Sequences ............................................................................................................... 6-116.5.3 Using Character Functions .............................................................................................. 6-116.5.4 Using Arithmetic Operators............................................................................................ 6-126.5.5 Using Numeric Functions................................................................................................ 6-126.5.6 Using Date Functions ....................................................................................................... 6-136.5.7 Using Aggregate Functions............................................................................................. 6-146.6 Using <strong>SQL</strong> Data Definition Language Statements.............................................................. 6-156.6.1 Creating a Table With <strong>SQL</strong>.............................................................................................. 6-156.6.2 Creating and Modifying an Index With <strong>SQL</strong> ............................................................... 6-166.6.3 Creating and Modifying a Constraint With <strong>SQL</strong> ......................................................... 6-166.6.4 Altering a Table With <strong>SQL</strong> .............................................................................................. 6-176.6.5 Dropping a Table With <strong>SQL</strong>............................................................................................ 6-176.6.6 Creating and Dropping a Sequence ............................................................................... 6-176.6.7 Creating and Dropping a Synonym............................................................................... 6-187 PL/<strong>SQL</strong>: Usage Information7.1 Overview of PL/<strong>SQL</strong> ................................................................................................................. 7-17.2 Entering and Executing PL/<strong>SQL</strong> Code ................................................................................... 7-27.3 Utilizing the Main Features of PL/<strong>SQL</strong> .................................................................................. 7-27.3.1 Using PL/<strong>SQL</strong> Block Structure.......................................................................................... 7-37.3.2 Using Comments ................................................................................................................. 7-47.3.3 Declaring Variables and Constants................................................................................... 7-47.3.4 Using Identifiers in PL/<strong>SQL</strong> .............................................................................................. 7-57.3.5 Assigning Values to a Variable With the Assignment Operator .................................. 7-67.3.6 Using Literals ....................................................................................................................... 7-77.3.7 Declaring and Assigning Variables With DEFAULT or NOT NULL .......................... 7-87.3.8 Assigning Values to a Variable With SELECT INTO ..................................................... 7-97.3.9 Inputting and Outputting Data with PL/<strong>SQL</strong> ................................................................ 7-97.3.10 Using %ROWTYPE and %TYPE Attributes to Declare Data Types ......................... 7-107.3.10.1 Using the %ROWTYPE Attribute to Declare Variables....................................... 7-107.3.10.2 Using the %TYPE Attribute to Declare Variables................................................. 7-117.3.11 Using PL/<strong>SQL</strong> Control Structures ................................................................................. 7-117.3.11.1 Conditional Control With IF-THEN ....................................................................... 7-117.3.11.2 Conditional Control With the CASE Statement.................................................... 7-127.3.11.3 Iterative Control With LOOPs ................................................................................. 7-137.3.11.4 Sequential Control With GOTO .............................................................................. 7-157.3.12 Using Local PL/<strong>SQL</strong> Subprograms in PL/<strong>SQL</strong> Blocks .............................................. 7-157.3.13 Working With PL/<strong>SQL</strong> Data Structures ....................................................................... 7-177.3.13.1 Using Cursors............................................................................................................. 7-177.3.13.2 Using Collections....................................................................................................... 7-17vii
7.3.13.3 Using Records ............................................................................................................ 7-187.3.14 Processing Queries with PL/<strong>SQL</strong> .................................................................................. 7-197.3.15 Using Dynamic <strong>SQL</strong> in PL/<strong>SQL</strong> .................................................................................... 7-197.3.16 Using Bind Variables........................................................................................................ 7-217.4 Handling PL/<strong>SQL</strong> Errors ....................................................................................................... 7-217.4.1 Summary of Predefined PL/<strong>SQL</strong> Exceptions............................................................... 7-217.4.2 Using the Exception Handler.......................................................................................... 7-237.4.3 Declaring PL/<strong>SQL</strong> Exceptions........................................................................................ 7-237.4.4 Scope Rules for PL/<strong>SQL</strong> Exceptions.............................................................................. 7-237.4.5 Continuing After an Exception is Raised ...................................................................... 7-248 Subprograms and Packages: Usage Information8.1 Overview of Packages and Subprograms ............................................................................... 8-18.1.1 Stored Subprograms............................................................................................................ 8-28.1.2 Packages ................................................................................................................................ 8-28.2 Managing Subprograms ............................................................................................................ 8-38.3 Managing Packages .................................................................................................................... 8-38.3.1 Calling Subprograms in Packages..................................................................................... 8-48.3.2 Accessing Variables in Packages ....................................................................................... 8-48.4 <strong>Oracle</strong> Product-Specific Packages............................................................................................. 8-59 Triggers: Usage Information9.1 Overview of Triggers.................................................................................................................. 9-19.1.1 Types of Triggers ................................................................................................................ 9-29.1.2 Naming Triggers ................................................................................................................. 9-29.1.3 When Is the Trigger Fired? ................................................................................................ 9-29.1.4 Controlling When a Trigger Is Fired ................................................................................ 9-29.1.4.1 Firing Triggers With the BEORE and AFTER Options ........................................... 9-29.1.4.2 Firing Triggers With the FOR EACH ROW Option ............................................... 9-39.1.4.3 Firing Triggers Based on Conditions (WHEN Clause) .......................................... 9-39.1.5 Accessing Column Values in Row Triggers .................................................................... 9-39.1.6 Detecting the DML Operation That Fired a Trigger....................................................... 9-49.1.7 Enabled and Disabled Trigger Modes .............................................................................. 9-49.1.8 Error Conditions and Exceptions in the Trigger Body .................................................. 9-49.2 Designing Triggers ..................................................................................................................... 9-59.2.1 Guidelines For Triggers ...................................................................................................... 9-59.2.2 Restrictions on Creating Triggers ..................................................................................... 9-59.2.3 Privileges Needed to Work with Triggers ...................................................................... 9-610 <strong>SQL</strong>*Plus: Usage Information10.1 Overview of <strong>SQL</strong>*Plus ............................................................................................................ 10-110.2 Using <strong>SQL</strong>*Plus ........................................................................................................................ 10-110.2.1 Starting and Exiting <strong>SQL</strong>*Plus........................................................................................ 10-210.2.2 Displaying Help With <strong>SQL</strong>*Plus .................................................................................... 10-210.2.3 Entering and Executing <strong>SQL</strong> Statements and Commands ......................................... 10-210.2.4 <strong>SQL</strong>*Plus DESCRIBE Command .................................................................................... 10-3viii
10.2.5 <strong>SQL</strong>*Plus SET Commands............................................................................................... 10-310.2.6 Running Scripts From <strong>SQL</strong>*Plus .................................................................................... 10-310.2.7 Spooling From <strong>SQL</strong>*Plus ................................................................................................. 10-410.2.8 Using Variables With <strong>SQL</strong>*Plus ..................................................................................... 10-410.2.8.1 Prompting for a Variable.......................................................................................... 10-410.2.8.2 Defining a Variable Value for a Query................................................................... 10-511 Working in a Global Environment11.1 Overview of Globalization Support ...................................................................................... 11-111.2 Setting up the Globalization Support Environment ........................................................... 11-311.2.1 Setting NLS Parameters ................................................................................................... 11-311.2.2 Choosing a Locale with the NLS_LANG Environment Variable .............................. 11-411.2.3 Language and Territory Parameters .............................................................................. 11-511.2.3.1 NLS_LANGUAGE..................................................................................................... 11-511.2.3.2 NLS_TERRITORY...................................................................................................... 11-611.2.4 Date and Time Parameters .............................................................................................. 11-711.2.4.1 Date Formats .............................................................................................................. 11-711.2.4.2 Time Formats ............................................................................................................. 11-911.2.5 Calendar Definitions ...................................................................................................... 11-1011.2.5.1 Calendar Formats .................................................................................................... 11-1011.2.5.2 NLS_CALENDAR ................................................................................................... 11-1111.2.6 Numeric and List Parameters ....................................................................................... 11-1111.2.6.1 Numeric Formats..................................................................................................... 11-1211.2.6.2 NLS_NUMERIC_CHARACTERS ......................................................................... 11-1211.2.7 Monetary Parameters..................................................................................................... 11-1311.2.7.1 Currency Formats.................................................................................................... 11-1311.2.7.2 NLS_CURRENCY.................................................................................................... 11-1311.2.7.3 NLS_ISO_CURRENCY ........................................................................................... 11-1411.2.7.4 NLS_DUAL_CURRENCY...................................................................................... 11-1411.2.8 Linguistic Sorting and Searching.................................................................................. 11-1411.2.8.1 NLS_SORT................................................................................................................ 11-1511.2.8.2 NLS_COMP .............................................................................................................. 11-1611.2.8.3 Case and Accent Insensitive Searching ................................................................ 11-1711.2.9 Length Semantics............................................................................................................ 11-1711.2.9.1 NLS_LENGTH_SEMANTICS................................................................................ 11-1811.3 <strong>SQL</strong> and PL/<strong>SQL</strong> Programming with Unicode ................................................................ 11-1811.3.1 Overview of Unicode ..................................................................................................... 11-1911.3.2 <strong>SQL</strong> NCHAR Data Types .............................................................................................. 11-1911.3.2.1 The NCHAR Data Type.......................................................................................... 11-2011.3.2.2 The NVARCHAR2 Data Type ............................................................................... 11-2011.3.3 Unicode String Literals .................................................................................................. 11-2111.4 Locale-Dependent <strong>SQL</strong> Functions with Optional NLS Parameters ............................... 11-2111.4.1 Default Values for NLS Parameters in <strong>SQL</strong> Functions ............................................. 11-2211.4.2 Specifying NLS Parameters in <strong>SQL</strong> Functions ........................................................... 11-2211.4.3 Unacceptable NLS Parameters in <strong>SQL</strong> Functions...................................................... 11-24ix
1<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage<strong>Oracle</strong> <strong>SQL</strong> <strong>Developer</strong> is a graphical version of <strong>SQL</strong>*Plus that gives databasedevelopers a convenient way to perform basic tasks. You can browse, create, edit, anddelete (drop) database objects; run <strong>SQL</strong> statements and scripts; edit and debugPL/<strong>SQL</strong> code; manipulate and export data; and view and create reports.You can connect to any target <strong>Oracle</strong> database schema using standard <strong>Oracle</strong> databaseauthentication. Once connected, you can perform operations on objects in thedatabase.See the Related Topics to learn about key features of <strong>SQL</strong> <strong>Developer</strong>.Related Topics<strong>SQL</strong> <strong>Developer</strong> User InterfaceDatabase ObjectsDatabase ConnectionsEntering and Modifying DataRunning and Debugging Functions and ProceduresUsing the <strong>SQL</strong> WorksheetUsing <strong>SQL</strong>*PlusUsing Snippets to Insert Code FragmentsReports<strong>SQL</strong> <strong>Developer</strong> PreferencesUsing the HelpTutorial: Creating Objects for a Small DatabaseSupplementary <strong>Oracle</strong> Database Information1.1 <strong>SQL</strong> <strong>Developer</strong> User Interface<strong>SQL</strong> <strong>Developer</strong> generally uses the left side for navigation to find and select objects,and the right side to display information about selected objects.Note: This help explains the default interface. However, you cancustomize many aspects of the appearance and behavior of <strong>SQL</strong><strong>Developer</strong> by setting preferences (see <strong>SQL</strong> <strong>Developer</strong> Preferences).<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-1
<strong>SQL</strong> <strong>Developer</strong> User InterfaceThe menus at the top contain standard entries, plus entries for features specific to <strong>SQL</strong><strong>Developer</strong> (see Menus for <strong>SQL</strong> <strong>Developer</strong>), as shown in the following figure.You can use shortcut keys to access menus and menu items: for example Alt+F for theFile menu and Alt+E for the Edit menu; or Alt+H, then Alt+S for Help, then Full TextSearch. You can also display the File menu by pressing the F10 key.Icons under the menus perform the following actions:■ New creates a new a new database object (see Create/Edit New Object).■■■■■Open opens a file (see Open File).Save saves any changes to the currently selected object.Save All saves any changes to all open objects.Open <strong>SQL</strong> Worksheet opens the <strong>SQL</strong> Worksheet (see Using the <strong>SQL</strong> Worksheet).If you do not use the drop-down arrow to specify the database connection to use,you are asked to select a connection.Back moves to the pane that you most recently visited. (Or use the drop-downarrow to specify a tab view.)■ Forward moves to the pane after the current one in the list of visited panes. (Oruse the drop-down arrow to specify a tab view.)The left side of the <strong>SQL</strong> <strong>Developer</strong> window has tabs and panes for the Connectionsand Reports navigators, icons for performing actions, and a hierarchical tree displayfor the currently selected navigator, as shown in the following figure.The Connections navigator lists database connections that have been created. Tocreate a new database connection, import an XML file with connection definitions, orexport or edit current connections, right-click the Connections node and select theappropriate menu item. (For more information, see Database Connections.)The Reports navigator lists informative reports provided by <strong>SQL</strong> <strong>Developer</strong>, such as alist of tables without primary keys for each database connection, as well as anyuser-defined reports. (For more information, see Reports.)Icons under the Connections tab (above the metadata tree) perform the followingactions on the currently selected object:1-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>SQL</strong> <strong>Developer</strong> User Interface■Refresh queries the database for the current details about the selected object (forexample, a connection or just a table).■ Apply Filter restricts the display of objects using a filter that you specify. Forexample, you can right-click the Tables node and specify a filter of EM% to seeonly tables that start with EM and to have the Tables node label be changed toTables (EM%). To remove the effects of applying a filter, right-click the node andselect Clear Filter.The metadata tree in the Connections pane displays all the objects (categorized byobject type) accessible to the defined connections. To select an object, expand theappropriate tree node or nodes, then click the object.The right side of the <strong>SQL</strong> <strong>Developer</strong> window has tabs and panes for objects that youselect or open, as shown in the following figure, which displays information about atable named BOOKS. (If you hold the mouse pointer over the tab label -- BOOKS inthis figure -- a tooltip displays the object’s owner and the database connection.)For objects other than subprograms, icons provide the following options:■■■Freeze View (the pin) keeps that object’s tab and information in the window whenyou click another object in the Connections navigator; a separate tab and displayare created for that other object. If you click the pin again, the object’s display isavailable for reuse.Edit displays a dialog box for editing the object.Refresh updates the display by querying the database for the latest information.■ Actions displays a a menu with actions appropriate for the object. The actions arethe same as when you right-click an object of that type in the Connectionsnavigator, except the Actions menu does not include Edit.To switch among objects, click the desired tabs; to close a tab, click the X in the tab. Ifyou make changes to an object and click the X, you are asked if you want to save thechanges.For tables and views, this information is grouped under tabs, which are labeled nearthe top. For example, for tables the tabs are Columns, Data (for seeing and modifyingthe data itself), Indexes, Constraints, and so on. For most objects, the tabs include <strong>SQL</strong>,which displays the <strong>SQL</strong> statement for creating the object.You can export data from a detail pane or from the results of a <strong>SQL</strong> Worksheetoperation or a report by using the right-click menu and selecting Export.The Messages - Log area is used for feedback information as appropriate (for example,results of an action, or error or warning messages). If this area is not already visible,you can display is by clicking View and then Log.<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-3
<strong>SQL</strong> <strong>Developer</strong> User InterfaceThe Compiler - Log area is used for any messages displayed as a result of a Compileor Compile for Debug operation.Related TopicsUsing the HelpDatabase ObjectsUsing the <strong>SQL</strong> WorksheetRunning and Debugging Functions and ProceduresEntering and Modifying Data<strong>SQL</strong> <strong>Developer</strong> Preferences<strong>SQL</strong> <strong>Developer</strong> Concepts and UsageTutorial: Creating Objects for a Small Database1.1.1 Menus for <strong>SQL</strong> <strong>Developer</strong>This topic explains menu items that are specific to <strong>SQL</strong> <strong>Developer</strong>.View menuContains options that affect what is displayed in the <strong>SQL</strong> <strong>Developer</strong> interface.Options: New View creates a new tab on the left side showing the hierarchy for onlythe selected connection; Freeze View keeps the tab and information in the windowwhen you click another object in the Connections navigator; a separate tab and displayare created for that other object.Connection Navigator: Moves the focus to the Connections navigator.Log: Displays the Messages - Log pane, which can contain errors, warnings, andinformational messages.Debugger: Displays panes related to debugging (see Running and DebuggingFunctions and Procedures).Run Manager: Displays the Run Manager pane, which contains entries for any activedebugging sessions.Status Bar: Controls the display of the status bar at the bottom of the <strong>SQL</strong> <strong>Developer</strong>window.Toolbars: Controls the display of the main toolbar (under the <strong>SQL</strong> <strong>Developer</strong> menus)and the Connections navigator toolbar.Refresh: Updates the current display for any open connections using the currentobjects in the affected database or databases.Snippet: Displays snippets (see Using Snippets to Insert Code Fragments).Report Navigator: Displays the Report Navigator (see Reports).Navigate menuContains options for navigating to panes and in the execution of subprograms.Back: Moves to the pane that you most recently visited.Forward: Moves to the pane after the current one in the list of visited panes.1-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>SQL</strong> <strong>Developer</strong> User InterfaceGo to Line: Goes to the specified line number and highlights the line in the editingwindow for the selected function or procedure.Go to Last Edit: Goes to the last line that was edited in the editing window for afunction or procedure.Go to Recent Files: Displays the Recent Files dialog box, in which you can specify afunction or procedure to go to.Run menuContains options relevant when a function or procedure is selected.Run [name]: Starts execution of the specified function or procedure.Execution Profile: Displays the execution profile for the selected function orprocedure.Debug menuContains options relevant when a function or procedure is selected.Debug [name]: Starts execution of the specified function or procedure in debug mode.The remaining items on the Debug menu match commands on the debugging toolbar,which is described in Running and Debugging Functions and Procedures.Source menuContains options for use when editing functions and procedures.Completion Insight, Smart Completion Insight, and Parameter Insight: Displaypop-up windows that list item as you type and from which you can select an item forautocompletion. See also the code insight and completion (autocomplete) options forCode Editor under <strong>SQL</strong> <strong>Developer</strong> Preferences.Toggle Line Comments: Inserts and removes comment indicators at the start ofselected code lines.Indent Block: Moves the selected statements to the right.Unindent Block: Moves the selected statements to the left.Tools menuInvokes <strong>SQL</strong> <strong>Developer</strong> tools.<strong>SQL</strong>*Plus: Displays a command-line window for entering <strong>SQL</strong> and <strong>SQL</strong>*Plusstatements (see Using <strong>SQL</strong>*Plus). If the location of the <strong>SQL</strong>*Plus executable is notstored in your <strong>SQL</strong> <strong>Developer</strong> preferences, you are asked to specify its location.Preferences: Enables you to customize the behavior of <strong>SQL</strong> <strong>Developer</strong> (see <strong>SQL</strong><strong>Developer</strong> Preferences).Export: Enables you to export some or all objects of one or more object types for adatabase connection to a file containing <strong>SQL</strong> data definition language (DDL)statements to create these objects (see the Export (Selected Objects or Object Types)dialog box).<strong>SQL</strong> Worksheet: Displays a worksheet in which you can enter and execute <strong>SQL</strong> andPL/<strong>SQL</strong> statements using a specified connection (see Using the <strong>SQL</strong> Worksheet).<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-5
Database Objects1.2 Database ObjectsYou can create, edit, and delete (drop) most types of objects in an <strong>Oracle</strong> database byusing the right-click menu in the Connections navigator or by clicking the Actionsbutton in the detail pane display. For some objects, you can do other operations, asappropriate for the object type.Note: The actions available from right-click menus and Actionsbuttons depend on the <strong>Oracle</strong> Database release number for thespecified database connection. If an action mentioned in the help isnot available with a connection, it may be that the feature was notavailable in that release of <strong>Oracle</strong> Database.1.2.1 Database Links1.2.2 DirectoriesRelated Topics<strong>SQL</strong> <strong>Developer</strong> Concepts and UsageTutorial: Creating Objects for a Small DatabaseSupplementary <strong>Oracle</strong> Database InformationA database link is a database object in one database that enables you to access objectson another database. The other database need not be an <strong>Oracle</strong> Database system;however, to access non-<strong>Oracle</strong> systems you must use <strong>Oracle</strong> Heterogeneous Services.After you have created a database link, you can use it to refer to tables and views inthe other database. For help with specific options in creating a database link, seeCreate/Edit Database Link.You can perform the following operations on a database link by right-clicking thedatabase link name in the Connections navigator and selecting an item from the menu:■■Test: Validates the database link.Drop: Deletes the database link.A directory object specifies an alias for a directory (called a folder on Windowssystems) on the server file system where external binary file LOBs (BFILEs) andexternal table data are located. To create a directory (that is, a directory object), you canuse <strong>SQL</strong> <strong>Developer</strong> or the <strong>SQL</strong> statement CREATE DIRECTORY.You can use directory names when referring to BFILEs in your PL/<strong>SQL</strong> code and OCIcalls, rather than hard coding the operating system path name, for managementflexibility. All directories are created in a single namespace and are not owned by anindividual schema. You can secure access to the BFILEs stored within the directorystructure by granting object privileges on the directories to specific users.You can perform the following operations on a directory by right-clicking the directoryname in the Connections navigator and selecting an item from the menu:■■Rename: Renames the directory.Drop: Deletes the directory.1-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
Database Objects1.2.3 Functions1.2.4 Indexes1.2.5 Materialized ViewsA function is a type of PL/<strong>SQL</strong> subprogram, which is a programming object that canbe stored and executed in the database server, and called from other programmingobjects or applications. (Functions return a value; procedures do not return a value.)For help with specific options in creating a PL/<strong>SQL</strong> subprogram, see Create PL/<strong>SQL</strong>Function, Procedure, or Package.You can perform the following operations on a function by right-clicking the functionname in the Connections navigator and selecting an item from the menu:■■■■■■■■Open: Displays the function text so that you can view and edit it.Compile: Performs a PL/<strong>SQL</strong> compilation of the function.Compile with Debug: Performs a PL/<strong>SQL</strong> compilation of the procedure, withPL/<strong>SQL</strong> library units compiled for debugging.Run: Displays the Run/Debug PL/<strong>SQL</strong> dialog box, and then executes the functionin normal (not debug) mode.Debug: Displays the Run/Debug PL/<strong>SQL</strong> dialog box, and then executes thefunction in debug mode.Execution Profile: Displays the execution profile for the procedure.Rename: Renames the function.Drop: Deletes the function.An index is a database object that contains an entry for each value that appears in theindexed column(s) of the table or cluster and provides direct, fast access to rows.Indexes are automatically created on primary key columns; however, you must createindexes on other columns to gain the benefits of indexing. For help with specificoptions in creating an index, see Create/Edit Index.You can perform the following operations on an index by right-clicking the indexname in the Connections navigator and selecting an item from the menu:■■■■■Drop: Deletes the index.Rebuild Index: Re-creates the index or one of its partitions or subpartitions. If theindex is unusable, a successful rebuild operation makes the index usable. For afunction-based index, rebuilding also enables the index; however, if the functionon which the index is based does not exist, the rebuild operation fails.Rename Index: Changes the name of the index.Unusable Index: Prevents the index from being used by <strong>Oracle</strong> in executingqueries. An unusable index must be rebuilt, or dropped and re-created, before itcan be used again.Coalesce Index: Merges the contents of index blocks, where possible, to free blocksfor reuse.A materialized view is a database object that contains the results of a query. The FROMclause of the query can name tables, views, and other materialized views. Collectivelythese objects are called master tables (a replication term) or detail tables (a datawarehousing term). This reference uses "master tables" for consistency. The databases<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-7
Database Objectscontaining the master tables are called the master databases. For help with specificoptions in creating a materialized view, see Create/Edit View, especially the ViewInformation or Materialized View Information tab.1.2.6 Materialized View Logs1.2.7 Packages1.2.8 ProceduresA materialized view log is a table associated with the master table of a materializedview. When DML changes are made to master table data, <strong>Oracle</strong> Database stores rowsdescribing those changes in the materialized view log and then uses the materializedview log to refresh materialized views based on the master table. This process is calledincremental or fast refresh. Without a materialized view log, <strong>Oracle</strong> Database mustre-execute the materialized view query to refresh the materialized view. This process iscalled a complete refresh. Usually, a fast refresh takes less time than a complete refresh.A package is an object that contains subprograms, which are programming objects thatcan be stored and executed in the database server, and called from other programmingobjects or applications. A package can contain functions or procedures, or both. Forhelp with specific options in creating a package, see Create PL/<strong>SQL</strong> Function,Procedure, or Package.You can perform the following operations on a package by right-clicking the packagename in the Connections navigator and selecting an item from the menu:■■New Package Body: Displays a pane in which you can enter text for the packagebody.Drop: Deletes the package.A procedure is a type of PL/<strong>SQL</strong> subprogram, which is a programming object that canbe stored and executed in the database server, and called from other programmingobjects or applications. (Procedures do not return a value; functions return a value.)For help with specific options in creating a PL/<strong>SQL</strong> subprogram, see Create PL/<strong>SQL</strong>Function, Procedure, or Package.You can perform the following operations on a procedure by right-clicking theprocedure name in the Connections navigator and selecting an item from the menu:■■■■■■■■Open: Displays the procedure text so that you can view and edit it.Compile: Performs a PL/<strong>SQL</strong> compilation of the procedure.Compile with Debug: Performs a PL/<strong>SQL</strong> compilation of the procedure, withPL/<strong>SQL</strong> library units compiled for debugging.Run: Displays the Run/Debug PL/<strong>SQL</strong> dialog box, and then executes theprocedure in normal (not debug) mode.Debug: Displays the Run/Debug PL/<strong>SQL</strong> dialog box, and then executes theprocedure in debug mode.Execution Profile: Displays the execution profile for the procedure.Drop: Deletes the procedure.Compile Dependants: Performs a PL/<strong>SQL</strong> compilation of the procedure and anyrelevant dependent subprograms (see the Dependencies tab).1-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
Database Objects1.2.9 Recycle Bin1.2.10 SequencesThe Recycle bin (applicable only to <strong>Oracle</strong> Database Release 10g) holds objects thathave been dropped (deleted). The objects are not actually deleted until a commitoperation is performed. Before the objects are actually deleted, you can "undelete"them by selecting them in the Recycle bin and selecting Undrop from the right-clickmenu.You can perform the following operations on an object in the Recycle bin byright-clicking the object name in the Recycle bin in the Connections navigator andselecting an item from the menu:■■Purge: Removes the object from the Recycle bin and deletes it.Undrop: Moves the object from the Recycle bin back to its appropriate place in theConnections navigator display.Sequences are used to generate unique integers. You can use sequences toautomatically generate primary key values. For conceptual and usage informationabout sequences, see Managing Sequences. For help with specific options in creatingand editing a sequence, see Create/Edit Sequence.1.2.11 Synonyms (Public and Private)Synonyms provide alternative names for tables, views, sequences, procedures, storedfunctions, packages, materialized views, Java class database objects, user-definedobject types, or other synonyms. The Connections navigator has a Synonyms node forall synonyms (public and private) owned by the user associated with the specifiedconnection, and a Public Synonyms node for all public synonyms on the databaseassociated with the connection. For conceptual and usage information aboutsequences, see Managing Synonyms. For help with specific options in creating andediting a synonym, see Create/Edit Synonym.1.2.12 TablesTables are used to hold data. Each table typically has multiple columns that describeattributes of the database entity associated with the table, and each column has anassociated data type. You can choose from many table creation options and tableorganizations (such as partitioned tables, index-organized tables, and external tables),to meet a variety of enterprise needs. To create a table, you can do either of thefollowing:■Create the table quickly by adding columns and specifying frequently usedfeatures. To do this, do not check Show Advanced Options in the Create Tabledialog box. For help with options for creating a table using this quick approach,see Create Table (quick creation).■ Create the table by adding columns and selecting from a larger set of features. Todo this, check Show Advanced Options in the Create Table dialog box. For helpwith options for creating a table with advanced features, see Create/Edit Table(with advanced options).You can perform the following operations on a table by right-clicking the table name inthe Connections navigator and selecting an item from the menu:■Edit: Displays the Create/Edit Table (with advanced options) dialog box.<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-9
Database Objects■■■■■■■■Table: Table actions include Rename, Copy (create a copy using a different name),Drop (delete the table), Truncate (delete existing data without affecting the tabledefinition), Lock (set the table lock mode: row share, exclusive, and so on),Comment (descriptive comment explaining the use or purpose of the table),Parallel (change the default degree of parallelism for queries and DML on thetable), No Parallel (specify serial execution), and Count Rows (return the numberof rows).Export: Enables you to export some or all of the table data to a file or to the systemclipboard, in any of the following formats: XML (XML tags and data), CSV(comma-separated values including a header row for column identifiers), <strong>SQL</strong>Insert (INSERT statements), or <strong>SQL</strong> Loader (<strong>SQL</strong>*Loader control file). After youselect a format, the Export Table Data dialog box is displayed.Column: Column actions include Comment (descriptive comment about acolumn), Add, Drop, and Normalize.Index: Options include Create (create an index on specified columns), Create Text(create an <strong>Oracle</strong> Text index on a column), Create Text (create a function-basedindex on a column), and Drop.Storage: Options include Shrink Table (shrink space in a table, for segments intablespaces with automatic segment management) and Move Table (to anothertablespace). The Shrink Table options include Compact (only defragments thesegment space and compacts the table rows for subsequent release, but does notreadjust the high water mark and does not release the space immediately) andCascade (performs the same operations on all dependent objects of the table,including secondary indexes on index-organized tables).Analyze: Options include Compute Statistics (compute exact table and columnstatistics and store them in the data dictionary), Estimate statistics (estimate tableand column statistics and store them in the data dictionary), and ValidateStructure (verifies the integrity of each data block and row, and for anindex-organized table also generates the optimal prefix compression count for theprimary key index on the table). Both computed and estimated statistics are usedby the <strong>Oracle</strong> Database optimizer to choose the execution plan for <strong>SQL</strong> statementsthat access analyzed objects.Constraint: Options include Enable or Disable Single, Drop (delete a constraint),Add Check (add a check constraint), Add Foreign Key, and Add Unique.Privileges: If you are connected as a database user with sufficient privileges, youcan Grant or Revoke privileges on the table to other users.■ Trigger: Options include Create, Create PK from Sequence (create a before-inserttrigger to populate the primary key using values from a specified sequence),Enable or Disable All, Enable or Disable Single, and Drop (delete the trigger).You can perform the following operations on a column in a table by right-clicking thecolumn name in the Connections navigator and selecting an item from the menu:■■■■Rename: Renames the column.Drop: Deletes the column (including all data in that column) from the table.Encrypt (for <strong>Oracle</strong> Database Release 10.2 and higher, and only if the TransparentData Encryption feature is enabled for the database): Displays a dialog box inwhich you specify a supported encryption algorithm to be used for encrypting alldata in the column. Current data and subsequently inserted data are encrypted.Decrypt (for <strong>Oracle</strong> Database Release 10.2 and higher, and only if the TransparentData Encryption feature is enabled for the database): Decrypts data in the column1-10 <strong>SQL</strong> <strong>Developer</strong> Online Help
Database Connectionsthat had been encrypted, and causes data that is subsequently inserted not to beencrypted.For conceptual and usage information about tables, see Managing Tables.1.2.13 TriggersTriggers are stored PL/<strong>SQL</strong> blocks associated with a table, a schema, or the database,or anonymous PL/<strong>SQL</strong> blocks or calls to a procedure implemented in PL/<strong>SQL</strong> or Java.<strong>Oracle</strong> Database automatically executes a trigger when specified conditions occur. Forconceptual and usage information about sequences, see Triggers: Usage Information.For help with specific options in creating a trigger, see Create Trigger.1.2.14 TypesA data type associates a fixed set of properties with the values that can be used in acolumn of a table or in an argument of a procedure or function. These properties cause<strong>Oracle</strong> Database to treat values of one data type differently from values of anotherdata type. Most data types are supplied by <strong>Oracle</strong>, although users can create datatypes.For conceptual and usage information about data types, see Data Types: UsageInformation. For help with specific options in creating a user-defined type, see CreateType (User-Defined).1.2.15 Users (Other Users)Database users are accounts through which you can log in to the database. In theConnections navigator, you can see the Other Users in the database associated with aconnection, but the database objects that you are allowed to see for each user aredetermined by the privileges of the database user associated with the current databaseconnection.1.2.16 ViewsViews are virtual tables (analogous to queries in some database products) that selectdata from one or more underlying tables. <strong>Oracle</strong> Database provides many viewcreation options and specialized types of views (such as materialized views, describedin Materialized Views), to meet a variety of enterprise needs. For conceptual and usageinformation about views, see Managing Views. For help with specific options increating and editing a view, see Create/Edit View.You can perform the following operations on a view by right-clicking the view namein the Connections navigator and selecting an item from the menu:■■■Edit: Displays the Create/Edit View dialog box.Drop: Deletes the view.Compile: Recompiles the view, to enable you to locate possible errors before runtime. You may want to recompile a view after altering one of its base tables toensure that the change does not affect the view or other objects that depend on it.1.3 Database ConnectionsA connection is a <strong>SQL</strong> <strong>Developer</strong> object that specifies the necessary information forconnecting to a specific database as a specific user of that database. You must have atleast one database connection (existing, created, or imported) to use <strong>SQL</strong> <strong>Developer</strong>.<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-11
Database ConnectionsWhen you start <strong>SQL</strong> <strong>Developer</strong> and whenever you display the database connectionsdialog box, <strong>SQL</strong> <strong>Developer</strong> automatically imports any connections defined in thetnsnames.ora file on your system, if that file exists. By default, tnsnames.ora is locatedin the $ORACLE_HOME/network/admin directory, but it can also be in the directoryspecified by the TNS_ADMIN environment variable or registry value or (on UNIXsystems) the global configuration directory. On Windows systems, if the tnsnames.orafile exists but its connections are not being used by <strong>SQL</strong> <strong>Developer</strong>, define TNS_ADMIN as a system environment variable. For information about the tnsnames.orafile, see the "Local Naming Parameters (tnsnames.ora)" chapter in <strong>Oracle</strong> Database NetServices Reference.You can create additional connections (for example, to connect to the same databasebut as different users, or to connect to different databases). Each database connection islisted in the Connections navigator hierarchy.To create a new database connection, right-click the Connections node and select NewDatabase Connection. Use the dialog box to specify information about the connection(see Create/Edit/Select Database Connection).To edit the information about an existing database connection, right-click theconnection name in the Connections navigator display and select Properties. Use thedialog box to modify information about the connection (see Create/Edit/SelectDatabase Connection).To export information about the existing database connections into an XML file thatyou can later use for importing connections, right-click Connections in theConnections navigator display and select Export Connections. Use the dialog box tospecify the connections to be exported (see Export/Import Connection Descriptors).To import connections that had previously been exported (adding them to anyconnections that may already exist in <strong>SQL</strong> <strong>Developer</strong>), right-click Connections in theConnections navigator display and select Import Connections. Use the dialog box tospecify the connections to be imported (see Export/Import Connection Descriptors).To delete a connection (that is, delete it from <strong>SQL</strong> <strong>Developer</strong>, not merely disconnectfrom the current connection), right-click the connection name in the Connectionsnavigator display and select Delete. Deleting a connection does not delete the userassociated with that connection.To connect using an existing connection, expand its node in the Connections navigator,or right-click its name and select Connect. A <strong>SQL</strong> Worksheet window is also openedfor the connection (see Using the <strong>SQL</strong> Worksheet).To disconnect from the current connection, right-click its name in the Connectionsnavigator and select Disconnect.Sharing of ConnectionsBy default, each connection in <strong>SQL</strong> <strong>Developer</strong> is shared when possible. For example, ifyou open a table in the Connections navigator and two <strong>SQL</strong> Worksheets using thesame connection, all three panes use one shared connection to the database. In thisexample, a commit operation in one <strong>SQL</strong> Worksheet commits across all three panes. Ifyou want a dedicated session, you must duplicate your connection and give it anothername. Sessions are shared by name, not connection information, so this newconnection will be kept separate from the original.Related TopicsCreate/Edit/Select Database ConnectionExport/Import Connection Descriptors1-12 <strong>SQL</strong> <strong>Developer</strong> Online Help
Entering and Modifying Data<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage1.4 Entering and Modifying DataYou can use <strong>SQL</strong> <strong>Developer</strong> to enter data into tables and to edit and delete existingtable data. To do any of these operations, select the table in the Connections navigator,then click the Data tab in the table detail display. The following figure shows the Datapane for a table named BOOKS, with a filter applied to show only books whose ratingis 10.Icons and other controls under the Data tab provide the following options:■■■■■■■Freeze View (the pin) keeps that object’s tab and information in the window whenyou click another object in the Connections navigator; a separate tab and displayare created for that other object. If you click the pin again, the object’s display isavailable for reuse.Insert Row adds an empty row after the selected row, for you to enter new data.Delete Selected Row(s) marks the selected rows for deletion. The actual deletiondoes not occur until you commit changes.Commit Changes ends the current transaction and makes permanent all changesperformed in the transaction.Rollback Changes undoes any work done in the current transaction.Sort displays a dialog box for selecting columns to sort by. For each column, youcan specify ascending or descending order, and you can specify that null values bedisplayed first.Filter enables you to enter a <strong>SQL</strong> predicate (WHERE clause text without theWHERE keyword) for limiting the display of data. For example, to show onlyrows where the RATING column value is equal to 10, specify: rating = 10■ Refresh (to the right of the icons shown in the preceding figure) queries thedatabase to update the data display. If a filter is specified, the refresh operationuses the filter.In the Data pane for a table or view, you can split the display vertically or horizontallyto see two (or more) parts independently by using the split box (thin blue rectangle),located to the right of the bottom scroll bar and above the right scroll bar.In the Data pane, the acceptable format or formats for entering dates may be differentfrom the date format required by <strong>SQL</strong>*Plus.Related Topics<strong>SQL</strong> <strong>Developer</strong> User Interface<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-13
Running and Debugging Functions and Procedures1.5 Running and Debugging Functions and ProceduresYou can use <strong>SQL</strong> <strong>Developer</strong> to run and debug PL/<strong>SQL</strong> functions and procedures.■To run a function or procedure, click its name in the Connections navigator; theneither right-click and select Run, or click the Edit icon and then click the Run iconabove its source listing.■ To debug a function or procedure, click its name in the Connections navigator. Ifthe procedure in its current form has not already been compiled for debug,right-click and select Compile for Debug. Then click the Edit icon and click theDebug icon above its source listing.In both cases, a code editing window is displayed. The following figure shows thecode editing window being used to debug a procedure named LIST_A_RATING2,which is used for tutorial purposes in Debugging a PL/<strong>SQL</strong> Procedure.The code editing window has the following tabs:■■The Source tab displays a toolbar and the text of the function or procedure, whichyou can edit. You can set and unset breakpoints for debugging by clicking to theleft of the thin vertical line beside each statement with which you want to associatea breakpoint. (When a breakpoint is set, a red circle is displayed.)The Privileges tab displays, for each privilege associated with the function orprocedure, the grantor and grantee, the object name, and whether the grantee cangrant the privilege to other users.1-14 <strong>SQL</strong> <strong>Developer</strong> Online Help
Running and Debugging Functions and Procedures■ The Dependencies tab shows any objects that this function or procedurereferences, and any objects that reference this function or procedure.The Source tab toolbar has the icons shown in the following figure.■■■Run starts normal execution of the function or procedure, and displays the resultsin the Running - Log tab.Debug starts execution of the function or procedure in debug mode, and displaysthe Debugging - Log tab, which includes the debugging toolbar for controlling theexecution.Compile performs a PL/<strong>SQL</strong> compilation of the function or procedure.■ Compile for Debug performs a PL/<strong>SQL</strong> compilation of the function or procedureso that it can be debugged.The Debugging - Log tab under the code text area contains the debugging toolbar andinformational messages. The debugging toolbar has the icons shown in the followingfigure.■■■■■■■■Find Execution Point goes to the next execution point.Resume continues execution.Step Over bypasses the next method and goes to the next statement after themethod.Step Into goes to the first statement in the next method.Step Out leaves the current method and goes to the next statement.Step to End of Method goes to the last statement of the current method.Pause halts execution but does not exit, thus allowing you to resume execution.Terminate halts and exits the execution. You cannot resume execution from thispoint; instead, to start running or debugging from the beginning of the function orprocedure, click the Run or Debug icon in the Source tab toolbar.■ Garbage Collection removes invalid objects from the cache in favor of morefrequently accessed and more valid objects.The Breakpoints tab under the code text area displays breakpoints, bothsystem-defined and user-defined.The Smart Data tab under the code text area displays information about variablesassociated with breakpoints.The Data tab under the code text area displays information about all variables.The Watches tab under the code text area displays information about watchpoints.For more information about developing, compiling, and using PL/<strong>SQL</strong> functions andprocedures, see Subprograms and Packages: Usage Information.<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-15
Using the <strong>SQL</strong> WorksheetRelated TopicsUsing Snippets to Insert Code FragmentsRun/Debug PL/<strong>SQL</strong> (dialog box)Debugging a PL/<strong>SQL</strong> Procedure (tutorial)Subprograms and Packages: Usage Information<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage1.6 Using the <strong>SQL</strong> WorksheetYou can use the <strong>SQL</strong> Worksheet to enter and execute <strong>SQL</strong>, PL/<strong>SQL</strong>, and <strong>SQL</strong>*Plusstatements. You can specify any actions that can be processed by the databaseconnection associated with the worksheet, such as creating a table, inserting data,creating and editing a trigger, selecting data from a table, and saving that data to a file.When you connect to a database, a <strong>SQL</strong> Worksheet window for that connection isautomatically opened. You can also display a <strong>SQL</strong> Worksheet by selecting Tools andthen <strong>SQL</strong> Worksheet, or by clicking the Use <strong>SQL</strong> Worksheet icon under the menu bar.In the Select Connection dialog box, select the database connection to use for yourwork with the worksheet. (You can also use that dialog box to create and edit databaseconnections.)The <strong>SQL</strong> Worksheet has the user interface shown in the following figure:<strong>SQL</strong> Worksheet toolbar (under the <strong>SQL</strong> Worksheet tab): Contains icons for thefollowing operations:■Execute Statement executes the statement at the mouse pointer in the Enter <strong>SQL</strong>Statement box. The <strong>SQL</strong> statements can include bind variables (but notsubstitution variables) of type VARCHAR2 (although in most cases, VARCHAR2is automatically converted internally to NUMBER if necessary); a pop-up box isdisplayed for entering bind variable values.1-16 <strong>SQL</strong> <strong>Developer</strong> Online Help
Using the <strong>SQL</strong> Worksheet■■■■■■■■Run Script executes all statements in the Enter <strong>SQL</strong> Statement box using the ScriptRunner. The <strong>SQL</strong> statements can include substitution variables (but not bindvariables) of type VARCHAR2 (although in most cases, VARCHAR2 isautomatically converted internally to NUMBER if necessary); a pop-up box isdisplayed for entering substitution variable values.Cancel: Stops the execution of any statements currently being executed.<strong>SQL</strong> History: Displays a dialog box with information about <strong>SQL</strong> statements thatyou have executed. You can save statements to a file, or append to or overwritestatements on the worksheet (see <strong>SQL</strong> History List).Execute Explain Plan: Generates the execution plan for the statement (internallyexecuting the EXPLAIN PLAN statement). To see the execution plan, click theExplain tab. For more information, see Execution Plan.Clear: Erases the statement or statements in the Enter <strong>SQL</strong> Statement box.Open File: Opens a <strong>SQL</strong> script file that you specify and displays it in the Enter<strong>SQL</strong> Statement box.Save File: Saves the contents of the Enter <strong>SQL</strong> Statement box to a <strong>SQL</strong> script filethat you specify.Print File: Prints the contents of the Enter <strong>SQL</strong> Statement box.■ To the right of these icons is a drop-down list for changing the databaseconnection to use with the worksheet.Enter <strong>SQL</strong> Statement: The statement or statements that you intend to execute. (For asingle statement, the semicolon at the end is optional in the <strong>SQL</strong> Worksheet.) <strong>SQL</strong>keywords are automatically highlighted. To format the statement (capitalizing thenames of statements, clauses, keywords, and so on), right-click in the statement areaand select Format <strong>SQL</strong>.You can drag some kinds of objects from the Connections navigator and drop theminto the Enter <strong>SQL</strong> Statement box:■If you drag and drop a table or view, a SELECT statement is constructed with allcolumns in the table or view. You can then edit the statement, for example,modifying the column list or adding a WHERE clause.■ If you drag and drop a function or procedure, a snippet-like text block isconstructed for you to edit when including that object in a statement.Tabs display panes with the following information:■■■■■Results: Displays the results of the most recent Execute Statement operation.Explain: Displays the output if you clicked the Explain Execution Plan icon (seeExecution Plan).Script Output: Displays the output if you clicked the Run Script icon (see ScriptRunner).DBMS Output: Displays the output of DBMS_OUTPUT package statements (seeDBMS Output Pane).OWA Output: Displays <strong>Oracle</strong> Web Agent (MOD_PL<strong>SQL</strong>) output (see OWAOutput Pane).Related Topics<strong>SQL</strong>*Plus Statements Supported and Not Supported in <strong>SQL</strong> Worksheet<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-17
Using the <strong>SQL</strong> WorksheetScript RunnerExecution PlanUsing Snippets to Insert Code FragmentsUsing the <strong>SQL</strong> Worksheet for Queries (tutorial)<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage1.6.1 <strong>SQL</strong>*Plus Statements Supported and Not Supported in <strong>SQL</strong> WorksheetThe <strong>SQL</strong> Worksheet supports some <strong>SQL</strong>*Plus statements. <strong>SQL</strong>*Plus statements mustbe interpreted by the <strong>SQL</strong> Worksheet before being passed to the database; any<strong>SQL</strong>*Plus that are not supported by the <strong>SQL</strong> Worksheet are ignored and not passed tothe database.The following <strong>SQL</strong>*Plus statements are supported by the <strong>SQL</strong> Worksheet:@@@acc[ept]conn[ect]def[ine]desc[ribe]doc[ument]exec[ute]exit (Stops execution and reinstates the specified connection)pro[mpt]quit (Stops execution and reinstates the specified connection)rem[ark]sta[rt]undef[ine]wheneverThe following <strong>SQL</strong>*Plus statements are not supported by the <strong>SQL</strong> Worksheet:a[ppend]archiveattr[ibute]bre[ak]bti[tle]c[hange]cl[ear]col[ulmn]comp[ute]copydeldisc[onnect]ed[it]gethelpho[st]i[nput]l[ist]newpageoradebugpassw[ord]pau[se]printr[un]recoverrepf[ooter]1-18 <strong>SQL</strong> <strong>Developer</strong> Online Help
Using the <strong>SQL</strong> Worksheetreph[eader]sav[e]sho[w]shu[tdown]spo[ol]startupstoretimi[ng]tti[tle]var[iable]Related TopicsUsing the <strong>SQL</strong> Worksheet1.6.2 Script RunnerThe script runner emulates a limited set of <strong>SQL</strong>*Plus features. If you do not have<strong>SQL</strong>*Plus on your system, you can often enter <strong>SQL</strong> and <strong>SQL</strong>*Plus statements andexecute them by clicking the Run Script icon. The Script Output pane displays theoutput.The <strong>SQL</strong>*Plus features available in the script runner include @, @@, CONNECT, EXIT,QUIT, UNDEFINE, WHENEVER, and substitution variables. For example, to run ascript named c:\myscripts\mytest.sql, type @c:\myscripts\mytest in the Enter <strong>SQL</strong>Statement box, and click the drop-down next to the Execute Statement icon and selectRun Script.The following considerations apply to using the <strong>SQL</strong> <strong>Developer</strong> script runner:■ You cannot use bind variables. (The Execute <strong>SQL</strong> Statement feature does let youuse bind variables of type VARCHAR2, NUMBER, and DATE.)■■■■For substitution variables, the syntax &&variable assigns a permanent variablevalue, and the syntax &variable assigns a temporary (not stored) variable value.For EXIT and QUIT, commit is the default behavior, but you can specify rollback.In either case, the context is reset: for example, WHENEVER commandinformation and substitution variable values are cleared.DESCRIBE works for most, but not all, object types for which it is supported in<strong>SQL</strong>*Plus.For <strong>SQL</strong>*Plus commands that are not supported, a warning message is displayed.■ <strong>SQL</strong>*Plus comments are ignored.If you have <strong>SQL</strong>*Plus available on your system, you may want to use it instead of thescript runner. To start <strong>SQL</strong>*Plus from <strong>SQL</strong> <strong>Developer</strong>, click Tools and then <strong>SQL</strong>*Plus.For information about <strong>SQL</strong>*Plus, see Using <strong>SQL</strong>*Plus.Related TopicsUsing the <strong>SQL</strong> Worksheet1.6.3 Execution PlanThe Execute Explain Plan icon generates the execution plan, which you can see byclicking the Explain tab. The execution plan is the sequence of operations that will beperformed to execute the statement. An execution plan shows a row source tree withthe hierarchy of operations that make up the statement. For each operation, it showsthe ordering of the tables referenced by the statement, access method for each table<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-19
Using the <strong>SQL</strong> Worksheetmentioned in the statement, join method for tables affected by join operations in thestatement, and data operations such as filter, sort, or aggregation.In addition to the row source tree, the plan table displays information aboutoptimization (such as the cost and cardinality of each operation), partitioning (such asthe set of accessed partitions), and parallel execution (such as the distribution methodof join inputs). For more information, see the chapter about using EXPLAIN PLAN in<strong>Oracle</strong> Database Performance Tuning Guide.Related TopicsUsing the <strong>SQL</strong> Worksheet1.6.4 DBMS Output PaneThe PL/<strong>SQL</strong> DBMS_OUTPUT package enables you to send messages from storedprocedures, packages, and triggers. The PUT and PUT_LINE procedures in thispackage enable you to place information in a buffer that can be read by anothertrigger, procedure, or package. In a separate PL/<strong>SQL</strong> procedure or anonymous block,you can display the buffered information by calling the GET_LINE procedure. TheDBMS Output pane is used to display the output of that buffer. This pane containsicons and other controls for the following operations:■■■■■■Enable/Disable DBMS Output: Toggles the SET SERVEROUTPUT settingbetween ON and OFF. Setting server output ON checks for any output that isplaced in the DBMS_OUTPUT buffer, and any output is displayed in the pane.Clear: Erases the contents of the pane.Save: Saves the contents of the pane to a file that you specify.Print: Prints the contents of the pane.Buffer Size: For databases before <strong>Oracle</strong> Database 10.2, limits the amount of datathat can be stored in the DBMS_OUTPUT buffer. The buffer size can be between 1and 1000000 (1 million).Poll: The interval (in seconds) at which <strong>SQL</strong> <strong>Developer</strong> will check the DBMS_OUTPUT buffer to see if there is data to print. The poll rate can be between 1 and15.Related TopicsUsing the <strong>SQL</strong> Worksheet1.6.5 OWA Output PaneOWA (<strong>Oracle</strong> Web Agent) or MOD_PL<strong>SQL</strong> is an Apache (Web Server) extensionmodule that enables you to create dynamic Web pages from PL/<strong>SQL</strong> packages andstored procedures. The OWA Output pane enables you to see the HTML output ofMOD_PL<strong>SQL</strong> actions that have been executed in the <strong>SQL</strong> Worksheet. This panecontains icons for the following operations:■■■■Enable/Disable OWA Output: Enables and disables the checking of the OWAoutput buffer and the display of OWA output to the pane.Clear: Erases the contents of the pane.Save: Saves the contents of the pane to a file that you specify.Print: Prints the contents of the pane.1-20 <strong>SQL</strong> <strong>Developer</strong> Online Help
Using Snippets to Insert Code FragmentsRelated TopicsUsing the <strong>SQL</strong> Worksheet1.7 Using <strong>SQL</strong>*PlusYou can use the <strong>SQL</strong>*Plus command-line interface to enter <strong>SQL</strong> and PL/<strong>SQL</strong>statements accessing the database associated with a specified connection. To displaythe <strong>SQL</strong>*Plus command window, from the Tools menu, select <strong>SQL</strong>*Plus.To use this feature, the system on which you are using <strong>SQL</strong> <strong>Developer</strong> must have an<strong>Oracle</strong> Home directory or folder, with a <strong>SQL</strong>*Plus executable under that location. If thelocation of the <strong>SQL</strong>*Plus executable is not already stored in your <strong>SQL</strong> <strong>Developer</strong>preferences, you are asked to specify its location (see <strong>SQL</strong>*Plus Location).If you do not have a <strong>SQL</strong>*Plus executable on your system, you can execute come<strong>SQL</strong>*Plus statements using the <strong>SQL</strong> Worksheet (see <strong>SQL</strong>*Plus Statements Supportedand Not Supported in <strong>SQL</strong> Worksheet), and you can also use the <strong>SQL</strong> <strong>Developer</strong> scriptrunner feature to emulate a limited set of <strong>SQL</strong>*Plus features (see Script Runner).For more information about using <strong>SQL</strong>*Plus, see <strong>SQL</strong>*Plus: Usage Information.Related Topics<strong>SQL</strong>*Plus Location (dialog box)<strong>SQL</strong>*Plus: Usage Information<strong>SQL</strong>*Plus Statements Supported and Not Supported in <strong>SQL</strong> WorksheetScript Runner<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage1.8 Using Snippets to Insert Code FragmentsSnippets are code fragments, such as <strong>SQL</strong> functions, Optimizer hints, andmiscellaneous PL/<strong>SQL</strong> programming techniques. Some snippets are just syntax, andothers are examples. You can insert and edit snippets when you are using the <strong>SQL</strong>Worksheet or creating or editing a PL/<strong>SQL</strong> function or procedure.To display snippets, from the View menu, select Snippets. In the snippets window (onthe right side), use the drop-down to select a group (such as Aggregate Functions orCharacter Functions). In most cases, the fragments in each group do not represent allavailable objects in that logical grouping, or all formats and options of each fragmentshown. For complete and detailed information, see the <strong>Oracle</strong> Databasedocumentation.A Snippets button is placed in the right window margin, so that you can display thesnippets window if it becomes hidden.To insert a snippet into your code in a <strong>SQL</strong> Worksheet or in a PL/<strong>SQL</strong> function orprocedure, drag the snippet from the snippets window and drop it into the desiredplace in your code; then edit the syntax so that the <strong>SQL</strong> function is valid in the currentcontext. To see a brief description of a <strong>SQL</strong> function in a tooltip, hold the pointer overthe function name.For example, you could type SELECT and then drag CONCAT(char1, char2) from theCharacter Functions group. Then, edit the CONCAT function syntax and type the restof the statement, such as in the following:SELECT CONCAT(title, ' is a book in the library.') FROM books;<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-21
Reports1.9 ReportsRelated TopicsRunning and Debugging Functions and ProceduresUsing the <strong>SQL</strong> Worksheet<strong>SQL</strong> <strong>Developer</strong> provides many reports about the database and its objects. You can alsocreate your own user-defined reports. To display reports, click the Reports tab on theleft side of the window (see <strong>SQL</strong> <strong>Developer</strong> User Interface). If this tab is not visible,select View and then Reports.Individual reports are displayed in tabbed panes on the right side of the window; andfor each report, you can select (in a drop-down control) the database connection forwhich to display the report. For reports about objects, the objects shown are only thosevisible to the database user associated with the selected database connection, and therows are usually ordered by Owner.To see the <strong>SQL</strong> statement used to retrieve the information for a report, click the <strong>SQL</strong>icon above the report and to the right of the database connection. Clicking this icondisplays the statement in the <strong>SQL</strong> Worksheet (see Using the <strong>SQL</strong> Worksheet).The time required to display specific reports will vary, and may be affected by thenumber and complexity of objects involved, and by the speed of the networkconnection to the database.For most reports that contain names of database objects, you can double-click theobject name in the report display pane to display that object in a detail view pane, justas if you had selected that object using the Connections navigator.Reports are grouped in the following categories:About Your Database reports list release information about the database associatedwith the connection.Database Administration reports list usage information about system resources.Table reports list information about tables owned by the user associated with thespecified connection. These reports can help you to better understand the metadataand data. The table reports include Quality Assurance reports that indicate possiblelogical design flaws and sources of run-time performance problems.PL/<strong>SQL</strong> reports list information about your PL/<strong>SQL</strong> objects and allow you to searchthe source of those objects.Security reports list privilege-related information about the database.XML reports list information about XML objects.Jobs reports list information about jobs running on the database.Streams reports list information about stream rules.All Objects reports list information about all objects accessible to the user associatedwith the specified database connection, not just objects owned by the user.Data Dictionary reports list information about the data dictionary views that areaccessible in the database. Examples of data dictionary views are ALL_OBJECTS andUSER_TABLES.User Defined reports are any customized reports that you have created.1-22 <strong>SQL</strong> <strong>Developer</strong> Online Help
ReportsBind Variables for ReportsFor some reports, you are prompted for bind variables before the report is generated.These bind variables let you further restrict the output. The default value for all bindvariables is null, which implies no further restrictions. To specify a bind variable,uncheck Null and type an entry in the Value field. Any bind variable values that youenter are case insensitive, all matches are returned where the value string appearsanywhere in the name of the relevant object type.Related Topics<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage<strong>SQL</strong> <strong>Developer</strong> User InterfaceUsing the <strong>SQL</strong> Worksheet<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage1.9.1 About Your Database reportsThe About Your Database reports list release information about the databaseassociated with the selected connection. The reports include Version Banner (databasesettings) and National Language Support Parameters (NLS_xxx parameter values forglobalization support).Related TopicsReports1.9.2 Database Administration reportsDatabase Administration reports list usage information about system resources. Thisinformation can help you to manage storage, user accounts, and sessions efficiently.Database Parameters: Provide information about all database parameters or onlythose parameters that are not set to their default values.Storage: Provide usage and allocation information for tablespaces and data files.Sessions: Provide information about sessions, selected and ordered by various criteria.Cursors: Provide information about cursors, including cursors by session (includingopen cursors and cursor details.All Tables: Contains the reports that are also grouped under Table reports, includingQuality Assurance reports.Top <strong>SQL</strong>: Provide information about <strong>SQL</strong> statements, selected and ordered by variouscriteria. This information might help you to identify <strong>SQL</strong> statements that are beingexecuted more often than expected or that are taking more time than expected.Users: Provide information about database users, selected and ordered by variouscriteria. For example, you can find out which users were created most recently, whichuser accounts have expired, and which users use object types and how many objectseach owns.Related TopicsReports<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-23
Reports1.9.3 Table reportsTable reports list information about tables owned by the user associated with thespecified connection. This information is not specifically designed to identify problemareas; however, depending on your resources and requirements, some of theinformation might indicate things that you should monitor or address.For table reports, the owner is the user associated with the database connection.Columns: For each table, lists each column, its data type, and whether it can contain anull value.Datatype Occurrences: For each table owner, lists each data type and how many timesit is used.Comments for tables and columns: For each table and for each column in each table,lists the descriptive comments (if any) associated with it. Also includes a report oftables without comments. If database developers use the COMMENT statement whencreating or modifying tables, this report can provide useful information about thepurposes of tables and columnsConstraints: For each table, lists each associated constraint, including its type (uniqueconstraint, check constraint, primary key, foreign key) and status (enabled ordisabled).Enabled Constraints and Disabled Constraints: For each constraint with a status ofenabled or disabled, lists the table name, constraint name, constraint type (uniqueconstraint, check constraint, primary key, foreign key), and status. A disabledconstraint is not enforced when rows are added or modified; to have a disabledconstraint enforced, you must edit the table and set the status of the constraint toEnabled (see the appropriate tabs for Create/Edit Table (with advanced options)).Primary Key Constraints: For primary key constraint, lists information that includesthe owner, the table name, the constraint name, the constraint status (enabled ordisabled), and the column name.Unique Constraints: For each unique constraint, lists information that includes theowner, the table name, the constraint name, the constraint status (enabled or disabled),and the column name.Foreign Key Constraints: For each foreign key constraint, lists information thatincludes the owner, the table name, the constraint name, the column that the constraintis against, the table that the constraint references, and the constraint in the table that isreferenced.Check Constraints: For each check constraint, lists information that includes theowner, the table name, the constraint name, the constraint status (enabled or disabled),and the constraint specification.Statistics: For each table, lists statistical information, including when it was lastanalyzed, the total number of rows, the average row length, and the table type. Inaddition, specialized reports order the results by most rows and largest average rowlength.Storage - Tables by Tablespace: For each tablespace, lists the number of tables and thetotal number of megabytes currently allocated for the tables.Storage - Tablespaces: For each table, lists the tablespace for the table and the numberof megabytes currently allocated for the table.Organization: Specialized reports list information about partitioned tables, clusteredtables, and index-organized tables.1-24 <strong>SQL</strong> <strong>Developer</strong> Online Help
ReportsQuality Assurance reportsQuality assurance reports are table reports that identify conditions that are nottechnically errors, but that usually indicate flaws in the database design. These flawscan result in various problems, such as logic errors and the need for additionalapplication coding to work around the errors, as well as poor performance withqueries at run time.Tables without Primary Keys: Lists tables that do not have a primary key defined. Aprimary key is a column (or set of columns) that uniquely identifies each row in thetable. Although tables are not required to have a primary key, it is stronglyrecommended that you create or designate a primary key for each table. Primary keycolumns are indexed, which enhances performance with queries, and they arerequired to be unique and not null, providing some "automatic" validation of inputdata. Primary keys can also be used with foreign keys to provide referential integrity.Tables without Indexes: Lists tables that do not have any indexes. If a column in atable has an index defined on it, queries that use the column are usually much fasterand more efficient than if there is no index on the column, especially if there are manyrows in the table and many different data values in the column.Tables with Unindexed Foreign Keys: Lists any foreign keys that do not have anassociated index. A foreign key is a column (or set of columns) that references aprimary key: that is, each value in the foreign key must match a value in its associatedprimary key. Foreign key columns are often joined in queries, and an index usuallyimproves performance significantly for queries that use a column. If an unindexedforeign key is used in queries, you may be able to improve run-time performance bycreating an index on that foreign key.Related TopicsReports1.9.4 PL/<strong>SQL</strong> reportsPL/<strong>SQL</strong> reports list information about PL/<strong>SQL</strong> packages, function, and procedures,and about types defined in them.Program Unit Arguments: For each argument (parameter) in a program unit, lists theprogram unit name, the argument position (1, 2, 3, and so on), the argument name,and whether the argument is input-only (In), output-only (Out), or both input andoutput (In/Out).Unit Line Counts: For each PL/<strong>SQL</strong> object, lists the number of source code lines. Thisinformation can help you to identify complex objects (for example, to identify codethat may need to be simplified or divided into several objects).Search Source Code: For each PL/<strong>SQL</strong> object, lists the source code for each line, andallows the source to be searched for occurrences of the specified variable.Related TopicsReports1.9.5 Security reportsSecurity reports list information about users that have been granted privileges, and insome cases about the users that granted the privileges. This information can help you(or the database administrator if you are not a DBA) to understand possible security<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-25
Reportsissues and vulnerabilities, and to decide on the appropriate action to take (forexample, revoking certain privileges from users that do not need those privileges).Object Grants: For each privilege granted on a specific table, lists the user that grantedthe privilege, the user to which the privilege was granted, the table, the privilege, andwhether the user to which the privilege was granted can grant that privilege to otherusers.Column Privileges: For each privilege granted on a specific column in a specific table,lists the user that granted the privilege, the user to which the privilege was granted,the table, the privilege, and whether the user to which the privilege was granted cangrant that privilege to other users.Role Privileges: For each granted role, lists the user to which the role was granted, therole, whether the role was granted with the ADMIN option, and whether the role isdesignated as a default role for the user.System Privileges: For each privilege granted to the user associated with the databaseconnection, lists the privilege and whether it was granted with the ADMIN option.Auditing: Lists information about audit policies.Encryption: Lists information about encrypted columns.Policies: Lists information about policies.Related TopicsReports1.9.6 XML reportsXML reports list information about XML objects.XML Schemas: For each user that owns any XML objects, lists information about eachobject, including the schema URL of the XSD file containing the schema definition.Related TopicsReports1.9.7 Jobs reportsJobs reports list information about jobs running on the database.Your Jobs: Lists information about each job for which the user associated with thedatabase connection is the log user, privilege user, or schema user. The informationincludes the start time of its last run, current run, and next scheduled run.All Jobs: Lists information about all jobs running on the database. The informationincludes the start time of its last run, current run, and next scheduled run.Related TopicsReports1.9.8 Streams reportsStreams reports list information about stream rules.Your Stream Rules: Lists information about each stream rule for which the userassociated with the database connection is the rule owner or rule set owner. The1-26 <strong>SQL</strong> <strong>Developer</strong> Online Help
Reportsinformation includes stream type and name, rule set owner and name, rule owner andname, rule set type, streams rule type, and subsetting operation.All Stream Rules: Lists information about all stream rules. The information includesstream type and name, rule set owner and name, rule owner and name, rule set type,streams rule type, and subsetting operation.Related TopicsReports1.9.9 All Objects reportsAll Objects reports list information about objects visible to the user associated with thedatabase connection.All Objects: For each object, lists the owner, name, type (table, view, index, and so on),status (valid or invalid), the date it was created, and the date when the last datadefinition language (DDL) operation was performed on it. The Last DDL date can helpyou to find if any changes to the object definitions have been made on or after aspecific time.Invalid Objects: Lists all objects that have a status of invalid.Object Count by Type: For each type of object associated with a specific owner, liststhe number of objects. This report might help you to identify users that have createdan especially large number of objects, particularly objects of a specific type.Collection Types: Lists information about for each collection type. The informationincludes the type owner, element type name and owner, and type-dependent specificinformation.Dependencies: For each object with references to it, lists information about referencesto (uses of) that object.Related TopicsReports1.9.10 Data Dictionary reportsData Dictionary reports list information about the data dictionary views that areaccessible in the database. Examples of data dictionary views are ALL_OBJECTS andUSER_TABLES.Dictionary Views: Lists each <strong>Oracle</strong> data dictionary view and (in most cases) acomment describing its contents or purpose.Dictionary View Columns: For each <strong>Oracle</strong> data dictionary view, lists informationabout the columns in the view.Related TopicsReports1.9.11 User Defined reportsUser Defined reports are any reports that are created by <strong>SQL</strong> <strong>Developer</strong> users. Tocreate a user-defined report, right-click the User Defined node under Reports andselect Add Report. A dialog box is displayed in which you specify the report name<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-27
<strong>SQL</strong> <strong>Developer</strong> Preferencesand the <strong>SQL</strong> query to retrieve information for the report (see Create/Edit UserDefined Report).You can organize user-defined reports in folders, and you can create a hierarchy offolders and subfolders. To create a folder for user-defined reports, right-click the UserDefined node or any folder name under that node and select Add Folder (seeCreate/Edit User Defined Report Folder).Information about user-defined reports, including any folders for these reports, isstored in a file named UserReports.xml under the directory for user-specificinformation. For information about the location of this information, see <strong>SQL</strong><strong>Developer</strong> User Information: Location.Related TopicsReportsCreate/Edit User Defined ReportCreate/Edit User Defined Report Folder<strong>SQL</strong> <strong>Developer</strong> User Information: Location1.10 <strong>SQL</strong> <strong>Developer</strong> Preferences1.10.1 EnvironmentYou can customize many aspects of the <strong>SQL</strong> <strong>Developer</strong> interface and environment bymodifying <strong>SQL</strong> <strong>Developer</strong> preferences according to your preferences and needs. Tomodify <strong>SQL</strong> <strong>Developer</strong> preferences, select Tools, then Preferences.Information about <strong>SQL</strong> <strong>Developer</strong> preferences is stored under the directory foruser-specific information. For information about the location of this information, see<strong>SQL</strong> <strong>Developer</strong> User Information: Location.Most preferences are self-explanatory, and this topic explains only those whosemeaning and implications are not obvious. Some preferences involve slight orperformance or system resource trade-offs (for example, enabling a feature that addsexecution time), and other preferences involve only personal aesthetic taste. Thepreferences are grouped in the following categories.The Environment pane contains options that affect the startup and overall behaviorand appearance of <strong>SQL</strong> <strong>Developer</strong>. You can specify that certain operations beperformed automatically at specified times, with the trade-off usually being the extratime for the operation as opposed to the possibility of problems if the operation is notperformed automatically (for example, if you forget to perform it when you should).The undo level (number of previous operations that can be undone) and navigationlevel (number of open files) values involve slight increases or decreases systemresource usage for higher or lower values.Automatically Reload Externally Modified Files: If this option is checked, any filesopen in <strong>SQL</strong> <strong>Developer</strong> that have been modified by an external application areupdated when you switch back to <strong>SQL</strong> <strong>Developer</strong>, overwriting any changes that youmight have made. If this option is not checked, changes that you make in <strong>SQL</strong><strong>Developer</strong> overwrite any changes that might have been made by external applications.Silently Reload When File Is Unmodified: If this option is checked, you are not askedif you want to reload files that have been modified externally but not in <strong>SQL</strong><strong>Developer</strong>. If this option is not checked, you are asked if you want to reload each file1-28 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>SQL</strong> <strong>Developer</strong> Preferencesthat has been modified externally, regardless of whether it has been modified in <strong>SQL</strong><strong>Developer</strong>,Environment: Dockable WindowsThe Dockable Windows pane configures the behavior of dockable windows and theshapes of the four docking areas of <strong>SQL</strong> <strong>Developer</strong>: top, bottom, left, and right.Dockable Windows Always on Top: If this option is checked, dockable windowsalways remain visible in front of other windows.Windows Layout: Click the corner arrows to lengthen or shorten the shape of eachdocking area.Environment: Local HistoryThe Local History pane controls whether information about editing operations on filesopened within <strong>SQL</strong> <strong>Developer</strong> is kept. If local history is enabled, you can specify howlong information is retained and the maximum number of revisions for each file.Environment: LogThe Log pane configures the colors of certain types of log messages and the saving oflog messages to log files.Save Logs to File: If this option is checked, all output to the Messages - Log window issaved to log files, where the file name reflects the operation and a timestamp. You arealso asked to specify a Log Directory; and if the specified directory does not alreadyexist, it is created. Note that is you save log information to files, the number of thesefiles can become large.Maximum Log Lines: The maximum number of lines to store in each log file.Related Topics<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.2 AcceleratorsThe Accelerators pane enables you to customize the accelerator key mappings for <strong>SQL</strong><strong>Developer</strong>.Category: Select All or a specific category, to control which actions are displayed.Actions: The actions for the selected category. When you select an action, any existingaccelerator key mappings are displayed.Accelerators: Any existing key mappings for the selected action. To remove an existingkey mapping, select it and click Remove.New Accelerator: The new accelerator key to be associated with the action. Press andhold the desired modifier key, then press the other key. For example, to associateCtrl+J with an action, press and hold the Ctrl key, then press the j key. If any actionsare currently associated with that accelerator key, they are listed in the CurrentAssignment field.Load Preset: Enables you to load a set of predefined key mappings for certain systemsand external editing applications. If you load any preset key mappings that conflictwith changes that you have made, your changes are overwritten.Related Topics<strong>SQL</strong> <strong>Developer</strong> Preferences<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-29
<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.3 Code EditorThe Code Editor pane contains general options that affect the appearance andbehavior of <strong>SQL</strong> <strong>Developer</strong> when you edit functions, procedures, and packages.Code Editor: BookmarksThe Bookmarks pane contains options that determine the persistence and searchbehavior for bookmarks that you create when using the code editor.Code Editor: Caret BehaviorThe Caret Behavior pane contains options that determine the shape, color, andblinking characteristics of the caret (cursor) in the code editorCode Editor: Code InsightThe Code Insight pane contains options for the logical completion (autocompleteoptions) of keywords and names while you are coding.Code Editor: Code Insight: CompletionThe Code Insight: Completion pane contains options for refining the behavior whenmatching items are found.Code Editor: DisplayThe Display pane contains general options for the appearance and behavior of thecode editor.Text Anti-Aliasing allows smooth-edged characters where possible.Code Folding Margin allows program blocks in procedures and functions to beexpanded and collapsed in the display.Visible Right Margin renders a right margin that you can set to control the length oflines of code.Automatic Brace Matching controls the highlighting of opening parentheses andbrackets and of blocks when a closing parenthesis or bracket is typed.Code Editor: Find OptionsThe Find Options pane determines which options are used by default at <strong>SQL</strong><strong>Developer</strong> startup for find or find and replace operations. You can choose whether touse the options in effect from the last <strong>SQL</strong> <strong>Developer</strong> session or to use specifiedoptions.Code Editor: FontsThe Fonts pane specifies text font options for the code editor.Display Only Fixed-Width Fonts: If this option is checked, the display of availablefont names is restricted to fonts where all characters have the same width.(Fixed-width fonts are contrasted with proportional-width fonts.)Code Editor: Line GutterThe Line Gutter pane specifies options for the line gutter (left margin of the codeeditor).Show Line Numbers: If this option is checked, lines are numbered.1-30 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>SQL</strong> <strong>Developer</strong> PreferencesEnable Line Selection by Click-Dragging: If this option is checked, you can selectconsecutive lines in the editor by clicking in the gutter and dragging the cursorwithout releasing the mouse button.Code Editor: PrintingThe Printing pane specifies options for printing the contents of the code editor. ThePreview pane sample display changes as you select and deselect options.Code Editor: Printing HTMLThe Printing HTML pane specifies options for printing HTML files from the codeeditor.Code Editor: Syntax ColorsThe Syntax Colors pane specifies colors for different kinds of syntax elements.Code Editor: Undo BehaviorThe Undo Behavior pane specifies options for the behavior of undo operations(Ctrl+Z, or Edit, then Undo). Only consecutive edits of the same type are considered; forexample, inserting characters and deleting characters are two different types ofoperation.Allow Navigation-Only Changes to be Undoable: If this option is checked,navigation actions with the keyboard or mouse can be undone. If this option is notchecked, navigation actions cannot be undone, and only actual changes to the text canbe undone.Related Topics<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.4 Database ConnectionsThe Database Connections pane sets connection properties.Save Passwords: If this option is checked, passwords are included in encrypted formwhen database connections are saved or exported to an XML file. If this option is notchecked, passwords are not included, and users will need to enter a passwordwhenever they try to open any of the associated connections.Autocommit in <strong>SQL</strong> Worksheet: If this option is checked, a commit operation isautomatically performed after each INSERT, UPDATE, or DELETE statement executedusing the <strong>SQL</strong> Worksheet. If this option is not checked, a commit operation is notperformed until you execute a COMMIT statement.Validate date and time default values: If this option is checked, date and timevalidation is used when you open tables.<strong>SQL</strong>*Plus Executable: The Windows path or Linux xterm command for the <strong>SQL</strong>*Plusexecutable. If there is no $ORACLE_HOME on your system, there is no <strong>SQL</strong>*Plusexecutable, and you cannot use <strong>SQL</strong>*Plus with <strong>SQL</strong> <strong>Developer</strong>; however, you can stilluse many <strong>SQL</strong>*Plus commands in the <strong>SQL</strong> Worksheet (see Using the <strong>SQL</strong> Worksheet,and especially <strong>SQL</strong>*Plus Statements Supported and Not Supported in <strong>SQL</strong>Worksheet).Related TopicsUsing <strong>SQL</strong>*Plus<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-31
<strong>SQL</strong> <strong>Developer</strong> Preferences<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.5 DebuggerThe Debugger pane contains general options for the <strong>SQL</strong> <strong>Developer</strong> debugger. Otherpanes contain additional specific kinds of debugger options.Debugger: BreakpointsThe Breakpoints pane sets the columns to appear in the Breakpoints pane and thescope of each breakpoint.Debugger: Breakpoints: Default ActionsThe Breakpoints: Default Actions pane sets defaults for actions to occur at breakpoints.These actions are the same as on the Actions tab in the Create/Edit Breakpoint dialogbox.Debugger: DataThe Data pane enables you to control the columns to appear in the debugger Datapane and aspects of how the data is displayed.Debugger: InspectorThe Inspector pane enables you to control the columns to appear in the debuggerInspector pane and aspects of how the data is displayed.Debugger: Smart DataThe Smart Data pane enables you to control the columns to appear in the debuggerSmart Data pane and aspects of how the data is displayed.Debugger: StackThe Stack pane enables you to control the columns to appear in the debugger Stackpane and other options.Debugger: WatchesThe Watches pane enables you to control the columns to appear in the debuggerWatches pane and aspects of how the data is displayed.Related Topics<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.6 DocumentationThe Documentation pane provides options for the display of <strong>SQL</strong> <strong>Developer</strong> onlinehelp.Display in Window: If this option is checked, help is displayed in a separate window.If this option is not checked, help is displayed in a pane in the <strong>SQL</strong> <strong>Developer</strong> UserInterface.Show Tabs: Controls which tabs appear in the Help Center pane (Table of Contents,Index, Full Text Search).Related TopicsUsing the Help1-32 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>SQL</strong> <strong>Developer</strong> Preferences<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.7 ExtensionsThe Extensions pane determines which extensions <strong>SQL</strong> <strong>Developer</strong> uses what it starts.If you change any settings, you must exit <strong>SQL</strong> <strong>Developer</strong> and restart it for the newsetting to take effect.Extensions to Use: Controls the specific extensions to use at startup.Check for Updates: Checks for any updates to the selected extensions.Automatically Check for Updates: If this option is checked, <strong>SQL</strong> <strong>Developer</strong>automatically checks for any updates to the selected extensions at startup.Related Topics<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.8 File TypesThe File Types pane determines which file types and extensions will be opened bydefault by <strong>SQL</strong> <strong>Developer</strong>. The display shows each file extension, the associated filetype, and a check mark if files with that extension are to be opened by <strong>SQL</strong> <strong>Developer</strong>be default, such as when a user double-clicks the file name.Details area at bottom: You can modify the file type, content type (text or binary), andwhether to open files of this extension automatically by <strong>SQL</strong> <strong>Developer</strong>.To have files of a specific extension be opened by default by <strong>SQL</strong> <strong>Developer</strong>, click thefile extension in the list, then check Open with <strong>SQL</strong> <strong>Developer</strong> in the Details area. Thisoverrides any previous application association that may have been in effect for that fileextension.To add a file extension, click Add and specify the file extension (including the period).After adding the extension, you can modify its associated information by selecting itand using the Details area.Related TopicsConfigure File Type Associations (dialog box)<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.9 Global Ignore ListThe Global Ignore List pane identifies files and file types that <strong>SQL</strong> <strong>Developer</strong> will notuse in any processing.New Filter: Enter a file name (for example, abc.txt) or a wildcard (*) and file type (forexample, *.txt) to identify a specific file or all files of a specified type to be ignored;then click Add to add it to the list.To remove an item from the list, select it and click Remove.To restore the default global ignore list, click Restore Defaults.Related Topics<strong>SQL</strong> <strong>Developer</strong> Preferences<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-33
<strong>SQL</strong> <strong>Developer</strong> User Information: Location1.10.10 PL/<strong>SQL</strong> CompilerThe PL/<strong>SQL</strong> Compiler pane controls the display of informational, severe, andperformance-related messages. (The ALL field overrides any individual specificationsfor the other fields.) For each field, you can specify any of the following:■■■■No entry (blank): Use any value specified for ALL; and if none is specified, use the<strong>Oracle</strong> default.Enable: Enable the display of all messages of this category.Disable: Disable the display of all messages of this category.Error: Enable the display of only error messages of this category.Related TopicsUsing the <strong>SQL</strong> Worksheet<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.11 ProxyThe Proxy pane controls whether of not to use n HTTP proxy server. If you enable theuse of an HTTP proxy server, you must specify the host name and port number, andany exception strings for addresses not to be accessed through the proxy server.If the proxy server requires authentication, specify the user name and password.Related Topics<strong>SQL</strong> <strong>Developer</strong> Preferences1.10.12 <strong>SQL</strong> FormatterThe <strong>SQL</strong> Formatter pane controls how statements in the <strong>SQL</strong> Worksheet are formattedwhen you click Format <strong>SQL</strong>. The options include whether to insert space characters ortab characters when you press the Tab key (and how many characters), uppercase orlowercase for keywords and identifiers, whether to preserve or eliminate empty lines,and whether comparable items should be placed or the same line (if there is room) oron separate lines.Related TopicsUsing the <strong>SQL</strong> Worksheet<strong>SQL</strong> <strong>Developer</strong> Preferences1.11 <strong>SQL</strong> <strong>Developer</strong> User Information: Location<strong>SQL</strong> <strong>Developer</strong> stores certain user-specific information, which may includeinformation about any database connections and user-defined reports that you create,as well as your <strong>SQL</strong> <strong>Developer</strong> preferences. This information is stored by defaultunder the following directory:■On Windows systems: \sqldeveloper\jdev\system■ On Linux and Mac OS X systems: ~/.sqldeveloperHowever, you can change this location by doing either of the following:1-34 <strong>SQL</strong> <strong>Developer</strong> Online Help
Supplementary <strong>Oracle</strong> Database Information■■Set the <strong>SQL</strong>DEVELOPER_USER_DIR environment variable to specify anotherdirectory path.Edit the /sqldeveloper/jdev/bin/sqldeveloper.conf file andsubstitute the desired directory path for <strong>SQL</strong>DEVELOPER_USER_DIR in thefollowing line:SetUserHomeVariable <strong>SQL</strong>DEVELOPER_USER_DIRIf you want to prevent other users from accessing your user-specific <strong>SQL</strong> <strong>Developer</strong>information, you must ensure that the appropriate permissions are set on the directorywhere that information is stored or on a directory above it in the path hierarchy. Forexample, on a Windows system you may want to ensure that the sqldeveloperfolder is not shareable, and on a Linux or Mac OS X system you may want to ensurethat the ~/.sqldeveloper directory is not world-readable.1.12 Using the Help<strong>SQL</strong> <strong>Developer</strong> provides a Help menu and context-sensitive help (click the Helpbutton or press the F1 key in certain contexts).By default, help from the Help menu is displayed on the right side of the window,with the Help Center area on the far right and containing tabs at the bottom. You canuse the Contents, Index, and Search (full-text) tabs or their corresponding Help menuitems. Context-sensitive help is displayed in a separate help window. (To change thedefault help behavior, set <strong>SQL</strong> <strong>Developer</strong> Documentation preferences.)For help displayed in the <strong>SQL</strong> <strong>Developer</strong> window, you can close individual HelpContent windows by clicking the X next to their tab names (just as with tabs for tablesand other database objects).To print a group of related topics, right-click the associated book icon in the Helpcontents hierarchy and select Print Topic Subtree. For example, to print allintroductory topics, right-click the book icon for <strong>SQL</strong> <strong>Developer</strong> Introduction andselect Print Topic Subtree.To print a single topic, display it in the Help Content area and click the Print icon, orright-click its page icon in the Help contents hierarchy and select Print Topic Subtree.The best way to become familiar with the help, and with <strong>SQL</strong> <strong>Developer</strong> itself, issimply to experiment with the Help menu options and the Help button in some dialogboxes.Related Topics<strong>SQL</strong> <strong>Developer</strong> User Interface<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage1.13 Supplementary <strong>Oracle</strong> Database InformationIn addition to information about <strong>SQL</strong> <strong>Developer</strong>, this online help includes conceptualand usage information adapted from some <strong>Oracle</strong> Database manuals. This informationappears in and under the following major topics, which are top-level books in the helpTable of Contents:■■■Database Objects: Usage InformationData Types: Usage Information<strong>SQL</strong>: Usage Information<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage 1-35
Supplementary <strong>Oracle</strong> Database Information■■■■■PL/<strong>SQL</strong>: Usage InformationSubprograms and Packages: Usage InformationTriggers: Usage Information<strong>SQL</strong>*Plus: Usage InformationWorking in a Global EnvironmentHowever, this supplementary information sometimes covers only basic informationand features. For conceptual, usage, and reference information about the full set of<strong>Oracle</strong> Database features and options, see the <strong>Oracle</strong> Documentation Library for yourinstallation of <strong>Oracle</strong> Database.1-36 <strong>SQL</strong> <strong>Developer</strong> Online Help
2Tutorial: Creating Objects for a SmallDatabaseIn this tutorial, you will use <strong>SQL</strong> <strong>Developer</strong> to create objects for a simplified librarydatabase, which will include tables for books, patrons (people who have library cards),and transactions (checking a book out, returning a book, and so on).The tables are deliberately oversimplified for this tutorial. They would not be adequatefor any actual public or organizational library. For example, this library contains onlybooks (not magazines, journals, or other document formats), and it can contain nomore than one copy of any book.You will perform the following major steps:Creating a Table (Books)Creating a Table (Patrons)Creating a Table (Transactions)Creating a SequenceCreating a ViewCreating a PL/<strong>SQL</strong> ProcedureDebugging a PL/<strong>SQL</strong> Procedure (optional)Using the <strong>SQL</strong> Worksheet for Queries (optional)Related TopicsScript for Creating and Using the Library Tutorial Objects<strong>SQL</strong> <strong>Developer</strong> Concepts and Usage<strong>SQL</strong> <strong>Developer</strong> User InterfaceDatabase Objects2.1 Creating a Table (Books)Tip: To print this tutorial, right-click its book icon in the HelpContents display and select Print Topic Subtree.The Books table contains a row for each book in the library. It includes columns ofcharacter and number types, a primary key, a unique constraint, and a checkconstraint. You will use the Create Table dialog box to create the table declaratively;Tutorial: Creating Objects for a Small Database 2-1
Creating a Table (Books)the table that you create will be essentially the same as if you had entered thefollowing statement using the <strong>SQL</strong> Worksheet:CREATE TABLE books (book_id VARCHAR2(20) PRIMARY KEY,title VARCHAR2(50)CONSTRAINT title_not_null NOT NULL,author_last_name VARCHAR2(30)CONSTRAINT last_name_not_null NOT NULL,author_first_name VARCHAR2(30),rating NUMBER,CONSTRAINT rating_1_to_10 CHECK (rating IS NULL OR(rating >= 1 and rating
Creating a Table (Patrons)In Available Columns, double-click TITLE and then AUTHOR_LAST_NAME to movethem to Selected Columns.Check Constraints tabClick Add to add a check constraint for the table, namely, that the rating column valueis optional (it can be null), but if a value is specified, it must be a number from 1through 10. You must enter the condition using <strong>SQL</strong> syntax that is valid in a CHECKclause (but do not include the CHECK keyword or enclosing parentheses for the entireCHECK clause text).Name: rating_1_to_10Condition: rating is null or (rating >= 1 and rating
Creating a Table (Transactions)Column Name Type Size Other Information and Notespatron_id NUMBER Primary Key. (Unique patron ID number, withvalues to be created using a sequence that youwill create)last_name VARCHAR2 30 Not Nullfirst_name VARCHAR2 30street_address VARCHAR2 30city_state_zip VARCHAR2 30The last column in the table (location) requires a complex data type, for which youmust use the Columns tab with advanced options. Check Show Advanced Options(next to Schema). This displays additional tabs for more table options.On the Columns tab, click the city_state_zip column name, and click the Add Column(+) icon to add the following as the last column in the table.Column Name Type Other Information and NoteslocationComplex typeSchema: MDSYSType: SDO_GEOMETRY(<strong>Oracle</strong> Spatial geometry object representing thepatron’s geocoded address)After you have entered the last column (location), click OK to finish creating the table.Go to Creating a Table (Transactions) to create the next table.Related TopicsTutorial: Creating Objects for a Small Database<strong>SQL</strong> <strong>Developer</strong> User Interface2.3 Creating a Table (Transactions)The Transactions table contains a row for each transaction involving a patron and abook (for example, someone checking a book out or returning a book). It includes twoforeign key columns. You will use the Create Table dialog box to create the tabledeclaratively; the table that you create will be essentially the same as if you hadentered the following statement using the <strong>SQL</strong> Worksheet:CREATE TABLE Transactions (transaction_id NUMBER PRIMARY KEY,patron_id CONSTRAINT for_key_patron_idREFERENCES patrons(patron_id),book_id CONSTRAINT for_key_book_idREFERENCES books(book_id),transaction_date DATE,transaction_type NUMBER);To create the Transactions table, if you are not already connected, connect to thedatabase as the user for the schema you are using for this tutorial. Right-click theTables node in the schema hierarchy on the left side, select Create Table, and enter thefollowing information. (If a tab or field is not mentioned, do not enter anything for it.)Schema: Specify your current schema as the schema in which to create the table.2-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
Creating a Table (Transactions)Name: TransactionsCreate the table columns using the following information. After creating each columnexcept the last one (transaction_type), click Add Column to add the next column. (Ifyou accidentally click OK instead of Add Column, right-click the TRANSACTIONStable in the Connections navigator display, select Edit, and continue to add columns.)Column Name Type Size Other Information and Notestransaction_id NUMBER Primary Key. (Unique transaction ID number,with values to be created using a trigger andsequence that will be created automatically)patron_id NUMBER (Foreign key; must match a patron_id value inthe Patrons table)book_id VARCHAR2 20 (Foreign key; must match a book_id value inthe Books table)transaction_date DATE (Date and time of the transaction)transaction_type NUMBER (Numeric code indicating the type oftransaction, such as 1 for checking out a book)After you have entered the last column (transaction_type), check Show AdvancedOptions (next to Schema). This displays additional tabs for more table options. Forthis table, you will use the Primary Key and Foreign Keys tabs.Primary Key tabBecause you have already specified the column for the primary key, you will use thistab only to specify that the primary key column values are to be populatedautomatically. This convenient approach uses a trigger and a sequence (both createdautomatically by <strong>SQL</strong> <strong>Developer</strong>), and ensures that each transaction ID value isunique.Populate Primary Key Column: TRANSACTION_IDFrom: (Accept the defaults.)Trigger Name: (Either accept the default or enter a name for the before-insert triggerthat will be created automatically.)Foreign Keys tab1. Click Add to create the first of the two foreign keys for the Transactions table.Name: for_key_patron_idReferenced Schema: Name of the schema containing the table with the primary key orunique constraint to which this foreign key refers. Use the schema you have beenusing for this tutorial.Referenced Table: PATRONSReferenced Constraint: Name (generated by <strong>Oracle</strong>) of the primary key constraint forthe Patrons table. (Might be a name with a format like PATRONS_PK.) Be sure that theReferenced Column on PATRONS displayed value is PATRON_ID after you select theReferenced Constraint.Associations: Local Column: PATRON_IDAssociations: Referenced Column on PATRONS: PATRON_ID2. Click Add to create the second of the two foreign keys for the Transactions table.Tutorial: Creating Objects for a Small Database 2-5
Creating a SequenceName: for_key_book_idReferenced Schema: Name of the schema containing the table with the primary key orunique constraint to which this foreign key refers. Use the schema you have beenusing for this tutorial.Referenced Table: BOOKSReferenced Constraint: Name (generated by <strong>Oracle</strong>) of the primary key constraint forthe Books table. (Might be a name with a format like BOOKS_PK.) Be sure that theReferenced Column on BOOKS displayed value is BOOK_ID after you select theReferenced Constraint.Associations: Local Column: BOOK_IDAssociations: Referenced Column on BOOKS: BOOK_ID3. Click OK to finish creating the table.You have finished creating all the tables. To create a sequence for use in generatingunique primary key values for the Patrons table, go to Creating a Sequence.Related TopicsTutorial: Creating Objects for a Small Database<strong>SQL</strong> <strong>Developer</strong> User Interface2.4 Creating a SequenceCreate one sequence object, which will be used in INSERT statements to generateunique primary key values in the Patrons table. (You do not need to create a sequencefor the primary key in the Transactions table, because you used the <strong>SQL</strong> <strong>Developer</strong>feature that enables automatic population of primary key values for that table.) Youwill use the Create Sequence dialog box to create the sequence declaratively; thesequence that you create will be essentially the same as if you had entered thefollowing statements using the <strong>SQL</strong> Worksheet:CREATE SEQUENCE patron_id_seqSTART WITH 100INCREMENT BY 1;After creating the sequence, you can use it in INSERT statements to generate uniquenumeric values. The following example uses the patron_id_seq sequence in creating arow for a new patron (library user), assigning her a patron ID that is the next availablevalue of the patrons_id_seq sequence:INSERT INTO patrons VALUES (patron_id_seq.nextval,'Smith', 'Jane', '123 Main Street', 'Mytown, MA 01234', null);To create the sequence, if you are not already connected, connect to the database as theuser for the schema you are using for this tutorial. Right-click the Sequences node inthe schema hierarchy on the left side, select Create Sequence, and enter informationusing the Create Sequence dialog box.Schema: Specify your current schema as the schema in which to create the sequence.Name: patron_id_seqIncrement: 1Start with: 1002-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
Creating a View2.5 Creating a ViewClick OK to finish creating the sequence.To create a view, go to Creating a View.Related TopicsTutorial: Creating Objects for a Small Database<strong>SQL</strong> <strong>Developer</strong> User InterfaceCreate a view that returns information about patrons and their transactions. This viewqueries the Patrons and Transactions tables, and returns rows that contain a patron’sID, last name, and first name, along with a transaction and the transaction type. Therows are ordered by patron ID, and by transaction type within patron IDs.To create the patrons_trans_view view, if you are not already connected, connect to thedatabase as the user for the schema you are using for this tutorial. Right-click theViews node in the schema hierarchy on the left side, select Create View, and enter thefollowing information. (If a tab or field is not mentioned, do not enter anything for it.)Schema: Specify your current schema as the schema in which to create the view.Name: patrons_trans_viewEntire <strong>SQL</strong> Query tabIn the Entire <strong>SQL</strong> Query box, enter (or copy and paste) the following statement:SELECT p.patron_id, p.last_name, p.first_name,t.transaction_type, t.transaction_dateFROM patrons p, transactions tWHERE p.patron_id = t.patron_idORDER BY p.patron_id, t.transaction_typeThen click Test Syntax, and ensure that you have not made any syntax errors. If youmade any errors, correct then and click Test Syntax again.DDLReview the <strong>SQL</strong> statement that <strong>SQL</strong> <strong>Developer</strong> will use to create the view. If you wantto make any changes, go back to the Entire <strong>SQL</strong> Query tab and make the changesthere.If you want to save the CREATE VIEW statement to a <strong>SQL</strong> script file, click Save andspecify the location and file name.When you are finished, click OK.You have finished creating the view. To see the data returned by the view, in theConnections navigator, expand Views, select PATRONS_TRANS_VIEW, and click theData tab.Related TopicsTutorial: Creating Objects for a Small Database<strong>SQL</strong> <strong>Developer</strong> User InterfaceTutorial: Creating Objects for a Small Database 2-7
Creating a PL/<strong>SQL</strong> Procedure2.6 Creating a PL/<strong>SQL</strong> ProcedureCreate a procedure that lists all books with a specified rating. You can then call thatprocedure with an input parameter (a number from 1 to 10), and the output will be allthe titles of all books with that rating.To create the procedure, if you are not already connected, connect to the database asthe user for the schema you are using for this tutorial. Right-click the Procedures nodein the schema hierarchy on the left side, select Create Procedure, and enter thefollowing information using the Create PL/<strong>SQL</strong> Procedure dialog box.Object Name: list_a_ratingClick OK. A Source window for the new procedure is opened. Enter (or copy andpaste) the following procedure text:PROCEDURE list_a_rating(in_rating IN NUMBER) ASmatching_title VARCHAR2(50);TYPE my_cursor IS REF CURSOR;the_cursor my_cursor;BEGINOPEN the_cursor FOR 'SELECT title FROM books WHERErating = :in_rating' USING in_rating;DBMS_OUTPUT.PUT_LINE('All books with a rating of ' || in_rating || ':');LOOPFETCH the_cursor INTO matching_title;EXIT WHEN the_cursor%NOTFOUND;DBMS_OUTPUT.PUT_LINE(matching_title);END LOOP;CLOSE the_cursor;END;This procedure uses a cursor (named the_cursor) to return only rows where the bookhas the specified rating (in_rating parameter), and uses a loop to output the title ofeach book with that rating.Click the Save icon to save the procedure.As a usage example, after creating the procedure named list_a_rating, you could usethe following statement to return all books with a rating of 10:CALL list_a_rating(10);To run this procedure within Database Designer, right-click LIST_A_RATING in theConnections navigator hierarchy display and select Run. In the Run PL/<strong>SQL</strong> dialogbox, change IN_RATING => IN_RATING to IN_RATING => 10, and click OK. TheLog window display will now include the following output:All books with a rating of 10:Moby DickSoftware WizardryRelated TopicsTutorial: Creating Objects for a Small DatabaseScript for Creating and Using the Library Tutorial Objects<strong>SQL</strong> <strong>Developer</strong> User Interface2-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
Debugging a PL/<strong>SQL</strong> Procedure2.7 Debugging a PL/<strong>SQL</strong> ProcedureIf you want to practice debugging a PL/<strong>SQL</strong> procedure with <strong>SQL</strong> <strong>Developer</strong>, create aprocedure that is like the list_a_rating procedure that you created in Creating aPL/<strong>SQL</strong> Procedure, but with a logic error. (The coding is also deliberately inefficient,to allow the display of the rating in a variable.)To create this procedure, if you are not already connected, connect to the database asthe user for the schema you are using for this tutorial. Right-click the Procedures nodein the schema hierarchy on the left side, select Create New PL/<strong>SQL</strong> Procedure, andenter the following information using the Create PL/<strong>SQL</strong> Procedure dialog box.Object Name: list_a_rating2Click OK. A Source window for the new procedure is opened. Enter (or copy andpaste) the following procedure text:PROCEDURE list_a_rating2(in_rating IN NUMBER) ASmatching_title VARCHAR2(50);matching_rating NUMBER;TYPE my_cursor IS REF CURSOR;the_cursor my_cursor;rating_cursor my_cursor;BEGINOPEN the_cursor FOR 'SELECT title FROM books WHERErating
Using the <strong>SQL</strong> Worksheet for Queriesmargin toggles the setting and unsetting of breakpoints.) This will enable you tosee the values of the matching_title and matching_rating variables as executionproceeds in debug mode.4. Right-click LIST_A_RATING2 in the Connections navigator hierarchy display andselect Debug. Ensure that the line IN_RATING => IN_RATING has been changedto IN_RATING => 10, and click OK.5. In the debugging toolbar, click the Resume icon to have execution proceed,stopping at the next breakpoint; note the display in the Smart Data tab in thelower right part of the window. Repeatedly click the Resume icon, noticingespecially the value of the rating variable as each row is processed. You will noticethe first incorrect result when you see that the title Get Rich Really Fast is included,even though its rating is only 1 (obviously less than 10). (See the screen illustrationwith debugging information in Running and Debugging Functions andProcedures.)6. When you have enough information to fix the problem, you can click theTerminate icon in the debugging toolbar.From this debugging session, you know that to fix the logic error, you should changerating
Script for Creating and Using the Library Tutorial ObjectsClick the Execute <strong>SQL</strong> Statement icon in the <strong>SQL</strong> Worksheet toolbar, and view theresults of the query.Click the Execute Explain Plan icon in the <strong>SQL</strong> Worksheet toolbar to see the executionplan (displayed on the Explain tab) that <strong>Oracle</strong> Database follows to execute the <strong>SQL</strong>statement. The information includes the optimizer strategy and the cost of executingthe statement. (For information about how to generate and interpret execution plans,see <strong>Oracle</strong> Database Performance Tuning Guide.)Related TopicsTutorial: Creating Objects for a Small DatabaseUsing the <strong>SQL</strong> Worksheet2.9 Script for Creating and Using the Library Tutorial ObjectsThe following statements create and use the database objects that you have created (orwill create) in Tutorial: Creating Objects for a Small Database. You can view thesecommands to help you understand the library database objects that are covered in thetutorial.-- Clean up from any previous runningDROP TABLE transactions;DROP TABLE books;DROP TABLE patrons;DROP SEQUENCE patron_id_seq;DROP SEQUENCE trans_id_seq;DROP VIEW patrons_trans_view;set serveroutput on-- Create objectsCREATE TABLE Books (book_id VARCHAR2(20) PRIMARY KEY,title VARCHAR2(50)CONSTRAINT title_not_null NOT NULL,author_last_name VARCHAR2(30)CONSTRAINT last_name_not_null NOT NULL,author_first_name VARCHAR2(30),rating NUMBER,CONSTRAINT rating_1_to_10 CHECK (rating IS NULL OR(rating >= 1 and rating
Script for Creating and Using the Library Tutorial ObjectsREFERENCES books(book_id),transaction_date DATECONSTRAINT tran_date_not_null NOT NULL,transaction_type NUMBERCONSTRAINT tran_type_not_null NOT NULL);CREATE SEQUENCE patron_id_seqSTART WITH 100INCREMENT BY 1;-- The actual sequence for the transaction_id-- in the tutorial is created automatically,-- and probably has a name in the form MDRS_xxx$.CREATE SEQUENCE trans_id_seqSTART WITH 1INCREMENT BY 1;CREATE OR REPLACE TRIGGER ins_transactionsBEFORE INSERT ON TRANSACTIONSFOR EACH ROWBEGINSELECT trans_id_seq.nextval INTO:new.TRANSACTION_ID FROM dual;END;/CREATE VIEW patrons_trans_view ASSELECT p.patron_id, p.last_name, p.first_name,t.transaction_type, t.transaction_dateFROM patrons p, transactions tWHERE p.patron_id = t.patron_idORDER BY p.patron_id, t.transaction_type;-- Procedure: List all books that have a specified rating.CREATE OR REPLACE PROCEDURE list_a_rating(in_rating IN NUMBER) ASmatching_title VARCHAR2(50);TYPE my_cursor IS REF CURSOR;the_cursor my_cursor;BEGINOPEN the_cursor FOR 'SELECT title FROM books WHERErating = :in_rating' USING in_rating;DBMS_OUTPUT.PUT_LINE('All books with a rating of ' || in_rating || ':');LOOPFETCH the_cursor INTO matching_title;EXIT WHEN the_cursor%NOTFOUND;DBMS_OUTPUT.PUT_LINE(matching_title);END LOOP;CLOSE the_cursor;END;/show errors;-- Insert and query data.INSERT INTO books VALUES ('A1111', 'Moby Dick', 'Melville', 'Herman', 10);INSERT INTO books VALUES ('A2222', 'Get Rich Really Fast', 'Scammer', 'Ima', 1);INSERT INTO books VALUES ('A3333', 'Finding Inner Peace', 'Blissford', 'Serenity',null);INSERT INTO books VALUES ('A4444', 'Great Mystery Stories', 'Whodunit', 'Rodney',5);2-12 <strong>SQL</strong> <strong>Developer</strong> Online Help
Script for Creating and Using the Library Tutorial ObjectsINSERT INTO books VALUES ('A5555', 'Software Wizardry', 'Abugov', 'D.', 10);INSERT INTO patrons VALUES (patron_id_seq.nextval,'Smith', 'Jane', '123 Main Street', 'Mytown, MA 01234', null);INSERT INTO patrons VALUES (patron_id_seq.nextval,'Chen', 'William', '16 S. Maple Road', 'Mytown, MA 01234', null);INSERT INTO patrons VALUES (patron_id_seq.nextval,'Fernandez', 'Maria', '502 Harrison Blvd.', 'Sometown, NH 03078', null);INSERT INTO patrons VALUES (patron_id_seq.nextval,'Murphy', 'Sam', '57 Main Street', 'Mytown, MA 01234', null);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (100, 'A1111', SYSDATE, 1);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (100, 'A2222', SYSDATE, 2);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (101, 'A3333', SYSDATE, 3);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (101, 'A2222', SYSDATE, 1);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (102, 'A3333', SYSDATE, 1);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (103, 'A4444', SYSDATE, 2);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (100, 'A4444', SYSDATE, 1);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (102, 'A2222', SYSDATE, 2);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (102, 'A5555', SYSDATE, 1);INSERT INTO transactions (patron_id, book_id,transaction_date, transaction_type)VALUES (101, 'A2222', SYSDATE, 1);-- Test the view and the procedure.SELECT * FROM patrons_trans_view;CALL list_a_rating(10);Tutorial: Creating Objects for a Small Database 2-13
Script for Creating and Using the Library Tutorial Objects2-14 <strong>SQL</strong> <strong>Developer</strong> Online Help
3Dialog Boxes for Creating/Editing Objects<strong>SQL</strong> <strong>Developer</strong> uses dialog boxes for creating and editing database connections andobjects in the database (tables, views, procedures, and so on). The dialog boxessometimes have multiple tabs, each reflecting a logical grouping of properties for thattype of object.For an explanation of any dialog box or tab, click the Help button or press the F1 key.The dialog boxes are not presented here in any rigorous order, because the help foreach box is an independent piece of information and is normally seen when you clickHelp or press F1 in that box.Note: For all Name fields, any name that you type is automaticallyconverted to and stored in the database metadata in uppercase, unlessyou enclose the name in quotation marks (" "). (Names of databaseobjects in <strong>SQL</strong> and PL/<strong>SQL</strong> statements are not case-sensitive.)To include lowercase characters, special characters, or spaces in objectnames, enclose the name in quotation marks (" ") when you type it.Example: "My table"3.1 Add Extension3.2 Apply FilterRelated TopicsDatabase ObjectsTutorial: Creating Objects for a Small DatabaseThis dialog box is displayed when you click Add in the File Types pane of <strong>SQL</strong><strong>Developer</strong> Preferences.Extension: Specify the file extension, including the period (for example, .xyz).After you click OK, you can select that extension and modify its details, including thefile type, content type, and whether to have files of the extension automatically openedby <strong>SQL</strong> <strong>Developer</strong>.Filter Text: Limits the display of objects available for selection according to a characterstring in the name, with the percent sign (%) as a wildcard character. The search formatching names is not case sensitive. For example, to limit the display of objects tothose whose names start with the string EM, specify the following filter text: EM%Dialog Boxes for Creating/Editing Objects 3-1
Check for UpdatesTo remove the effects of applying a filter, right-click the object type node in theConnections navigator display and select Clear Filter.3.3 Check for Updates3.4 Choose DirectoryWhen you click Help and then Check for Updates, you can check for and downloadavailable <strong>SQL</strong> <strong>Developer</strong> updates. The following pages may be displayed:1. Source: Select the source or sources to be checked for available updates: any or allof some specified online update centers, or a local ZIP file containing an updatebundle.2. Update: If any updates are available from the selected source or sources, selectthose that you want to download.3. Download: If you selected any updates to download, this page displays theprogress of the download operation.This is a standard box for choosing a directory in which to place files: use Location tonavigate to (double-clicking) the folder in which to save the files, or enter a directoryname. If the directory does not already exist, it is created.3.5 Create/Edit New ObjectSpecify the type of object to create. After you click OK, the dialog box for creating thattype of object is displayed.Filter By: Available Items displays the types of objects that you can create in thecurrent database connection; All Items displays all types of objects (some of whichmay not be available for selection).Categories: A hierarchical display of categories of objects.Items: Types of objects that you can create within the selected category.Related TopicsDatabase Objects3.6 Create/Edit/Select Database ConnectionThe database connection dialog box displays any existing connections. Depending onthe context, you can select a connection to connect to the database, edit the informationabout existing connections, or specify information while creating a new connection.(See Creating and Editing Connections.)Connection Name: An alias for a connection to the database using the informationthat you enter. (The connection name is not stored in the database, and the connectionis not a database object.) Suggestion: Include the database name (SID) and user namein the connection name. Example: personnel_herman for connecting to the personneldatabase as user Herman.Username: Name of the database user for the connection. This user must havesufficient privileges to perform the tasks that you want perform while connected to thedatabase, such as creating, editing, and deleting tables, views, and other objects.Password: Password associated with the specified database user.3-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
Select Connection3.7 Select ConnectionRole: The set of privileges to be associated with the connection. For a user that hasbeen granted SYSOPER or SYSDBA system privilege, you can specify a connectionthat includes the privilege.Basic tabHost Name: Host system for the <strong>Oracle</strong> database.Port: Listener port.SID: Database name.Service Name: Network service name of the database (for a remote databaseconnection over a secure connection).TNS tabNetwork Alias: <strong>Oracle</strong> Net alias for the database. (The list for selecting a network aliasis initially filled from the tnsnames.ora file on your system, if that file exists.)Connect Identifier: <strong>Oracle</strong> Net connect identifier.Advanced tabCustom JDBC URL: URL for connecting from Java to the database.Creating and Editing ConnectionsTo create a new connection when no connections exist, enter the connection informationand click Connect. To test the connection before you create it, click Test.To create a new connection when one or more connections already exist, click New, enter theconnection information, and click Connect. To test the connection before you create it,click Test.To edit an existing connection, click in its entry in the Connection Name column, changeany connection information on the left side, and click Connect. To test the connectionbefore you save changes to it, click Test.Related TopicsDatabase Connections<strong>SQL</strong> <strong>Developer</strong> User InterfaceUse this dialog box to select a database connection for use with a specific <strong>SQL</strong><strong>Developer</strong> feature (for example, the <strong>SQL</strong> worksheet or the Reports navigator). Afteryou click OK, the interface for the component is displayed , with the current user thesame as the one specified in the connection.To create a new database connection, click New; to edit the selected databaseconnection, click Edit. In both cases, a dialog box for specifying connectioninformation is displayed (see Create/Edit/Select Database Connection).Related TopicsDatabase ConnectionsDialog Boxes for Creating/Editing Objects 3-3
Select Library3.8 Select LibraryThis dialog box is displayed when you click Browse in the Database Connections panewhen setting <strong>SQL</strong> <strong>Developer</strong> Preferences. Use this box to select the library for thespecified JDBC driver class.Related TopicsDatabase Connections3.9 Create LibraryThis dialog box is displayed when you click New in the Select Library dialog box,which is displayed when you click Browse in the Database Connections pane whensetting <strong>SQL</strong> <strong>Developer</strong> Preferences. Use this box to create the library for the specifiedJDBC driver class.Related TopicsDatabase Connections3.10 Export/Import Connection DescriptorsThe Export Connection Descriptors dialog box exports information about one or moredatabase connections to an XML file. The Import Connection Descriptors dialog boximports connections that have been exported. Connections that you import are addedto any connections that already exist in <strong>SQL</strong> <strong>Developer</strong>.File Name: Name of the XML file to contain exported information or that containsinformation to be imported. Use the Browse button to specify the location.Connections: Names of connections that you can select for the export or importoperation.Related TopicsDatabase Connections3.11 Create/Edit Database LinkThe following information applies to a database link, which is a database object in onedatabase that enables you to access objects on another database, as explained inDatabase Links.Schema: Database schema in which to create the database link.Name: Name of the database link. Must be unique within a schema.Service Name: The service name of a remote database. If you specify only the databasename, <strong>Oracle</strong> Database implicitly appends the database domain to the connect stringto create a complete service name. Therefore, if the database domain of the remotedatabase is different from that of the current database, you must specify the completeservice name.Current User: Creates a current user database link. The current user must be a globaluser with a valid account on the remote database. If the database link is used directly,that is, not from within a stored object, then the current user is the same as theconnected user.3-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
Create/Edit Index3.12 Create/Edit IndexFixed User: Creates a fixed user database link, for which you specify the user nameand password used to connect to the remote database.Public: If this option is checked, the database link is public (available to all users). Ifthis option is not checked, the database link is private and is available only to you.Shared: If this option is checked, a single network connection is used to create a publicdatabase link that can be shared among multiple users. In this case, you must alsospecify the Authentication information.Authentication - User Name and Password: The user name and password on thetarget instance. This information authenticates the user to the remote server and isrequired for security. The specified user and password must be a valid user andpassword on the remote instance.DDL tabYou can review and save the <strong>SQL</strong> statement that <strong>SQL</strong> <strong>Developer</strong> will use to create anew database link or that reflects any changes you have made to the database linkproperties.Related TopicsDatabase Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceDialog Boxes for Creating/Editing ObjectsThe following information applies to an index, which is a database object that containsan entry for each value that appears in the indexed column(s) of the table or clusterand provides direct, fast access to rows, as explained in Indexes.Schema: Database schema that owns the table associated with the index.Table: Name of the table associated with the index.Name: Name of the index. Must be unique within a schema.Index Type: Normal for a standard <strong>Oracle</strong> index, in which case you also specifynon-unique, unique, or bitmap, as well as one or more index expressions; or Text foran <strong>Oracle</strong> Text index (created with INDEXTYPE IS CTXSYS.CONTEXT), in which caseyou specify the column to be indexed.Non-unique means that the index can contain multiple identical values; Uniquemeans that no duplicate values are permitted; Bitmap stores rowids associated with akey value as a bitmap.Index: A list of index expressions, that is, the table columns or column expressions inthe index. To add an index expression, click the Add Column Expression (+) icon; thisadds a column name here and in Column Expression, where you can edit it. To deletean index expression, click the Remove Column Expression (X) icon; to move an indexexpression up or down in the list click the Move Column Up and Move Column Downicons. An index must have at least one index expression.For example, to create an index on the AUTHOR_LAST_NAME column of the Bookstable from the tutorial (see Creating a Table (Books)), click the + icon, and selectAUTHOR_LAST_NAME in Column Name or Expression (next field), which changesBOOKS to AUTHOR_LAST_NAME in the Index field.Dialog Boxes for Creating/Editing Objects 3-5
Create PL/<strong>SQL</strong> Function, Procedure, or PackageColumn Name or Expression: A column name or column expression. A columnexpression is an expression built from columns, constants, <strong>SQL</strong> functions, anduser-defined functions. When you specify a column expression, you create afunction-based index.Order: ASC for an ascending index (index values sorted in ascending order); DESC fora descending index (index values sorted in descending order).Related TopicsDatabase Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceDialog Boxes for Creating/Editing Objects3.13 Create PL/<strong>SQL</strong> Function, Procedure, or PackageSpecify the following information for a PL/<strong>SQL</strong> subprogram (function or procedure)or a package to contain subprograms.Object Name: Name of the object. Must be unique within a schema.Object Type (if you have specified PL/<strong>SQL</strong> Subprogram and not a specific type ofobject): One of the following object types:■■FUNCTION: a function (returns a value)PROCEDURE: a procedure (does not return a value)■ PACKAGE: a package that can contain multiple functions or procedures, or acombination of functions and proceduresThe object is created and is displayed in the Editor window, where you can enter thedetails.For information about PL/<strong>SQL</strong> subprograms, see Subprograms and Packages: UsageInformation.Related TopicsDatabase Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceDialog Boxes for Creating/Editing Objects3.14 Create/Edit SequenceThe following information applies to a sequence, which is an object from whichmultiple users may generate unique integers. You can use sequences to automaticallygenerate primary key values.Schema: Database schema in which to create the sequence.Name: Name of the sequence. Must be unique within a schema.Increment: Interval between successive numbers in a sequence.Start with: Starting value of the sequence.Min value: Lowest possible value for the sequence. The default is 1 for an ascendingsequence and -(10^26) for a descending sequence.3-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
Create/Edit SynonymMax value: Highest possible value for the sequence. The default is 10^27 for anascending sequence and -1 for a descending sequence.Cycle: Indicates whether the sequence "wraps around" to reuse numbers after reachingits maximum value (for an ascending sequence) or its minimum value (for adescending sequence). If cycling of values is not enabled, the sequence cannot generatemore values after reaching its maximum or minimum value.Cache and Cache size: If Cache is checked, sequence values are preallocated in cache,which can improve application performance; Cache size indicates the number ofsequence values preallocated in cache. If Cache is not checked, sequence values are notpreallocated in cache.Order: Indicates whether sequence numbers are generated in the order in which theyare requested. If no ordering is specified, sequence numbers are not guaranteed to bein the order in which they were requested.DDL tabYou can review the <strong>SQL</strong> statement that <strong>SQL</strong> <strong>Developer</strong> will use to create a newsequence or that reflects any changes you have made to the sequence properties.For information about sequences, see Managing Sequences.Related TopicsDatabase Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceDialog Boxes for Creating/Editing Objects3.15 Create/Edit SynonymThe following information applies to a synonym, which is an alternative name for atable, view, sequence, procedure, stored function, package, materialized view, Javaclass database object, user-defined object type, or another synonym.Public: If this option is checked, the synonym is accessible to all users. (However eachuser must have appropriate privileges on the underlying object in order to use thesynonym.) If this option is not checked, the synonym is a private synonym, and isaccessible only within its schema.Schema: Database schema in which to create the synonym.Name: Name of the synonym. A private synonym must be unique within its schema; apublic synonym must be unique within the database.For - Referenced Schema: Schema containing the object or name to which thissynonym refers.Object Based: Specify the object to which this synonym refers.Name Based: Enter the name of the object to which this synonym refers.DDL tabYou can review the <strong>SQL</strong> statement that <strong>SQL</strong> <strong>Developer</strong> will use to create a newsynonym or that reflects any changes you have made to the synonym properties.For information about synonyms, see Managing Synonyms.Dialog Boxes for Creating/Editing Objects 3-7
Create Table (quick creation)Related TopicsDatabase Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceDialog Boxes for Creating/Editing Objects3.16 Create Table (quick creation)This dialog box (if you do not check Show Advanced Options) creates a new tablequickly by specifying columns and some frequently used features. (If you need to addor change features after you create the table, you can edit the table by clicking theModify icon while viewing the table or by right-clicking its name in the Connectionsnavigator and selecting Properties, which displays the Create/Edit Table (withadvanced options) dialog box.)To create a new table, the only things you must do are specify the schema and the tablename, add the necessary columns, and click OK. Although it is not required, youshould also specify a primary key.Show Advanced Options: If this option is checked, the dialog box changes to one withmultiple tabs, in which you can specify an extended set of features while creating thetable. For example, you must check this option if you want to create a partitionedtable, an index-organized table, or an external table.Schema: Database schema in which to create the table.Name: Name of the table. Must be unique within a schema.Columns tab (quick creation)Specifies properties for each column in the table.Columns: Lists the columns currently in the table.Note: To add a column after the currently selected column, click AddColumn; to delete a column, select it and click Remove Column.Column Name: Name of the column. Must be unique within the table. Suggestion: Fora new column, replace any default name, such as COLUMN1.Type: Data type for the column. The drop-down list includes only selected frequentlyused data types. To specify any other type for the column, you must use the Columnstab of the Create/Edit Table (with advanced options) dialog box.Size: For VARCHAR2 data, the maximum size of the column data; for NUMBER data,the maximum number of digits.Not Null: If this option is checked, the column must contain data; you cannot specifyno value or an explicit null value for this column when you insert a row. If this optionis not checked, the column can contain either data or no data.Primary Key: If this option is checked, the column is the primary key, or part of theprimary key, for the table. The primary key is the column, or set of columns, thatuniquely identifies each row in the table. A primary key column cannot be null.If you want to have the primary key values automatically populated by a convenientmethod that uses a before-insert trigger and a sequence, then before you finishcreating the table, you must check Show Advanced Options and use the Primary Keytab, starting with the Populate Primary Key Column field.3-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
Create/Edit Table (with advanced options)To add another column, click Add Column. When you are finished adding columns,either click OK or click the DDL tab to review the CREATE TABLE statement.DDL tab (quick creation)You can review and save the CREATE TABLE statement that <strong>SQL</strong> <strong>Developer</strong> will useto create a new table or that reflects any changes you have made to the tableproperties. If you want to make any changes, go back to the Columns tab and makethe changes there.When you are finished, click OK.Related TopicsCreate/Edit Table (with advanced options) (dialog box including advanced features)Database Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceTutorial: Creating Objects for a Small Database3.17 Create/Edit Table (with advanced options)The table dialog box is used for creating a new table or editing an existing table. Thetable properties are grouped under several tabs.To create a new table, the only things you must do are specify the schema and the tablename, add the necessary columns, and click OK. Although it is not required, youshould also specify a primary key using the Primary Key tab. For other table-relatedfeatures, use the appropriate tabs; the order in which you visit tabs usually does notmatter, although you might find it convenient to visit them in the sequence in thistopic. If you are editing an existing table, you can visit the tabs in any order.If you click OK before you are finished creating or editing the table, right-click thetable name in the Connections navigator, select Edit, and continue creating or editingthe table.Schema: Database schema in which to create the table.Name: Name of the table. Must be unique within a schema.Type: The type of table:■■■■Normal: A regular database table. It can be partitioned (see Partitioning tab,Subpartition Templates tab, and Partition Definitions tab).External: An external table (see External Table Properties tab).Index Organized: An index-organized table (see Index Organized Properties tab).Temporary: A temporary table, which is not stored permanently in the database.The temporary table definition persists in the same way as the definition of aregular table, but the table segment and any data in the temporary table persistonly for the duration of either the transaction (Transaction option) or the session(Session option).Columns tabSpecifies properties for each column in the table.Columns: Lists the columns currently in the table. To add a column, click the AddColumn (+) icon; to delete a column, select it and click the Remove Column (X) icon; toDialog Boxes for Creating/Editing Objects 3-9
Create/Edit Table (with advanced options)move a column up or down in the table definition, select it and use the up-arrow anddown-arrow keys.Note: After you add a column, to add another column, click the AddColumn (+) icon.Name: Name of the column. Must be unique within the table. Suggestion: For a newcolumn, replace any default name, such as COLUMN1.Datatype: Simple indicates a simple (non-object) data type; Complex indicates anobject type. For a complex type, you must specify the schema and the type name (forexample, MDSYS and SDO_GEOMETRY for the <strong>Oracle</strong> Spatial geometry type).Type: Name of the data type. Most of the remaining information depends on thespecific type.Precision: For numeric data, the precision (total number of significant digits that canbe represented) of the column data.Scale: For numeric data, the scale (number of digits after the decimal point) of thecolumn data.Size: For character data, the maximum size of the column data.Units: For character data, the units represented by the Size: BYTE for bytes or CHARfor characters. This attribute is important if the database can contain data in Unicodeformat, with multiple bytes for each character.Default: For relevant types, the default value inserted into the column if no value isspecified when a row is inserted.Cannot be NULL: If this option is checked, the column must contain data; you cannotspecify no value or an explicit null value for this column when you insert a row. If thisoption is not checked, the column can contain either data or no data. A primary keycolumn (see Primary Key tab) cannot be null.Comment: Optional descriptive comment about the column.To add another column, click the Add Column (+) icon.Primary Key tabSpecifies the primary key for the table. The primary key is the column, or set ofcolumns, that uniquely identifies each row in the table.An index is automatically created on the primary key.Name: Name of the constraint to be associated with the primary key definition. Mustbe unique within the database.Enabled: If this option is checked, the primary key constraint is enforced: that is, thedata in the primary key column (or set of columns) must be unique and not null.Available Columns: Lists the columns that are available to be added to the primarykey definition.Selected Columns: Lists the columns that are included in the primary key definition.To add a column to the primary key definition, select it in Available Columns and clickthe Add (>) icon; to remove a column from the primary key definition, select it inSelected Columns and click the Remove (>) or Remove All (
Create/Edit Table (with advanced options)column up or down in the primary key definition, select it in Selected Columns anduse the arrow keys.The remaining fields (Populate Primary Key Column through Trigger Name) appearonly when you are creating a table. They are not available when you are editing anexisting table.Populate Primary Key Column: When you are creating a table, if you want to use atrigger and a sequence to have a unique value automatically inserted into the primarykey column when you insert a new row, specify the primary key column.From: An existing sequence that you select, or a new sequence whose name you enter.(For a new sequence, <strong>SQL</strong> <strong>Developer</strong> creates the sequence automatically using thename that you enter.)Trigger Name: The name for the before-insert trigger that will be automaticallycreated. This trigger uses the sequence to generate a new value for the primary keywhen a row is inserted. For an example of using this technique, see the tutorial sectionCreating a Table (Transactions).Unique Constraints tabSpecifies one or more unique constraints for the table. A unique constraint specifies acolumn, or set of columns, whose data values must be unique: each data value mustnot be null, and it must not be the same as any other value in the column.For a multicolumn unique constraint, the combination of values must be unique, andno column in the constraint definition can have a null value. For example, if youspecify the office_name and city columns for a unique constraint, you could not havetwo Sales offices in Chicago, but you could have a Sales office in Chicago and a Salesoffice in Atlanta.Unique Constraints: Lists the unique constraints currently defined on the table. Toadd a unique constraint, click the Add button; to delete a unique constraint, select itand click the Remove button.Note: After you add a unique constraint, to add another uniqueconstraint, click the Add button.Name: Name of the unique constraint. Must be unique within the database.Enabled: If this option is checked, the unique constraint is enforced.Available Columns: Lists the columns that are available to be added to the uniqueconstraint definition.Selected Columns: Lists the columns that are included in the unique constraintdefinition.To add a column to the unique constraint definition, select it in Available Columns andclick the Add (>) icon; to remove a column from the unique constraint definition,select it in Selected Columns and click the Remove (>) or Remove All (
Create/Edit Table (with advanced options)Foreign Keys tabSpecifies one or more foreign keys for the table. A foreign key specifies a column("local column"), each of whose data values must match a value in the primary key orunique constraint of another table.Foreign Keys: Lists the foreign keys currently defined on the table. To add a foreignkey, click the Add button; to delete a foreign key, select it and click the Remove button.Note: After you add a foreign key, to add another foreign key, clickthe Add button.Name: Name of the foreign key definition. Must be unique within the database.Enabled: If this option is checked, the foreign key is enforced.Referenced Schema: Name of the schema containing the table with the primary key orunique constraint to which this foreign key refers.Referenced Table: Name of the table with the primary key or unique constraint towhich this foreign key refers.Referenced Constraint: Name of the primary key or unique constraint to which thisforeign key refers.Associations: Local Column: Lists the column in the currently selected (local) tablethat is included in the foreign key definition. For each local column in the foreign keydefinition, select the name of a column in the local table.Associations: Referenced Column on [table]: For each local column, identifies thecolumn in the other (foreign) table that must have a value matching the value in thelocal column.Check Constraints tabSpecifies one or more check constraints for the table. A check constraint specifies acondition that must be met when a row is inserted into the table or when an existingrow is modified.Check Constraints: Lists the check constraints currently defined on the table. To add acheck constraint, click the Add button; to delete a check constraint, select it and clickthe Remove button.Note: After you add a check constraint, to add another checkconstraint, click the Add button.Name: Name of the check constraint definition. Must be unique within the database.Enabled: If this option is checked, the check constraint is enforced.Condition: Condition that must be met for a row. Can be any valid WHERE clause(without the WHERE keyword) for a SELECT statement. For example, to indicate thatthe value in a numeric column named RATING must be from 1 to 10, you can specify:rating >=1 and rating
Create/Edit Table (with advanced options)Indexes: Lists the indexes currently defined on the table. To add an index, click theAdd Index (+) icon; to delete an index, select it and click the Remove Index (X) icon.Note: After you add an index, to add another index, click the AddIndex (+) icon.Name: Name of the index. Must be unique within the schema.Index: A list of index expressions, that is, the table columns or column expressions inthe index. To add an index expression, click the Add Column Expression (+) icon; thisadds a column name here and in Column Expression, where you can edit it. To deletean index expression, click the Remove Column Expression (X) icon; to move an indexexpression up or down in the list click the Move Column Up and Move Column Downicons. An index must have at least one index expression.For example, to create an index on the AUTHOR_LAST_NAME column of the Bookstable from the tutorial (see Creating a Table (Books)), click the + icon, and selectAUTHOR_LAST_NAME in Column Name or Expression (next field), which changesBOOKS to AUTHOR_LAST_NAME in the Index field.Column Name or Expression: A column name or column expression. A columnexpression is an expression built from columns, constants, <strong>SQL</strong> functions, anduser-defined functions. When you specify a column expression, you create afunction-based index.Order: ASC for an ascending index (index values sorted in ascending order); DESC fora descending index (index values sorted in descending order).Storage Options tabSpecifies storage options for the table, enabling you to override the default storageoptions.Tablespace: Name of the tablespace for the table.Pct Free: Percentage of space in each of the data blocks of the table reserved for futureupdates to the rows of the table. You can enter a value from 0 through 99.Pct Used: Minimum percentage of used space that <strong>Oracle</strong> maintains for each datablock of the table. A block becomes a candidate for row insertions when its used spacefalls below the Pct Used value. You can enter a value from 1 through 99.Extents - Initial: Size of the first extent of the table. Specify K (kilobytes) or M(megabytes) for the unit associated with the number.Extents - Next: Size of the next extent to be allocated to the table. Specify K (kilobytes)or M (megabytes) for the unit associated with the number.Extents - Min: Minimum number of extents allocated when the table is created.Extents - Max: Maximum number of extents allocated when the table is created.Unlimited (if checked) means that there is no maximum (and any specified maximumis ignored).Pct Increase: Percentage that each extent grows over the previous extent.Ini Trans: Number of update transaction entries for which space is initially reserved inthe data block header.Max Trans: Number of transaction entries that could concurrently use data in a datablock. This parameter has been deprecated. <strong>Oracle</strong> Database now automatically allowsDialog Boxes for Creating/Editing Objects 3-13
Create/Edit Table (with advanced options)up to 255 concurrent update transactions for any data block, depending on theavailable space in the block.Free Lists - Lists: Number of free lists for each of the free list groups for the table. Thedefault and minimum value for this parameter is 1, meaning that each free list groupcontains one free list.Free Lists - List Groups: Number of groups of free lists for the table. The default andminimum value for this parameter is 1. <strong>Oracle</strong> uses the instance number of RealApplication Clusters instances to map each instance to one free list group.Buffer Pool: means to use the <strong>Oracle</strong> Database default. KEEP means toput blocks from the segment into the Keep buffer pool; maintaining an appropriatelysized Keep buffer pool lets <strong>Oracle</strong> retain the database object in memory to avoid I/Ooperations. RECYCLE means to put blocks from the segment into the Recycle pool; anappropriately sized Recycle pool reduces the number of objects whose default pool isthe Recycle pool from taking up unnecessary cache space.Logging: means to use the <strong>Oracle</strong> Database default. ON means that thetable creation and any subsequent direct loader (<strong>SQL</strong>*Loader) and direct-path INSERToperations against the table, partition, or LOB storage are logged in the redo log file.OFF means that these operations are not logged in the redo log file.Partitioning tabSpecifies partitioning options for a partitioned table, which is a table that is organizedinto smaller and more manageable pieces called partitions. <strong>SQL</strong> queries and DMLstatements do not need to be modified in order to access partitioned tables; however,after partitions are defined, DDL statements can access and manipulate individualspartitions rather than entire tables or indexes. Also, partitioning is entirely transparentto applications.Partition By: The type of partitioning: RANGE partitions the table on ranges of valuesfrom the column list (which for an index-organized tablet must be a subset of theprimary key columns of the table); HASH partitions the table using the hash method(rows assigned to partitions using a hash function on values found in columnsdesignated as the partitioning key); LIST partitions the table on lists of literal valuesfrom column (useful for controlling how individual rows map to specific partitions).Available: Lists the columns whose values are available to be used in assigning rowsto partitions.Selected: Lists the column whose values are to be used in assigning rows to partitions.To add a column to the partitioning definition, select it in Available Columns and clickthe Add (>) icon; to remove a column from the partitioning definition, select it inSelected Columns and click the Remove (>) or Remove All (
Create/Edit Table (with advanced options)Tablespaces: Available and Selected tablespaces for storage of the data in asubpartition.Subpartition Templates: Specifications (subpartition templates) to control theplacement of rows in each subpartition. Click the Add (+) icon to add a subpartitiontemplate that is appropriate for the subpartition type.Subpartition Details: For each subpartition template, specify a name and (if relevant)a value or set of values that is appropriate for the subpartition type.Storage: Enables you to specify a tablespace for the subpartition.Partition Definitions tabDefines each partition for a partitioned table. The options depend on the partitiontype, and might include the following.Partitions: Specifications to control the placement of rows in each partition. Click theAdd (+) icon to add a partition specification that is appropriate for the partition type.Partition Details: For each partition specification, specify a name and (if relevant) avalue or set of values that is appropriate for the subpartition type.Storage: Enables you to specify a tablespace for the partition.Subpartitions: Enables you to specify subpartition information.Index Organized Properties tabSpecifies options for an index-organized table, which is a table in which the rows,both primary key column values and nonkey column values, are maintained in anindex built on the primary key. Index-organized tables are best suited for primarykey-based access and manipulation.PCTTHRESHOLD: The percentage of space reserved in the index block for anindex-organized table row; must be large enough to hold the primary key. All trailingcolumns of a row, starting with the column that causes the specified threshold to beexceeded, are stored in the overflow segment. PCTTHRESHOLD must be a value from1 to 50; the default is 50.Key Compression: If this option is checked, key compression is enabled, whicheliminates repeated occurrence of primary key column values in index-organizedtables. In the box to the right of this field, you can specify the prefix length, which isthe number of prefix columns to compress. (This value can be from 1 to the number ofprimary key columns minus 1; the default prefix length is the number of primary keycolumns minus 1.)Include Column: Column at which to divide an index-organized table row into indexand overflow portions. The primary key columns are always stored in the index. TheInclude Column can be either the last primary key column or any non-primary-keycolumn. All non-primary-key columns that follow the Include Column are stored inthe overflow data segment.Mapping Table: If this option is checked, <strong>SQL</strong> <strong>Developer</strong> creates a mapping of local tophysical ROWIDs and store them in a heap-organized table. This mapping is neededin order to create a bitmap index on the index-organized table. If the index-organizedtable is partitioned, then the mapping table is also partitioned and its partitions havethe same name and physical attributes as the base table partitions.Overflow: Specifications for the overflow segment. The options are the same as for theStorage Options tab.Dialog Boxes for Creating/Editing Objects 3-15
Create/Edit Table (with advanced options)External Table Properties tabSpecifies options for an external table, which is a read-only table whose metadata isstored in the database but whose data in stored outside the database. Among othercapabilities, external tables let you query data without first loading it into thedatabase.Access Driver: The access driver of the external table. The access driver is the API thatinterprets the external data for the database: ORACLE_LOADER or ORACLE_DATAPUMP. You must specify the ORACLE_DATAPUMP access driver if you specifythe AS subquery clause to unload data from one <strong>Oracle</strong> database and reload it into thesame database or a different <strong>Oracle</strong> database.Access Type: Type of data to be automatically converted during loads and unloads:BLOB or CLOB.Default Directory: A default directory object corresponding to a directory on the filesystem where the external data sources may reside. The default directory can also beused by the access driver to store auxiliary files such as error logs.Project Column: Determines how the access driver validates the rows of an externaltable in subsequent queries. ALL processes all column values, regardless of whichcolumns are selected, and validates only those rows with fully valid column entries. Ifany column value would raise an error, such as a data type conversion error, the row isrejected even if that column was not referenced in the select list. REFERENCEDprocesses only those columns in the select list.The ALL setting guarantees consistent result sets. The REFERENCED setting can resultin different numbers of rows returned, depending on the columns referenced insubsequent queries, but is faster than the ALL setting. If a subsequent query selects allcolumns of the external table, then the settings behave identically.Reject Limit: The number of conversion errors can occur during a query of theexternal data before an <strong>Oracle</strong> Database error is returned and the query is aborted.Access Parameters: Values to the parameters of the specific access driver for thisexternal table.Location Specifications: One or more external data sources. Each is usually a file, butit need not be. <strong>Oracle</strong> Database does not interpret this clause; it is up to the accessdriver to interpret this information in the context of the external data. Use the Add (+)icon to add each location specification.DDL tabYou can review and save the CREATE TABLE statement that <strong>SQL</strong> <strong>Developer</strong> will useto create a new table or that reflects any changes you have made to the tableproperties. If you want to make any changes, go back to the relevant tabs and makethe changes there.To save the <strong>SQL</strong> statement to a script file, click Save and specify the location and filename.When you are finished, click OK.Related TopicsCreate Table (quick creation) (dialog box with limited features)Database Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceTutorial: Creating Objects for a Small Database3-16 <strong>SQL</strong> <strong>Developer</strong> Online Help
Create Trigger3.18 Create TriggerThe following information applies to a trigger, which is which is a stored PL/<strong>SQL</strong>block associated with a table, a schema, or the database, or an anonymous PL/<strong>SQL</strong>block or a call to a procedure implemented in PL/<strong>SQL</strong> or Java. The trigger isautomatically executed when the specified conditions occur.Trigger Owner: Database schema in which to create the trigger.Name: Name of the trigger. Must be unique within the database.Trigger Type: The type of object on which to create the trigger: TABLE, VIEW,SCHEMA, or DATABASE. (The remaining items depend on the type of trigger.)Table Owner or View Owner: For a trigger on a table or a view, the name of the ownerof the table or the view.Table Name or View Name : For a trigger on a table or a view, the name of the table orthe view.Before or After: For a trigger on a table, select Before to cause the database to fire thetrigger before executing the triggering event, or select After to cause the database tofire the trigger after executing the triggering event.Statement Level or Row Level: For a trigger on a table, Statement Level fires thetrigger once before or after the triggering statement that meets the optional triggerconstraint defined in the WHEN condition; Row Level fires the trigger once for eachrow that is affected by the triggering statement and that meets the optional triggerconstraint defined in the WHEN condition.Insert, Update, Delete: For a trigger on a table or a view, Insert fires the triggerwhenever an INSERT statement adds a row to a table or adds an element to a nestedtable; Update fires fire the trigger whenever an UPDATE statement changes a value inone of the columns specified in Selected Columns (or in any column if no columns arespecified); Delete fires the trigger whenever a DELETE statement removes a row fromthe table or removes an element from a nested table.Referencing - Old: For a trigger on a table, the correlation names in the PL/<strong>SQL</strong> blockand WHEN condition of a row trigger to refer specifically to old value of the currentrow.Referencing - New: For a trigger on a table, the correlation names in the PL/<strong>SQL</strong>block and WHEN condition of a row trigger to refer specifically to new value of thecurrent row.Available Columns: For a trigger on a table, lists the columns from which you canselect for use in an Update trigger definition.Selected Columns: For a trigger on a table, lists the columns used in an Update triggerdefinition.When: For a trigger on a table, an optional trigger condition, which is a <strong>SQL</strong> conditionthat must be satisfied for the database to fire the trigger. This condition must containcorrelation names and cannot contain a query.Schema: For a trigger on a schema, the name of the schema on which to create thetrigger.Available Events: For a trigger on a schema or database, lists events from which youcan select for use in the trigger definition.Selected Events: For a trigger on a schema or database, lists events used in the triggerdefinition.Dialog Boxes for Creating/Editing Objects 3-17
Create Type (User-Defined)For more information about triggers, see Triggers: Usage Information.Related TopicsTriggers: Usage InformationDatabase Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceDialog Boxes for Creating/Editing Objects3.19 Create Type (User-Defined)This dialog box is displayed when you right-click Types in the Connections navigatorand select Create Type to create a user-defined type. After you complete theinformation in this dialog box and click OK, a <strong>SQL</strong> Worksheet is displayed in whichyou must specify the appropriate definition of the type.Schema: Database schema in which to create the type.Name: Name of the type. Must be unique within its schema.Type: Select the type of data type to be created: array type, object type specification,object type specification and type body, or table type.For more information about creating a user-defined type, see the CREATE TYPEstatement in <strong>Oracle</strong> Database <strong>SQL</strong> Reference. For information about <strong>Oracle</strong>-suppliedtypes, see Data Types: Usage Information.Related TopicsDatabase Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceDialog Boxes for Creating/Editing Objects3.20 Create/Edit User Defined ReportThe following information applies to a user-defined report. For information about howto create a user-defined report, see User Defined reports.Name: Name of the user-defined report.Description: Optional description of the report.ToolTip: Optional tooltip text to be displayed when the mouse pointer stays brieflyover the report name in the Reports navigator display.<strong>SQL</strong> Statement: The complete <strong>SQL</strong> statement for retrieving the information to bedisplayed in the user-defined report. As a trivial example, the statement SELECT user"Current User" FROM DUAL; displays Current User as the heading and the name ofthe user associated with the current database connection.Suggestion: Look at the <strong>SQL</strong> statements for various <strong>SQL</strong> <strong>Developer</strong>-supplied reports;check the Messages - Log pane below the report results, or click the <strong>SQL</strong> icon underthe Report Results tab.Related TopicsReportsUser Defined reports3-18 <strong>SQL</strong> <strong>Developer</strong> Online Help
Create/Edit View3.21 Create/Edit User Defined Report FolderThe following information applies to a folder for organizing user-defined reports. Eachfolder can contain reports and other folders (subfolders). For example, you can create afolder named Sales, and then under that folder create folders named Sales by Districtand Sales by Product.For information about how to create user-defined reports and folders for these reports,see User Defined reports.Name: Name of the folder.Description: Optional description of the folder.ToolTip: Optional tooltip text to be displayed when the mouse pointer stays brieflyover the folder name in the Reports navigator display.Related TopicsReportsUser Defined reports3.22 Create/Edit ViewThe view dialog box is used for creating or editing a view or materialized view. Youmust use the Entire <strong>SQL</strong> Query tab to specify the query part of the view definition,and you can use one or more other tabs (depending on the type of view) for otherparts of the definition.If you click OK before you are finished creating or editing the view, right-click theview name in the Connections navigator, select Edit, and continue creating or editingthe view.Schema: Database schema in which to create the view.Name: Name of the view. Must be unique within a schema.Entire <strong>SQL</strong> Query tabSpecifies the query part of the view definition, using the SELECT and FROMkeywords and usually a WHERE clause with whatever syntax is needed to retrieve thedesired information.For example, the following query, from the Creating a View tutorial topic, selectscolumns from the Patrons and Transactions tables, ordering them first by values in thethe PATRON_ID column in the Patrons table and then by values in theTRANSACTION_TYPE column in the Transactions table. The result is a listing bypatron ID of all patrons who had transactions, and for each listed patron thetransaction information listed by transaction typeCREATE VIEW patrons_trans_view ASSELECT p.patron_id, p.last_name, p.first_name,t.transaction_type, t.transaction_dateFROM patrons p, transactions tWHERE p.patron_id = t.patron_idORDER BY p.patron_id, t.transaction_type;<strong>SQL</strong> Parse Results: If you click Test Syntax, displays any <strong>SQL</strong> syntax errors, ordisplays a message indicating no errors if there are no syntax errors.Revert: Cancels any edits you have made in the Entire <strong>SQL</strong> Query box, and displaysthe contents of the box before these edits.Dialog Boxes for Creating/Editing Objects 3-19
Create/Edit ViewTest Syntax: Checks the statement in the Entire <strong>SQL</strong> Query box for any <strong>SQL</strong> syntaxerrors.View Information or Materialized View Information tabOptions for a standard view:Restrict Query: If this option is checked, you can enable one of the following options■Read Only: Prevents the view from being used to add, delete, or change data inthe underlying table or tables.■ Check Option: If this option is checked, it prohibits any changes to the underlyingtable or tables that would produce rows that are not included in this view.Force on create: If this option is checked, the view is created even if it has errors in itsdefinition. This option is useful if you want to create the view regardless of any errors,and go back and correct the errors later. If this option is not checked, the view is notcreated is its definition contains any errors.Options for a materialized view:Refresh Options:Method: The method of refresh operation to be performed:■■■Complete Refresh: Executes the defining query of the materialized view, even if afast refresh is possible.Fast Refresh: Uses the incremental refresh method, which performs the refreshaccording to the changes that have occurred to the master tables. The changes forconventional DML changes are stored in the materialized view log associated withthe master table.The changes for direct-path INSERT operations are stored in thedirect loader log.Forced Refresh: Performs a fast refresh if one is possible; otherwise, performs acomplete refresh.■ Never: Do not perform refresh operations.When: The type of refresh operation to be performed:■■Automatic: Automatically performs a refresh operation, starting and continuing asspecified in the remaining fields.On Commit: Performs a fast refresh whenever the database commits a transactionthat operates on a master table of the materialized view. This may increase thetime taken to complete the commit, because the database performs the refreshoperation as part of the commit process.■ On Demand: Performs a refresh when one of the DBMS_MVIEW refreshprocedures is called.Type: Refresh type, which determines the type of materialized view:■■Primary Key: Creates a primary key materialized view, which allows materializedview master tables to be reorganized without affecting the eligibility of thematerialized view for fast refresh.Row ID: Creates a rowid materialized view, which is useful if the materializedview does not include all primary key columns of the master tables.Start on: Starting date and time for the first automatic refresh operation. Must be inthe future.3-20 <strong>SQL</strong> <strong>Developer</strong> Online Help
Create/Edit ViewNext: Time for the next automatic refresh operation. The interval between the Start onand Next times establishes the interval for subsequent automatic refresh operations. Ifyou do not specify a value, the refresh operation is performed only once at the timespecified for Start on.Materialized View Options:Parallel: If this option is checked, parallel operations will be supported for thematerialized view, and you can specify a number for the default degree of parallelismfor queries and DML on the materialized view after creation.Enable Cache: If this option is checked, the blocks retrieved for this table are placed atthe most recently used end of the least recently used (LRU) list in the buffer cachewhen a full table scan is performed. This setting is useful for small lookup tables. Ifthis option is not checked, the blocks are placed at the least recently used end of theLRU list.Build Type: Specifies when to populate the materialized view. Immediate indicatesthat the materialized view is to be populated immediately. Deferred indicates that thematerialized view is to be populated by the next refresh operation. If you specifyDeferred, the first (deferred) refresh must always be a complete refresh; until then, thematerialized view has a staleness value of unusable, so it cannot be used for queryrewrite.Enable Query Rewrite: If this option is checked, the materialized view is enabled forquery rewrite, an optimization technique that transforms a user request written interms of master tables into a semantically equivalent request that includes one or morematerialized views.Prebuilt Option: If this option is checked, an existing table is registered as apreinitialized materialized view. This option is particularly useful for registering largematerialized views in a data warehousing environment. The table must have the samename and be in the same schema as the resulting materialized view, and the tableshould reflect the materialization of a subquery. Reduced Precision authorizes the lossof precision that will result if the precision of the table or materialized view columnsdo not exactly match the precision returned by subquery. No Reduced Precisionrequires that the precision of the table or materialized view columns match exactly theprecision returned by subquery, or the create operation will fail.Index Storage Options:Use index storage: If this option is checked, you can specify storage parameters for thedefault index that is used to maintain the materialized view data and to speed upincremental (fast) refresh of the materialized view. You can specify either the defaultsettings or custom settings for the tablespace, the initial and subsequent extent size,and the percentage of free space to allocate initially in each extent.DDL tabIf you are editing an existing view or if you have only partially created a view, this tabcontains a read-only display of a <strong>SQL</strong> statement that reflects the current definition ofthe view.To save the <strong>SQL</strong> statement to a script file, click Save and specify the location and filename.Related TopicsDatabase Objects<strong>SQL</strong> <strong>Developer</strong> User InterfaceDialog Boxes for Creating/Editing Objects 3-21
Configure File Type AssociationsDialog Boxes for Creating/Editing Objects3.23 Configure File Type AssociationsThis dialog box, which is displayed the first time you start <strong>SQL</strong> <strong>Developer</strong>, enables youto associate certain file types with <strong>SQL</strong> <strong>Developer</strong>. If a file type is associated with <strong>SQL</strong><strong>Developer</strong>, files with that type’s extension will automatically be opened by <strong>SQL</strong><strong>Developer</strong> when you double-click the file name. Any previous association for that filetype is replaced.If you do not associate a file type with <strong>SQL</strong> <strong>Developer</strong>, any existing association for thatfile is unchanged.After you close this box, you can change the associations for these file types and manyothers by clicking Tools and then Preferences, and selecting File Types (see FileTypes).3.24 Edit Value (Table Column Data)This dialog box enables you to edit data in a cell in the table Data grid (that is, edit thevalue of a single column within a row). You can change the data value and then clickOK.3.25 Export (Selected Objects or Object Types)This dialog box is displayed when you click Tools and then Export. For a selecteddatabase connection, you can export some or all objects of one or more object types toa file containing <strong>SQL</strong> data definition language (DDL) statements to create theseobjects. To specify options for the export operation, use the Options tab. To specify theobjects and/or types of objects to export, use the Objects tab.Options tabFile: Specify the name of the file to contain the DDL statements for creating the objectsto be exported (for example, my_tables.sql). You can click Browse to select adirectory for this file.Storage: If this option is checked, any STORAGE clauses in definitions of the databaseobjects are preserved in the exported DDL statements. If you do not want to use thecurrent storage definitions (for example, if you will re-create the objects in a differentsystem environment), uncheck this option.Terminator: If this option is checked, ...........(TBS.....).Pretty Print: If this option is checked, the statements are attractively formatted in theoutput file, and the size of the file will be larger than it would otherwise be.Byte vs. Char: If this option is checked, column length specifications refer to bytes; ifthis option is not checked, column length specifications refer to characters.Add Force to Views: If this option is checked, the FORCE option is added to anyCREATE VIEW statements, causing each view to be created even if it contains errors.Constraints as Alters: If this option is checked, constraints for each table are defined inseparate ALTER TABLE statements instead of in the CREATE TABLE statement.Objects tabConnection: Select the database connection with the objects to be exported.3-22 <strong>SQL</strong> <strong>Developer</strong> Online Help
Filter Object TypesObjects: Expand the tree as needed to display the object types and objects that youwant to export, and check to select the desired object types and/or objects. You mustselect at least one object or object type.3.26 Export Table DataThis dialog box is displayed when you right-click a table name and select Export andthen an export format. You can export some or all of the table data to a file or to thesystem clipboard. To restrict the output to data in specified columns, use the Columnstab. To restrict the output based on a WHERE clause condition, use the Where tab.Format tabFormat: Determines the format of entries written in the specified output file: Insert for<strong>SQL</strong> INSERT statements, XML for XML tags and data, <strong>SQL</strong> LOADER for a<strong>SQL</strong>*Loader control file, or CSV for comma-separated values including a header rowfor column identifiers.Output: File writes the output to a file that you specify; Clipboard places the output onthe system clipboard, so that you can paste it into a file, a command line, or otherlocation appropriate for the format.File: If the output is to a file, click Browse to select the directory or folder and tospecify the file name and extension. The file path is then placed in the File box.Standard file extensions are .sql for Insert format, .xml for XML format, .ctl for <strong>SQL</strong>LOADER format, and .csv for CSV format.Columns tabYou can specify whether the output should include data from all columns or just fromthe checked columns.Where tabYou can restrict the output by entering a valid WHERE clause for a query on the table,without the WHERE keyword. For example, to restrict the exported data to rowswhere a column named RATING contains a value greater than 5, specify: rating >53.27 Externally Modified FilesThis dialog box filters is displayed when an external application has modified a filethat you have open in <strong>SQL</strong> <strong>Developer</strong>. You are asked if you want to reload theexternally modified file.If you click Yes, the externally modified file overwrites any changes that you mighthave made in <strong>SQL</strong> <strong>Developer</strong>. If you click No, the externally modified file will beoverwritten by your version when you save the file in <strong>SQL</strong> <strong>Developer</strong>.3.28 Filter Object TypesThis dialog box filters (restricts) the types of objects to be displayed for the schemaassociated with the selected user.Available Object Types: Lists the types of objects that are available to be added to thedisplay.Displayed Object Types: Lists the types of objects that are included in the display.Dialog Boxes for Creating/Editing Objects 3-23
Find/Replace TextTo add a type of object to the display, select it in Available Object Types and click theAdd (>) icon; to remove a type of object from the display, select it in Displayed ObjectTypes and click the Remove (>) or Remove All (
Create/Edit BreakpointFiles: A list of files opened in <strong>SQL</strong> <strong>Developer</strong>, with the most recent file first. The ShowAll option determines whether the list includes only files opened implicitly or filesopened implicitly or explicitly.Show All: If this option is checked, the list includes both explicitly and implicitlyopened files; if this option is not checked, the list includes only implicitly opened files.Explicitly opened files are those that you opened directly; implicitly opened files arethose that <strong>SQL</strong> <strong>Developer</strong> opened to support your work (for example, while you weredebugging).3.35 Run/Debug PL/<strong>SQL</strong>Use this box to specify parameter values for running or debugging a PL/<strong>SQL</strong> functionor procedure. (If you specify a package, select a function or procedure in the package.)Target: Name of the function or procedure to run or to run in debug mode. (You have achoice only if you specified a package that has more than one subprogram.)Parameters: List of each parameter for the specified target. The mode of eachparameter can be IN (the value is passed in), OUT (the value is returned, or IN/OUT(the value is passed in, and the result of the function or procedure’s action is stored inthe parameter).PL/<strong>SQL</strong> Block: A block of PL/<strong>SQL</strong> code created by <strong>SQL</strong> <strong>Developer</strong>. You shouldchange the formal IN and IN/OUT parameter specifications in this block to actualvalues that you want to use for running or debugging the function or procedure.For example, to specify 10 as the value for an input parameter named in_rating,change IN_RATING => IN_RATING to IN_RATING => 10.When you click OK, <strong>SQL</strong> <strong>Developer</strong> runs the function or procedure.If you are debugging a function or procedure, the debugging toolbar and one or morewindows for debug-related information are displayed, as explained in Running andDebugging Functions and Procedures.Related TopicsRunning and Debugging Functions and ProceduresDebugging a PL/<strong>SQL</strong> Procedure (tutorial)3.36 Create/Edit BreakpointUse this box to create or edit a breakpoint to use when debugging a PL/<strong>SQL</strong> functionor procedure.Definition tabSpecify the definition of the breakpoint.Breakpoint Type: Type of breakpoint, indicating when the breakpoint will occur.Options include breaking when one of the following occurs: a specific line of code(Source); exception class or other class; method, file, or watchpoint.Breakpoint Details: Options depend on the breakpoint type.Breakpoint Group Name: Breakpoint group in which to include this breakpoint.Breakpoint groups can be edited, enabled, and disabled.Dialog Boxes for Creating/Editing Objects 3-25
Save/Save As3.37 Save/Save As3.38 Save FilesConditions tabSpecify any conditions that apply to the breakpoint.Condition: A <strong>SQL</strong> condition (WHERE clause without the WHERE keyword)restricting when the breakpoint occurs. For example, to specify that the conditionshould occur only when status_code is greater than 10, specify:status_code > 10Thread Options: You can specify whether the breakpoint occurs for all threads, oronly when the breakpoint is hit by threads that either do or do not have a specifiedname.Pass Count: The number of times the debugger should allow execution to pass overthe breakpoint before the breakpoint occurs.Actions tabSpecify the actions to be taken when the breakpoint occurs. The options you specifyoverride any default values on the Debugger: Breakpoints: Default Actions pane of the<strong>SQL</strong> <strong>Developer</strong> Preferences.Halt Execution: Pauses execution when the breakpoint occurs.Beep: Beeps when the breakpoint occurs.Log Breakpoint Occurrence: Sends a message to the log window when the breakpointoccurs. You can also specify the following to be included in each display: a tag, and acondition to be evaluated.Enable/Disable a Group of Breakpoints: Enables or disables the specified breakpointgroup when this breakpoint occurs.Related TopicsRunning and Debugging Functions and ProceduresDebugging a PL/<strong>SQL</strong> Procedure (tutorial)This is a standard box for saving information to a file: use Location to navigate to(double-clicking) the folder in which to save the file, then specify the file name(including any extension) and, if necessary, the file type.This box asks if you want to save the specified files before another action occurs (forexample, saving procedures you had been editing before disconnecting).3.39 Unable to Save FilesThis box informs you that <strong>SQL</strong> <strong>Developer</strong> is unable to save the specified file or files. Tocancel the attempt to save the files and to return to edit the relevant object, clickCancel.3.40 Save Style SettingsThis dialog box is displayed when you click Save As in the Code Editor: Syntax Colorspane when setting <strong>SQL</strong> <strong>Developer</strong> Preferences. You can save the specified color3-26 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>SQL</strong>*Plus Locationsettings as a named color scheme, which adds it to the drop-down list for Scheme inthat pane.3.41 <strong>SQL</strong> History ListUse this box, which is displayed by clicking the <strong>SQL</strong> History button in the <strong>SQL</strong>Worksheet toolbar, to view <strong>SQL</strong> statements that you have executed and optionally toselect (check) one to have it either replace the statements currently on the <strong>SQL</strong>Worksheet or be added to the statements currently on the <strong>SQL</strong> Worksheet.The <strong>SQL</strong> history list will not contain any statement that can include a password. Suchstatements include (but are not necessarily limited to) CONNECT, ALTER USER, andCREATE DATABASE LINK.Clear: Removes all statements from the display in the dialog box.Replace: Replaces any statements currently on the <strong>SQL</strong> Worksheet with the selectedstatement.Append: Appends the selected statement to any statements currently on the <strong>SQL</strong>WorksheetRelated TopicsUsing the <strong>SQL</strong> Worksheet3.42 <strong>SQL</strong>*Plus LocationUse this box to specify the location of the <strong>SQL</strong>*Plus executable on the system on whichyou are running <strong>SQL</strong> <strong>Developer</strong>. The <strong>SQL</strong>*Plus executable is under the <strong>Oracle</strong> Homedirectory or folder, and its specific location and file name depend on your operatingsystem and <strong>Oracle</strong> Database installation.If there is no <strong>SQL</strong>*Plus executable on the system on which you are running <strong>SQL</strong><strong>Developer</strong>, you cannot invoke <strong>SQL</strong>*Plus from <strong>SQL</strong> <strong>Developer</strong>.Related TopicsUsing <strong>SQL</strong>*PlusDialog Boxes for Creating/Editing Objects 3-27
<strong>SQL</strong>*Plus Location3-28 <strong>SQL</strong> <strong>Developer</strong> Online Help
4Database Objects: Usage InformationThis topic discusses creating and managing database objects in your schema, plusdesign considerations and indexing guidelines when developing applications with<strong>Oracle</strong> Database. It contains the following topics:■■■■■■Overview of Managing ObjectsManaging TablesManaging IndexesManaging ViewsManaging SequencesManaging SynonymsSee Also:4.1 Overview of Managing Objects■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information about databaseobjects, object names, and data types.You need to create tables, indexes, and possibly other database objects in a schemabefore you start developing your application. A schema is a collection of databaseobjects. A schema is owned by a database user and has the same name as that user,such as the HR schema. Schema objects are logical structures created by users. Objectscan define areas of the database to hold data, such as tables or indexes, or can consistjust of a definition, such as a views or synonyms.Database Objects: Usage Information discusses tables, indexes, views, sequences, andsynonyms. Other database (schema) objects include functions, packages, procedures,and triggers. Functions, packages, and procedures are discussed in Subprograms andPackages: Usage Information. Triggers are discussed in Triggers: Usage Information.Some object types have many more management options than others, but most have anumber of similarities. Every object in the database belongs to just one schema and hasa unique name within that schema. Therefore, when you create an object, you mustensure it is in the schema where you intend to store it. Generally, you place all of theobjects that belong to a single application in the same schema.A database object name must abide by certain rules, including the rule that it must beunique within its schema. For example, object names cannot be longer than 30 bytesand must begin with a letter. If you attempt to create an object with a name thatviolates any of these rules, then <strong>Oracle</strong> raises an error.Database Objects: Usage Information 4-1
Managing TablesTo include lowercase characters, special characters, or spaces in an object name, youmust enclose the name in quotation marks (" ") when you type it in a Name field in<strong>SQL</strong> <strong>Developer</strong>. Example: "My table"The following topics describe how to view, create, and manage the various types ofobjects in your database schemas:■■■■■Managing TablesManaging IndexesManaging ViewsManaging SequencesManaging Synonyms4.2 Managing TablesTables are the basic unit of data storage in an <strong>Oracle</strong> database. They hold alluser-accessible data. A table is two-dimensional object comprised of columns androws. For example the employees table includes (vertical) columns called first_name, last_name, and employee_id. Each (horizontal) row in the table contains avalue for employee name and Id number. The most common type of table in an <strong>Oracle</strong>database is a relational table.This topic contains the following topics:■ Column Data Types■ Column Default Values■ Ensuring Data Integrity With Constraints■ Column Constraints■ Table-Level ConstraintsSee Also:■■■<strong>Oracle</strong> Database Administrator's Guide for information on managingtables.<strong>Oracle</strong> Database Concepts for conceptual information on tablestypes.<strong>Oracle</strong> Database <strong>SQL</strong> Reference for the syntax required to create andalter tables.4.2.1 Column Data TypesData types are required elements that define the nature of the data to be stored in thecolumns of a table. Data types might include a value to indicate the longest value thatcan be placed in the column. When you create a table, you must specify a data type foreach of its columns. For a discussion of data types, see Data Types: Usage Information.These data types define the domain of values that each column can contain or eachargument can have. For example, DATE columns cannot accept the value February29 (except for a leap year) or the values 2 or SHOE. Each value subsequently placed ina column assumes the column data type. For example, if you insert 17-JAN-2004 intoa date column, then <strong>Oracle</strong> treats the 17-JAN-2004 character string as a date valueafter verifying that it translates to a valid date.4-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
Managing TablesIn most cases, you should only need columns of NUMBER, VARCHAR2, and DATE datatypes when creating a definition of a table.When defining numeric data, you can use the precision option to set the maximumnumber of digits in the number, and the scale option to define how many of the digitsare to the right of the decimal point. For example, a field to hold monetary valuesmight be defined as NUMBER(12,2), providing ten digits for the primary unit ofcurrency (dollars, pounds, marks, and so on) and two digits for the secondary unit(cents, pennies, pfennigs, and so on).To define a VARCHAR2 field for character data, you must include the size value. Set thesize to the maximum number of bytes (or, optionally, characters) to be stored in thecolumn. A column to hold postal codes for different countries, for example, might berestricted to 12 bytes by defining it as VARCHAR2(12).DATE columns are automatically formatted by <strong>Oracle</strong> to include a date and timecomponent. Although both the date and time are stored in a date column, by default,the date portion is automatically displayed for you, when retrieving date data.However, <strong>Oracle</strong> Database enables you great flexibility in how you can display yourdates and times.4.2.2 Column Default ValuesSee Also: <strong>Oracle</strong> Database <strong>SQL</strong> Reference for a complete list of<strong>Oracle</strong>’s built-in data types.Default values are values that are automatically stored into the column whenever anew row is inserted without a value being provided for the column. When you definea column with a default value, any new rows inserted into the table store the defaultvalue unless the row contains an alternate value for the column. Assign default valuesto columns that contain a typical value. For example, in the departments table, ifmost departments are located at one site, then the default value for the location_idcolumn can be set to this value, such as 1700.Default values can help avoid errors where there is a number, such as zero, thatapplies to a column that has no entry. For example, a default value of zero can simplifytesting, by changing a test like this:IF salary >= 0 AND salary < 50000to the simpler form:IF salary < 50000Depending upon your business rules, you might use default values to represent zeroor FALSE, or leave the default values as NULL to signify an unknown value.Default values can be defined using any literal, or almost any expression includingSYSDATE, which is a <strong>SQL</strong> function that returns the current date.4.2.3 Ensuring Data Integrity With ConstraintsYou can define integrity constraints to enforce business rules on data in your tables.Business rules specify conditions and relationships that must always be true, or mustalways be false.When an integrity constraint applies to a table, all data in the table must conform tothe corresponding rule. When you issue a <strong>SQL</strong> statement that inserts or modifies datain the table, <strong>Oracle</strong> Database ensures that the new data satisfies the integrityconstraint, without the need to do any checking within your program.Database Objects: Usage Information 4-3
Managing Tables4.2.4 Column ConstraintsYou can enforce rules by defining integrity constraints more reliably than by addinglogic to your application. <strong>Oracle</strong> Database can check that all the data in a table obeysan integrity constraint faster than an application can.Some constraints can be defined at the column level or at the table level. Column levelconstraints are syntactically defined where the column to which the constraint appliesis defined. Table level constraints are syntactically defined at the end of the tabledefinition.Column constraints are optional elements that determine what values are valid in thecolumn.The NOT NULL constraint on a column requires that the column must contain a valuewhenever a row is inserted or updated. Unlike other constraints described in"Table-Level Constraints" on page 4-4, which may be defined as part of the columndefinition or part of the table definition, the NOT NULL constraint must be defined aspart of the column definition.Use a NOT NULL constraint when the data is required for the integrity of the database.For example, if all employees must belong to a specific department, then the columnthat contains the department identifier should be defined with a NOT NULL constraint.On the other hand, do not define a column as NOT NULL if the data may be unknownor may not exist when rows are added or changed, for example, the second, optionalline in a mailing address.A primary key constraint automatically adds a NOT NULL constraint to the column orcolumns included in the primary key, in addition to enforcing uniqueness among thevalues.4.2.5 Table-Level ConstraintsYou can apply rules to preserve the integrity of your data. For example, in a tablecontaining employee data, the employee email column must be unique. Similarly, inthis table you cannot have two employees with the same employee Id.<strong>Oracle</strong> Database enables you to apply data integrity rules as constraints on columns atthe table level. Any attempt to insert, update, or remove a row that violates aconstraint results in an error and the statement is rolled back. Likewise, any attempt toapply a new constraint to a populated table also results in an error if any existing rowviolates the new constraint.The types of constraints you can apply at the table level are as follows:■ Primary Key■ Unique Key■ Check Constraint■ Foreign KeyConstraints can be created and, in most cases, modified with a number of differentstatus values. The options include enabled or disabled, which determine if theconstraint is checked when rows are added, modified, or removed; and deferred orimmediate, which cause constraint validation to occur at the end of a transaction or atthe end of a statement, respectively.See Also: <strong>Oracle</strong> Database Concepts for more information onconstraints.4-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
Managing Tables4.2.5.1 Primary KeyA primary key requires that a column (or combination of columns) be the uniqueidentifier of the row and ensures that no duplicate rows exist. A primary key columncannot contain NULL values. Each table can have only one primary key.Use the following guidelines when selecting a primary key:■ Whenever practical, create a sequence number generator to generate uniquenumeric values for your primary key values.■■■■■Choose a column whose data values are unique, because the purpose of a primarykey is to uniquely identify each row of the table.Choose a column whose data values are never changed. A primary key value isonly used to identify a row in the table, and its data should never be used for anyother purpose. Therefore, primary key values should rarely or never be changed.Choose a column that does not contain any nulls. A PRIMARY KEY constraint, bydefinition, does not allow any row to contain a null in any column that is part ofthe primary key.Choose a column that is short and numeric. Short primary keys are easy to type.Minimize your use of composite primary keys. A composite primary keyconstraint applies to more than one column. Although composite primary keys areallowed, they do not satisfy all of the other recommendations. For example,composite primary key values are long and cannot be assigned by sequencenumbers.4.2.5.2 Unique KeyA unique key requires that every value in a column be unique. That is, no two rowscan have duplicate values in a specified column or combination of columns.Choose columns for unique keys carefully. The purpose of these constraints is differentfrom that of primary keys. Unique key constraints are appropriate for any columnwhere duplicate values are not allowed. Primary keys identify each row of the tableuniquely, and typically contain values that have no significance other than beingunique. In the employees table, the email column has a unique key constraintbecause it is important that the emails for each employee are unique. Note that theemail column has a NOT NULL constraint.Some examples of good unique keys include:■ An employee social security number where the primary key might be theemployee number■■■A truck license plate number where the primary key might be the truck numberA customer phone number, consisting of the two columns area_code andlocal_phone where the primary key might be the customer numberA department name and location where the primary key might be the departmentnumber4.2.5.3 Check ConstraintA check constraint requires that a column (or combination of columns) satisfy acondition for every row in the table. A check constraint must be a boolean expressionthat is evaluated using the column value about to be inserted or updated to the row.Database Objects: Usage Information 4-5
Managing Indexes4.3 Managing IndexesUse CHECK constraints when you need to enforce integrity rules based on logicalexpressions, such as comparisons. Never use CHECK constraints when any of the othertypes of integrity constraints can provide the necessary checking.Examples of CHECK constraints include the following:■ A CHECK constraint on employee salaries so that no salary value is less than 0.■■A CHECK constraint on department locations so that only the locations Boston,New York, and Dallas are allowed.A CHECK constraint on the salary and commissions columns to prevent thecommission from being larger than the salary.4.2.5.4 Foreign KeyWhenever two tables contain one or more common columns, you can enforce therelationship between the tables through a referential integrity constraint with a foreignkey. A foreign key requires that all column values in the child table exist in the parenttable. The table that includes the foreign key is called the dependent or child table. Thetable that is referenced is called the parent table.An example of a foreign key constraint is when the department column of theemployees table (child) must contain a department ID that exists in the parentdepartments table.Foreign keys can be comprised of multiple columns. Such a composite foreign keymust reference a composite primary or unique key of the exact same structure, withthe same number of columns and the same data types. Because composite primary andunique keys are limited to 32 columns, a composite foreign key is also limited to 32columns. You must use the same data type for corresponding columns in the parentand child tables. The column names do not need to match.Indexes are optional structures associated with tables. You can create them to improvequery performance. Just as the index in this book helps you to quickly locate specificinformation, an <strong>Oracle</strong> Database index provides a quick access path to table data.You can create indexes on one or more columns of a table. After an index is created, itis automatically maintained and used by <strong>Oracle</strong> Database. Changes to a table's data orstructure, such as adding new rows, updating rows, or deleting rows, areautomatically incorporated into all relevant indexes with complete transparency to theuser.Some indexes are created implicitly through constraints that are placed on a table. Forexample, a column with the constraint that its values be unique causes <strong>Oracle</strong>Database to create a unique key index.<strong>Oracle</strong> Database automatically creates the indexes necessary to support data integritydefined with constraints when you add or enable those constraints. For performancepurposes, you might want to add an index to the columns you define in a child tablewhen adding a foreign key constraint. Before you add additional indexes, you shouldexamine the performance of your database. You can then compare performance afterthe new indexes are added.After index creation, <strong>Oracle</strong> Database automatically synchronizes the index with anysubsequent inserts, updates, or deletes to the base table.Indexes are generally of value to queries and to <strong>SQL</strong> statements that need to operateon a single, existing row or a small number of existing rows. Too many indexes can4-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
Managing Indexescause serious problems by increasing the processing overhead for statements that add,modify, or delete rows. In some cases, a statement could use two or more indexes andthe optimizer picks just one of them. Unless other statements can take advantage ofthe unused indexes, they are not providing any benefit. Therefore, you might findyourself deleting indexes if you create too many.This topic contains the following topics:■■■Creating Indexes for Use with ConstraintsIndex TypesGuidelines for Creating Indexes4.3.1 Creating Indexes for Use with Constraints4.3.2 Index TypesAll enabled unique and primary keys require corresponding indexes, although in mostcases the indexes are created automatically. Note the following:■■■Constraints use existing indexes where possible, rather than creating new ones.Unique and primary keys can use non-unique as well as unique indexes. They caneven use just the first few columns of non-unique indexes.At most one unique or primary key can use each non-unique index.■ The column orders in the index and the constraint do not need to match.You should almost always index foreign keys; the database does not do this for youautomatically.Indexes can be categorized in a number of ways. The primary options are:4.3.2.1 NormalA standard, B-tree index contains an entry for each value in the index key along withan address to the row where the value is stored. A B-tree index is the default and mostcommon type of index in an <strong>Oracle</strong> database.4.3.2.2 Ascending and DescendingThe default search through an index is from lowest to highest value, where characterdata is sorted by ASCII values, numeric data from smallest to largest number, and datefrom the earliest to the latest value. This default behavior is performed in indexescreated as ascending indexes. You can cause index searches to reverse the search orderby creating the related index with the descending option.4.3.2.3 Column and Function-basedTypically, an index entry is based on the value or values found in the table's column orcolumns. This is a column index. Alternatively, you can create a function-based indexin which the indexed value is derived from the table data. For example, to findcharacter data that can be in mixed case, you could use a function-based index to lookfor the values as if they were all in uppercase characters.4.3.2.4 Single Column and ConcatenatedYou can create an index on just one column, which is called a single column index, oron multiple columns, which is called a concatenated index. Concatenated indexes areDatabase Objects: Usage Information 4-7
Managing Indexesuseful when all of the columns are likely to be included in the WHERE clause offrequently executed <strong>SQL</strong> statements.For concatenated indexes, you should define the columns used in the index carefullyso that the column with the fewest duplicate values is named first, the column withnext fewest duplicate values is second, and so on. Columns with many duplicatevalues or many rows with NULL values should not be included or should be thelast-named columns in the index definition.4.3.3 Guidelines for Creating IndexesYou can create indexes on columns to speed up queries. Indexes provide faster accessto data for operations that return a small portion of a table's rows.In general, you should create an index on a column in any of the following situations:■■The column is queried frequently.A referential integrity constraint exists on the column.■ A UNIQUE key integrity constraint exists on the column.You can create an index on any column; however, if the column is not used in any ofthese situations, creating an index on the column does not increase performance andthe index takes up resources unnecessarily.Although the database creates an index for you on a column with an integrityconstraint, explicitly creating an index on such a column is recommended.4.3.3.1 Index the Correct Tables and ColumnsUse the following guidelines for determining when to create an index:■■■Create an index if you frequently want to retrieve less than about 15% of the rowsin a large table. This threshold percentage varies greatly, however, according to therelative speed of a table scan and how clustered the row data is about the indexkey. The faster the table scan, the lower the percentage; the more clustered the rowdata, the higher the percentage.Index columns that are used for joins to improve join performance.Primary and unique keys automatically have indexes, but you might want tocreate an index on a foreign key. See "Foreign Key" on page 4-6 for moreinformation.■ Small tables do not require indexes; if a query is taking too long, then the tablemight have grown from small to large.Some columns are strong candidates for indexing. Columns with one or more of thefollowing characteristics are good candidates for indexing:■■■Values are unique in the column, or there are few duplicates.There is a wide range of values (good for regular indexes).The column contains many nulls, but queries often select all rows having a value.In this case, a comparison that matches all the non-null values, such as:WHERE COL_X >= -9.99 *power(10,125)is preferable toWHERE COL_X IS NOT NULL4-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
Managing IndexesThis is because the first uses an index on COL_X (assuming that COL_X is anumeric column).Columns with the following characteristics are less suitable for indexing:■ There are many nulls in the column and you do not search on the non-null values.The size of a single index entry cannot exceed roughly one-half (minus someoverhead) of the available space in the data block. Consult with the databaseadministrator for assistance in determining the space required by an index.4.3.3.2 Limit the Number of Indexes for Each TableThe more indexes, the more overhead is incurred as the table is altered. When rows areinserted or deleted, all indexes on the table must be updated. When a column isupdated, all indexes on the column must be updated.You must weigh the performance benefit of indexes for queries against theperformance overhead of updates. For example, if a table is primarily read-only, youmight use more indexes; but, if a table is heavily updated, you might use fewerindexes.4.3.3.3 Choose the Order of Columns in Composite IndexesAlthough you can specify columns in any order in the CREATE INDEX command, theorder of columns in the CREATE INDEX statement can affect query performance. Ingeneral, you should put the column expected to be used most often first in the index.You can create a composite index (using several columns), and the same index can beused for queries that reference all of these columns, or just some of them.For example, assume the columns of the vendor_parts table are as follows:vendor_id part_no unit_cost1010 10-440 0.271010 10-457 5.101012 08-300 1.191012 10-440 0.251012 10-441 0.391012 10-457 4.961220 08-300 1.331292 10-457 5.29Assume that there are five vendors, and each vendor has about 1000 parts. Supposethat the vendor_parts table is commonly queried by <strong>SQL</strong> statements such as thefollowing:SELECT * FROM vendor_partsWHERE part_no = 457 AND vendor_id = 1012;To increase the performance of such queries, you might create a composite indexputting the most selective column first; that is, the column with the most values:CREATE INDEX ind_vendor_id ON vendor_parts (part_no, vendor_id);Composite indexes speed up queries that use the leading portion of the index. So inthis example, queries with WHERE clauses using only the part_no column also note aperformance gain. Because there are only five distinct values, placing a separate indexon vendor_id would serve no purpose.Database Objects: Usage Information 4-9
Managing Views4.4 Managing Views4.3.3.4 Drop Indexes That Are No Longer RequiredYou might drop an index if:■■It does not speed up queries. The table might be very small, or there might bemany rows in the table but very few index entries.The queries in your applications do not use the index.■ The index must be dropped before being rebuilt.You cannot drop an index which is created through a constraint. You must drop theconstraint and then the index is dropped also.If you drop a table, then all associated indexes are dropped.To drop an index, the index must be contained in your schema or you must have theDROP ANY INDEX system privilege.Views are customized presentations of data in one or more tables or other views. Youcan think of them as stored queries. Views do not actually contain data, but insteadderive their data from the tables upon which they are based. These tables are referredto as the base tables of the view.Like tables, views can be queried, updated, inserted into, and deleted from, with somerestrictions. All operations performed on a view actually affect the base tables of theview. Views provide an additional level of security by restricting access to apredetermined set of rows and columns of a table. They also hide data complexity andstore complex queries.4.5 Managing SequencesA sequence is a database object similar to a pseudocolumn that generates uniquesequential values. These values are often used for primary and unique keys. Using asequence generator to provide the value for a primary key in a table is an easy way toguarantee that the key value is unique.You can refer to sequence values in <strong>SQL</strong> statements with these pseudocolumns:■CURRVAL: Returns the current value of a sequence■ NEXTVAL: Increments the sequence and returns the next valueYou must qualify CURRVAL and NEXTVAL with the name of the sequence, such asemployees_seq.CURRVAL or employees_seq.NEXTVAL.When you create a sequence, you can define its initial value and the incrementbetween its values. The first reference to NEXTVAL returns the initial value of thesequence. Subsequent references to NEXTVAL increment the sequence value by thedefined increment and return the new value. Any reference to CURRVAL alwaysreturns the current value of the sequence, which is the value returned by the lastreference to NEXTVAL.Before you use CURRVAL for a sequence in your session, you must first initialize thesequence with NEXTVAL.4-10 <strong>SQL</strong> <strong>Developer</strong> Online Help
Managing Synonyms4.6 Managing SynonymsA synonym is an alias for any schema object such as a table or view. Synonymsprovide an easy way to provide an alternative name for a database object and can beused to simplify <strong>SQL</strong> statements for database users. For example, you can create asynonym named emps as an alias for the employees table in the HR schema.If a table in an application has changed, such as the personnel table has replaced theemployees table, you can use the employees synonym to refer to the personneltable so that the change is transparent to the application code and the database users.Because a synonym is simply an alias, it does not require any storage in the databaseother than its definition.You can create both public and private synonyms. A public synonym is owned by thespecial user group named PUBLIC and every user in a database can access it. A privatesynonym is in the schema of a specific user who has control over its availability toothers.Database Objects: Usage Information 4-11
Managing Synonyms4-12 <strong>SQL</strong> <strong>Developer</strong> Online Help
5Data Types: Usage InformationThe topic discusses the data types used with <strong>Oracle</strong> Database. It contains the followingtopics:■ Overview of Data Types on page 5-1■ Storing Character Data on page 5-1■ Storing Numeric Data on page 5-2■ Storing Datetime Data on page 5-5See Also:■■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for complete reference informationon the <strong>SQL</strong> data types<strong>Oracle</strong> Database Concepts to learn about <strong>Oracle</strong> built-in data types5.1 Overview of Data TypesA data type associates a fixed set of properties with the values that can be used in acolumn of a table or in an argument of a procedure or function. These properties cause<strong>Oracle</strong> Database to treat values of one data type differently from values of anotherdata type. For example, <strong>Oracle</strong> Database can use the addition operator on values ofNUMBER data type, but not with values of some other data types. The data typessupported by <strong>Oracle</strong> Database include characters, numbers, and dates and times(known as datetime data types).To view the data types contained in a database table, such as the employees table,you can use Connections navigator or the <strong>SQL</strong>*Plus DESCRIBE. For information on the<strong>SQL</strong>*Plus DESCRIBE command, see <strong>SQL</strong>*Plus DESCRIBE Command.5.2 Storing Character DataThis topic contains the following topics:■■What are the Character Data Types?Choosing Between the Character Data Types5.2.1 What are the Character Data Types?You can use the following <strong>SQL</strong> data types to store alphanumeric data:■VARCHAR2 and NVARCHAR2 data types store variable-length character literals.Data Types: Usage Information 5-1
Storing Numeric Data■■NCHAR and NVARCHAR2 data types store variable-length Unicode character dataonly.CHAR and NCHAR data types store fixed-length character literals.5.2.2 Choosing Between the Character Data TypesWhen deciding which data type to use for a column that will store alphanumeric datain a table, consider the following points of distinction:■■■5.3 Storing Numeric DataSpace usageTo store data more efficiently, use the VARCHAR2 data type. The CHAR data typeblank-pads and stores trailing blanks up to a fixed column length for all columnvalues, whereas the VARCHAR2 data type does not add extra blanks.Comparison semanticsUse the CHAR data type when you require ANSI compatibility in comparisonsemantics (when trailing blanks are not important in string comparisons). Use theVARCHAR2 when trailing blanks are important in string comparisons.Future compatibilityThe CHAR and VARCHAR2 data types are fully supported.This topic contains the following topics:■■■What Are the Numeric Data Types?Using NUMBER Data TypesUsing Floating-Point Number Formats5.3.1 What Are the Numeric Data Types?The following <strong>SQL</strong> data types store numeric data:■■NUMBERSee Also:■■BINARY_FLOAT<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on data types<strong>Oracle</strong> Database Globalization Support Guide for information onglobalization supportSee Also: <strong>Oracle</strong> Database <strong>SQL</strong> Reference for more information oncomparison semantics for these data types■ BINARY_DOUBLEUse the NUMBER data type to store integers and real numbers in a fixed-point orfloating-point format. Numbers using this data type are guaranteed to be portableamong different <strong>Oracle</strong> Database platforms. For nearly all cases where you need tostore numeric data, you would use the NUMBER data type.<strong>Oracle</strong> Database provides the numeric BINARY_FLOAT and BINARY_DOUBLE datatypes exclusively for floating-point numbers. They support all of the basicfunctionality provided by the NUMBER data type. However, while NUMBER uses5-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
Storing Numeric Datadecimal precision, BINARY_FLOAT and BINARY_DOUBLE use binary precision. Thisenables faster arithmetic calculations and usually reduces storage requirements.See Also:■■<strong>Oracle</strong> Database Concepts for information about the internal formatfor the NUMBER data type<strong>Oracle</strong> Database <strong>SQL</strong> Reference for more information about theNUMBER, BINARY_FLOAT, and BINARY_DOUBLE data typesformats5.3.2 Using NUMBER Data TypesThe NUMBER data type stores zero as well as positive and negative fixed numbers withabsolute values from 1.0 x 10 -130 to (but not including) 1.0 x 10 126 . If you specify anarithmetic expression whose value has an absolute value greater than or equal to 1.0 x10 126 , then <strong>Oracle</strong> returns an error. Each NUMBER value requires from 1 to 22 bytes.When you specify a fixed-point number use the following form to specify the precisionand scale of the number:NUMBER(precision, scale)Precision and scale are defined as follows:■ Precision is the total number of significant decimal digits, where the mostsignificant digit is the left-most nonzero digit, and the least significant digit is theright-most known digit. For examples, see Table 5–1 on page 5-4.■ Scale is the number of digits from the decimal point to the least significant digit.The scale can range from -84 to 127. For examples, see Table 5–1 on page 5-4.– Positive scale is the number of significant digits to the right of the decimalpoint to and including the least significant digit.– Negative scale is the number of significant digits to the left of the decimalpoint, to but not including the least significant digit. For negative scale theleast significant digit is on the left side of the decimal point, because the actualdata is rounded to the specified number of places to the left of the decimalpoint. For example, a specification of (10,-2) means to round to hundreds.Scale can be greater than precision, most commonly when e notation is used. Whenscale is greater than precision, the precision specifies the maximum number ofsignificant digits to the right of the decimal point. For example, a column defined asNUMBER(4,5) requires a zero for the first digit after the decimal point and rounds allvalues past the fifth digit after the decimal point.It is good practice to specify the scale and precision of a fixed-point number columnfor extra integrity checking on input. Specifying scale and precision does not force allvalues to a fixed length. If a value exceeds the precision, then <strong>Oracle</strong> returns an error. Ifa value exceeds the scale, then <strong>Oracle</strong> rounds it.Specify an integer using the following form:NUMBER(p)This represents a fixed-point number with precision p and scale 0 and is equivalent toNUMBER(p,0).Specify a floating-point number using the following form:NUMBERData Types: Usage Information 5-3
Storing Numeric DataThe absence of precision and scale designators specifies the maximum range andprecision for an <strong>Oracle</strong> number.Table 5–1 show how <strong>Oracle</strong> stores data using different values for precision and scale.Table 5–1Storage of Scale and PrecisionActual Data Specified As Stored As123.89 NUMBER 123.89123.89 NUMBER(3) 124123.89 NUMBER(6,2) 123.89123.89 NUMBER(6,1) 123.9123.89 NUMBER(3) exceeds precision123.89 NUMBER(4,2) exceeds precision123.89 NUMBER(6,-2) 100.01234 NUMBER(4,5) .01234.00012 NUMBER(4,5) .00012.000127 NUMBER(4,5) .00013.0000012 NUMBER(2,7) .0000012.00000123 NUMBER(2,7) .00000121.2e-4 NUMBER(2,5) 0.000121.2e-5 NUMBER(2,5) 0.000015.3.3 Using Floating-Point Number FormatsThe BINARY_FLOAT and BINARY_DOUBLE data types store floating-point data in the32-bit IEEE 754 format and the double precision 64-bit IEEE 754 format respectively.Compared to the <strong>Oracle</strong> NUMBER data type, arithmetic operations on floating-pointdata are usually faster for BINARY_FLOAT and BINARY_DOUBLE. Also, high-precisionvalues require less space when stored as BINARY_FLOAT and BINARY_DOUBLE.The floating-point number system is a common way of representing and manipulatingnumeric values in computer systems. The value 4.32682E-21F is an example of aBINARY_FLOAT data type.Floating-point numbers can have a decimal point anywhere from the first to the lastdigit or can have no decimal point at all. An exponent may optionally be usedfollowing the number to increase the range (for example, 1.777 e -20 ). A scale value isnot applicable to floating-point numbers, because the number of digits that can appearafter the decimal point is not restricted.Binary floating-point numbers differ from NUMBER in the way the values are storedinternally by <strong>Oracle</strong> Database. Values are stored using decimal precision for NUMBER.All literals that are within the range and precision supported by NUMBER are storedexactly as NUMBER. Literals are stored exactly because literals are expressed usingdecimal precision (the digits 0 through 9). Binary floating-point numbers are storedusing binary precision (the digits 0 and 1). Such a storage scheme cannot represent allvalues using decimal precision exactly. Frequently, the error that occurs whenconverting a value from decimal to binary precision is undone when the value isconverted back from binary to decimal precision. The literal 0.1 is such an example.5-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
Storing Datetime Data5.3.3.1 BINARY_FLOATBINARY_FLOAT is a 32-bit, single-precision floating-point number data type. EachBINARY_FLOAT value requires 5 bytes, including a length byte.5.3.3.2 BINARY_DOUBLEBINARY_DOUBLE is a 64-bit, double-precision floating-point number data type. EachBINARY_DOUBLE value requires 9 bytes, including a length byte.In a NUMBER column, floating point numbers have decimal precision. In a BINARY_FLOAT or BINARY_DOUBLE column, floating-point numbers have binary precision.The binary floating-point numbers support the special values infinity and NaN (not anumber).You can specify floating-point numbers within the limits listed in Table 5–2 onpage 5-5.Table 5–25.4 Storing Datetime DataThis topic contains the following topics:■■Using DATE and TIMESTAMP Data TypesManipulating the DATE and TIME Formats5.4.1 Using DATE and TIMESTAMP Data Types<strong>Oracle</strong> Database supports the following datetime data types:■■■■DATETIMESTAMPFloating Point Number LimitsValue Binary-Float Binary-DoubleMaximum positive finite value 3.40282E+38F 1.79769313486231E+308Minimum positive finite value 1.17549E-38F 2.22507485850720E-308TIMESTAMP WITH TIME ZONETIMESTAMP WITH LOCAL TIME ZONESee Also:■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on DATE,TIMESTAMP, TIMESTAMP WITH TIME ZONE, and TIMESTAMPWITH LOCAL TIME ZONE data types5.4.1.1 Using the DATE Data TypeUse the DATE data type to store point-in-time values (dates and times) in a table. Anapplication that specifies the time for a job might use the DATE data type.The DATE data type stores the century, year, month, day, hours, minutes, and seconds.The valid date range is from January 1, 4712 BC to December 31, 9999 AD.Data Types: Usage Information 5-5
Storing Datetime Data5.4.1.2 Using the TIMESTAMP Data TypeUse the TIMESTAMP data type to store values that are precise to fractional seconds. Anapplication that must decide which of two events occurred first might useTIMESTAMP.5.4.1.3 Using the TIMESTAMP WITH TIME ZONE Data TypeBecause TIMESTAMP WITH TIME ZONE can also store time zone information, it isparticularly suited for recording date information that must be gathered orcoordinated across geographic regions.5.4.1.4 Using the TIMESTAMP WITH LOCAL TIME ZONE Data TypeUse TIMESTAMP WITH LOCAL TIME ZONE when the time zone is not significant. Forexample, you might use it in an application that schedules teleconferences, whereparticipants each see the start and end times for their own time zone.The TIMESTAMP WITH LOCAL TIME ZONE type is appropriate for two-tierapplications in which you want to display dates and times that use the time zone ofthe client system. It is generally inappropriate in three-tier applications because datadisplayed in a Web browser is formatted according to the time zone of the Web server,not the time zone of the browser. The Web server is the database client, so its local timeis used.5.4.1.5 Representing the Difference Between Datetime ValuesUse the INTERVAL DAY TO SECOND data type to represent the precise differencebetween two datetime values. For example, you might use this value to set a reminderfor a time 36 hours in the future or to record the time between the start and end of arace. To represent long spans of time with high precision, you can use a large value forthe days portion.Use the INTERVAL YEAR TO MONTH data type to represent the difference betweentwo datetime values, where the only significant portions are the year and the month.For example, you might use this value to set a reminder for a date 18 months in thefuture, or check whether 6 months have elapsed since a particular date.<strong>Oracle</strong> Database stores dates in its own internal format which is fixed-length fields ofseven bytes each, corresponding to century, year, month, day, hour, minute, andsecond.5.4.2 Manipulating the DATE and TIME FormatsFor input and output of dates, the standard <strong>Oracle</strong> Database default date format isDD-MON-RR. The RR datetime format element enables you store 20th century dates inthe 21st century by specifying only the last two digits of the year.Time is stored in a 24-hour format as HH24:MI:SS. By default, the time in a DATEcolumn is 12:00:00 A.M. (midnight) if no time portion is entered or if the DATE istruncated. In a time-only entry, the date portion defaults to the first day of the currentmonth.You can change the current default date or time format for a specific date or timestampwith the use the TO_DATE or TO_TIMESTAMP function with a format mask, such as:TO_DATE('27-OCT-98', 'DD-MON-RR')TO_DATE('15-NOV-05 10:56 A.M.','DD-MON-YY HH:MI A.M.')TO_TIMESTAMP ('10-Sep-05 14:10:10.123000','DD-Mon-RR HH24:MI:SS.FF')5-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
Storing Datetime Data<strong>Oracle</strong> Database provides various functions for calculating and converting datetimedata. For examples in <strong>SQL</strong> statements, see Using Date Functions.Be careful when using a date format such as DD-MON-YY. The YY indicates the year inthe current century. For example, 31-DEC-92 is December 31, 2092, not 1992 asyou might expect. If you want to indicate years in any century other than the currentone, use a format mask such as the default RR.You can use the following techniques to change the default date format on a moreglobal level:■To change on an instance-wide basis, use the NLS_DATE_FORMAT parameter.■ To change during a session, use the ALTER SESSION statement.For more information on these techniques, see Working in a Global Environment.See Also:■■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for more information about date andtime formats<strong>Oracle</strong> Database Concepts for information about Julian dates. <strong>Oracle</strong>Database Julian dates might not be compatible with Julian datesgenerated by other date algorithms.Data Types: Usage Information 5-7
Storing Datetime Data5-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
6<strong>SQL</strong>: Usage InformationThis topic discusses how to use <strong>SQL</strong> with <strong>Oracle</strong> Database. It includes the followingtopics:■■■■■■Overview of <strong>SQL</strong>Retrieving Data With QueriesManipulating Data With <strong>SQL</strong> StatementsTransaction Control StatementsUsing Pseudocolumns, Sequences, and <strong>SQL</strong> FunctionsUsing <strong>SQL</strong> Data Definition Language StatementsSee Also:■■■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for detailed information about <strong>SQL</strong>statements and other parts of <strong>SQL</strong>, such as operators, functions,and format models.<strong>Oracle</strong> Database Concepts for conceptual information on <strong>SQL</strong>.<strong>SQL</strong>*Plus User's Guide and Reference for information about<strong>SQL</strong>*Plus, <strong>Oracle</strong>'s version of <strong>SQL</strong>.■ <strong>Oracle</strong> Database Sample Schemas for information on the HR sampleschema that is used for examples.6.1 Overview of <strong>SQL</strong>6.1.1 Features of <strong>SQL</strong>Structured Query Language (<strong>SQL</strong>) is a database access, nonprocedural language.Users issue <strong>SQL</strong> statements or commands to perform various tasks, such as retrievingdata, and the <strong>SQL</strong> language compiler automatically handles how to navigate thedatabase and perform the desired task. All database operations are performed using<strong>SQL</strong>.This topic includes the following topics:■ Features of <strong>SQL</strong>■ Types of <strong>SQL</strong> StatementsWith <strong>SQL</strong> statements you can perform the following:■ Query, insert, update, and delete data in tables<strong>SQL</strong>: Usage Information 6-1
Retrieving Data With Queries■■■■Format, perform calculations on, store, and print from query resultsExamine table and object definitionsDevelop and run batch scriptsPerform database administration6.1.2 Types of <strong>SQL</strong> StatementsAll operations performed on the information in an <strong>Oracle</strong> database are run using <strong>SQL</strong>statements. A statement consists partially of <strong>SQL</strong> reserved words, which have specialmeaning in <strong>SQL</strong> and cannot be used for any other purpose. For example, SELECT andUPDATE are reserved words and cannot be used as table names.A <strong>SQL</strong> statement is an instruction. The statement must be the equivalent of a complete<strong>SQL</strong> sentence, as in:SELECT last_name, department_id FROM employees;<strong>Oracle</strong> <strong>SQL</strong> statements are divided into several categories:■ Data Manipulation Language (DML) StatementsThese statements query, insert, update, delete data in tables.■ Transaction Control StatementsThese statements commit or rollback the processing of transactions. A group ofchanges that you make is referred to as a transaction.■Data Definition Language (DDL) StatementsThese create, alter, and drop database objects.6.2 Retrieving Data With QueriesYou can retrieve data from rows stored one or more database tables or views with aquery using the <strong>SQL</strong> SELECT statement. The SELECT statement retrieves the all of orpart of the column data from rows depending on the conditions that you specify inWHERE clauses. The group of columns that are selected from a table is referred to as theSELECT list.■■■■■■Displaying Data Using the SELECT StatementUsing Character Literals in <strong>SQL</strong> StatementsUsing a Column Alias to Change Headings When Selecting DataRestricting Data Using the WHERE ClauseSorting Data Using the ORDER BY ClauseDisplaying Data From Multiple Tables6.2.1 Displaying Data Using the SELECT StatementWith the <strong>SQL</strong> SELECT statement, you can query and display data of tables in adatabase.Example 6–1 shows how to use SELECT to retrieve data from the employees table. Inthis example, the data for all columns in a row (record) of the employees table isretrieved with the use of the wildcard (*) notation. Note the use of comments to6-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
Retrieving Data With Queriesdocument the <strong>SQL</strong> statements. The comments (or remarks) in this example begin with--.Example 6–1Using SELECT to Retrieve Data-- the following uses the wildcard * to retrieve all the columns of data in-- all rows of the employees tableSELECT * FROM employees;Example 6–2 shows how to use SELECT to retrieve the data for specific columns of theemployees table. In this example, you explicitly enter the column names in theSELECT statement.Example 6–2Using SELECT to Retrieve Data From Specific Columns-- the following retrieves the data in columns employee_id, last_name, first_nameSELECT employee_id, last_name, first_name FROM employees;See Also:■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for detailed information on the <strong>SQL</strong>SELECT statement.6.2.2 Using Character Literals in <strong>SQL</strong> StatementsMany <strong>SQL</strong> statements, functions, expressions, and conditions require you to specifycharacter literal values. You can specify character literals with the following notations:■Character literals with the 'text' notation, as in the literals 'users01.dbf'and 'Muthu''s computer'.■ National character literals with the N'text' or n'text' notation, where N or nspecifies the literal using the national character set. For example, N'résumé' is aNational character literal.For information on unicode literals, see Unicode String Literals.6.2.2.1 Quoting Character LiteralsBy default you must quote character literals in single-quotes, as in 'Hello'. Thistechnique can sometimes be inconvenient if the text itself contains single quotes. Insuch cases, you can also use the Q-quote mechanism, which enables you to specify qor Q followed by a single quote and then another character to be used as the quotedelimiter. For example, the literal q'#it's the "final" deadline#' uses thepound sign (#) as a quote delimiter for the string it's the "final" deadline.The Q-quote delimiter can be any single- or multibyte character except space, tab, andreturn. If the opening quote delimiter is a [, {, , or ) character. In all other cases, theopening and closing delimiter must be the identical character.The following character literals use the alternative quoting mechanism:q'(name LIKE '%DBMS_%%')'q''q'"name like '['"'nq'ïŸ1234ï'<strong>SQL</strong>: Usage Information 6-3
Retrieving Data With QueriesSee Also:■■<strong>Oracle</strong> Database Globalization Support Guide to learn about nationalcharacter sets<strong>Oracle</strong> Database <strong>SQL</strong> Reference to learn about character literals6.2.3 Using a Column Alias to Change Headings When Selecting DataWhen displaying the result of a query, <strong>SQL</strong> normally uses the name of the selectedcolumn as the column heading. You can change a column heading by using a columnalias to make the heading more descriptive and easier to understand.You can specify the alias after the column name in the SELECT list using a space as aseparator. If the alias contains spaces or special characters (such as # or $), or if it iscase-sensitive, enclose the alias in double quotation marks (" ").Example 6–3 shows the use of a column alias to provide more description for eachheading of the columns selected in a query.Example 6–3Using a Column Alias-- the following retrieves the data in columns employee_id, last_name, first_name-- and provides column aliases for more descriptive headings of the columnsSELECT employee_id "Employee Id number", last_name "Employee last name",first_name "Employee first name" FROM employees;6.2.4 Restricting Data Using the WHERE ClauseThe WHERE clause uses comparison operators to identify specific rows in a table. Whenused with the SELECT statement, you can selectively retrieve rows from a table ratherthan retrieving all rows of a table.Comparison operators include those listed in Table 6–1.Table 6–1OperatorComparison OperatorsDefinition=, !=, test for equal, not equal, not equal>, >=,
Retrieving Data With Queries-- this retrieves employees with managers with Ids between 122 and 125 inclusiveSELECT * FROM employees WHERE manager_id BETWEEN 122 AND 125;-- this uses the wildcard % to retrieve employee data-- where the last name contains mar somewhere in the nameSELECT employee_id, last_name FROM employees WHERE last_name LIKE '%mar%';-- this retrieves employees where the last name starts with MarSELECT employee_id, last_name FROM employees WHERE last_name LIKE 'Mar%';-- this retrieves employees where the commission percentage is not nullSELECT employee_id, last_name FROM employees WHERE commission_pct IS NOT NULL;-- the following retrieves data where the employee_id equals 125, 130, or 135SELECT employee_id, last_name, first_name FROM employeesWHERE employee_id IN (125, 130, 135);See Also:■ <strong>Oracle</strong> Database <strong>SQL</strong> Reference for detailed information on usingthe WHERE clause.6.2.5 Sorting Data Using the ORDER BY ClauseYou can use SELECT with the ORDER BY clause to retrieve and display rows from atable ordered (sorted) by a specified column in the table. The specified column in theORDER BY clause does not have to be in the select-list of columns that you want todisplay.You can specify the sort order ASC for ascending or DESC for descending. The defaultsort order is ascending, which means:■ Numeric values are displayed with the lowest values first, such as 1 to 999.■■Character values are displayed in alphabetical order, such as A first and Z last.Date values are displayed with the earliest value first, such as 01-JUN-93 before01-JUN-95.Null (empty) values are displayed last for ascending sequences and first fordescending sequences.Example 6–5 shows how to use SELECT with the ORDER BY clause to retrieve anddisplay rows from the employees table ordered (sorted) by specified columns.Example 6–5Using SELECT With ORDER BY-- the following retrieves rows with manager_id = 122 ordered by employee_id-- the order is the default ascending order, lowest employee_id displays firstSELECT * FROM employees WHERE manager_id = 122 ORDER BY employee_id;-- the following retrieves rows ordered by manager_id-- the order is specified as descending, highest manager_id displays firstSELECT employee_id, last_name, first_name, manager_id FROM employeesORDER BY manager_id DESC;See Example 6–20 on page 6-14 for the use of ORDER BY with the GROUP BY clause.<strong>SQL</strong>: Usage Information 6-5
Retrieving Data With QueriesSee Also:■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for detailed information on usingORDER BY with SELECT.6.2.6 Displaying Data From Multiple TablesYou can use SELECT to display data from the multiple tables. This process is referredto as joining the tables. In a join, multiple tables share a similar column.When you retrieve data from multiple tables, you can explicitly identify which table acolumn belongs to. This is important when tables contain columns with the samename. You can use the complete table name to explicitly identify a column, such asemployees.employee_id, or a table alias. Note the use of the table aliases (d, e, andl) to explicitly identify the columns by table in the <strong>SQL</strong> statement. The alias is definedin the FROM clause of the <strong>SQL</strong> statement. A table alias is used to simply and reduce thesize of the <strong>SQL</strong> code.Example 6–6 is an example of querying data from joined tables using ANSI syntax.The first SELECT joins two tables and the second SELECT joins three tables.Example 6–6Selecting Data From Multiple Tables With the ANSI Join Syntax-- the following SELECT statements retrieve data from two tables-- that have a corresponding column (department_id)-- this join uses ANSI syntax, note the use of JOIN and ONSELECT e.employee_id, e.last_name, e.first_name, e.department_id,d.department_name FROM employees eJOIN departments d ON e.department_id = d.department_id;-- the following SELECT retrieves data from three tables-- two tables have the corresponding column department_id and-- two tables have the corresponding column location_idSELECT e.employee_id, e.last_name, e.first_name, e.department_id,d.department_name, d.location_id, l.country_id FROM employees eJOIN departments d ON e.department_id = d.department_idJOIN locations l ON d.location_id = l.location_id;In Example 6–7 the joins use the <strong>Oracle</strong>-proprietary syntax. There is no performancedifference between the ANSI and <strong>Oracle</strong> syntax.Example 6–7 Using SELECT to Display Data From Multiple Tables-- the following SELECT statements retrieve data from two tables-- that have a corresponding column (department_id)-- note that the employees table has been aliased to e and departments to dSELECT e.employee_id, e.last_name, e.first_name, e.department_id,d.department_name FROM employees e, departments dWHERE e.department_id = d.department_id;-- the following SELECT retrieves data from three tables-- two tables have the corresponding column department_id and-- two tables have the corresponding column location_idSELECT e.employee_id, e.department_id, d.department_name, d.location_id,l.country_id FROM employees e, departments d, locations lWHERE e.department_id = d.department_id AND d.location_id = l.location_id;6-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
Manipulating Data With <strong>SQL</strong> StatementsSee Also:■"Joins" in <strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on usingSELECT with multiple tables.6.3 Manipulating Data With <strong>SQL</strong> StatementsData manipulation language (DML) statements query or manipulate data in existingschema objects. They enable you to:■■Add new rows of data into a table or view (INSERT)Change column values in existing rows of a table or view (UPDATE)■ Remove rows from tables or views (DELETE)DML statements are the most frequently used <strong>SQL</strong> statements.■ Adding Data With the INSERT Statement■ Updating Data With the UPDATE Statement■ Deleting Data With the DELETE Statement6.3.1 Adding Data With the INSERT StatementYou can use the <strong>SQL</strong> INSERT statement to add a row of data to a table. The datainserted must be valid for the data type and size of each column of the table.Example 6–8 shows how to use INSERT to add a row to the employees table. In thefirst INSERT statement, values are inserted into all columns in a row of the table.When you insert data into the columns, you must provide data values that are validfor the data type and size of the column.In the second INSERT statement, values are inserted only into the specified columns ofthe table and the remaining columns are set to NULL. If the those remaining columnshad been specified with a NOT NULL constraint for the table, an error would have beenraised. For information on constraints, see "Managing Tables" and ColumnConstraints.Example 6–8Using the INSERT Statement-- the following inserts data for all the columns in a rowINSERT INTO employees VALUES(300, 'Enrique', 'Belden', 'enrique.belden', '555.111.2222','01-AUG-05', 'AC_MGR', 9000, .1, 101, 110);-- the following inserts data into the columns specified by name-- NULLs are inserted in those columns not explicitly namedINSERT INTO employees (employee_id, last_name, email, hire_date, job_id, salary)VALUES (301, 'Doe', 'john.doe', '31-AUG-05', 'SH_CLERK', 2400);-- the following shows the rows were inserted beginning with 300SELECT employee_id, last_name FROM employees WHERE employee_id >= 300;See Also:■ <strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the INSERTstatement.<strong>SQL</strong>: Usage Information 6-7
Transaction Control Statements6.3.2 Updating Data With the UPDATE StatementYou can use the <strong>SQL</strong> UPDATE statement to update data in a row of a table. Theupdated data must be valid for the data type and size of each column of the table.Example 6–9 shows how to use UPDATE to update data in the employees table. Notethe use of the use of multiplication operator * to calculate a new salary. Forinformation on arithmetic operators, See "Using Arithmetic Operators" on page 6-12.Example 6–9Using the UPDATE StatementSELECT salary FROM employees WHERE employee_id = 301;-- update the salary for employee 301, multiply the salary by 105%UPDATE employees SET salary = salary * 1.05 WHERE employee_id = 301;-- the following should show a change in salarySELECT salary FROM employees WHERE employee_id = 301;See Also:■ <strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the UPDATEstatement.6.3.3 Deleting Data With the DELETE StatementWith the <strong>SQL</strong> DELETE statement you can delete all or specific rows in a table.When you delete all the rows in a table, the empty table still exists. If you want toremove the entire table from the database, use the <strong>SQL</strong> DROP statement. See "Droppinga Table With <strong>SQL</strong>" on page 6-17.Example 6–10 shows how to use DELETE to delete selected rows in the employeestable. Note the use of the WHERE clause. Without that clause, all the rows would bedeleted.Example 6–10 Using the DELETE StatementDELETE FROM employees WHERE employee_id = 300 OR employee_id = 301;-- the following query should not find any recordsSELECT * FROM employees WHERE employee_id = 300 OR employee_id = 301;If you accidentally delete rows, you can restore the rows with the ROLLBACKstatement. See "Rolling Back a Transaction" on page 6-9.See Also:■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the DELETEstatement.6.4 Transaction Control StatementsTransaction control statements manage the changes made by DML statements andgroup DML statements into transactions. They enable you to:■■Make a transaction's changes permanent (COMMIT)Undo the changes in a transaction, either since the transaction started or since asavepoint (ROLLBACK)6-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
Transaction Control StatementsThis topic includes the following topics:■■Committing Transaction ChangesRolling Back a Transaction6.4.1 Committing Transaction ChangesThe <strong>SQL</strong> COMMIT statement saves any changes you have made to the database. Whena COMMIT has been executed, all the recent changes since the last COMMIT, or since youlogged on as the current user, are saved.Example 6–11 shows how to use COMMIT to commit (save) changes to the employeestable in the database.Example 6–11 Using the COMMIT Statement-- add a row and then update the dataINSERT INTO employees (employee_id, last_name, email, hire_date, job_id, salary)VALUES (301, 'Doe', 'john.doe', '31-AUG-05', 'SH_CLERK', 2400);UPDATE employees SET salary = salary*1.10 WHERE employee_id = 301;-- commit (save) the INSERT and UPDATE changes in the databaseCOMMIT;See Also:■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the COMMITstatement.6.4.2 Rolling Back a TransactionYou can use the <strong>SQL</strong> ROLLBACK statement to rollback (undo) any changes you made tothe database before a COMMIT has been executed.Example 6–12 shows how to use ROLLBACK to rollback the deletions made to theemployees table. Note that the ROLLBACK was issued before a COMMIT was executed.Example 6–12Using the ROLLBACK Statement-- delete a row (record)DELETE FROM employees WHERE last_name = 'Doe';-- rollback the delete statement because the previous DELETE was incorrectROLLBACK;-- the following is validSELECT * FROM employees WHERE last_name = 'Doe';See Also:■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the ROLLBACKstatement.<strong>SQL</strong>: Usage Information 6-9
Using Pseudocolumns, Sequences, and <strong>SQL</strong> Functions6.5 Using Pseudocolumns, Sequences, and <strong>SQL</strong> FunctionsWith <strong>SQL</strong> built-in functions you can manipulate character, numeric, and date data in<strong>SQL</strong> statements. You can also perform operations on a collection of data with theaggregate functions.Pseudocolumns are built-in values that provide specific information with a query andare similar to functions without arguments. However, functions without argumentstypically return the same value for every row in the result set, whereaspseudocolumns typically return a different value for each row.This topic includes the following topics:■ Using Pseudocolumns With <strong>SQL</strong>■ Using Sequences■ Using Character Functions■ Using Arithmetic Operators■ Using Numeric Functions■ Using Date Functions■ Using Aggregate FunctionsSee Also:■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for detailed information on <strong>SQL</strong>functions.6.5.1 Using Pseudocolumns With <strong>SQL</strong>A pseudocolumns is similar to a table column, but is not actually stored in a table. Apseudocolumn returns a value so it is similar to a function without argument. <strong>Oracle</strong>Database provides several pseudocolumns, such as the ROWNUM, SYSDATE, and USER.The ROWNUM pseudocolumn returns a number indicating the order in which <strong>Oracle</strong>selects the row in a query. SYSDATE returns the current date and time set for theoperating system on which the database resides. USER returns the name of the username that is currently logged in.Example 6–13 show the use of the ROWNUM, SYSDATE, and USER pseudocolumns. Notethe use of the table DUAL, which is automatically created by <strong>Oracle</strong> Database for use asa dummy table in <strong>SQL</strong> statements.Example 6–13 Using Pseudocolumns-- the following statement displays the SYSDATE, which is the current system date-- NOW is a column alias for display purposes-- DUAL is a dummy table with one row simply used to complete the SELECT statementSELECT SYSDATE "NOW" FROM DUAL;-- display the name of the current user, the user name should be HRSELECT USER FROM DUAL;-- using ROWNUM < 10 limits the number of rows returned to less than 10SELECT employee_id, hire_date, SYSDATE FROM employees WHERE ROWNUM < 10;See Example 6–18 on page 6-14 for another example of the use of SYSDATE.6-10 <strong>SQL</strong> <strong>Developer</strong> Online Help
Using Pseudocolumns, Sequences, and <strong>SQL</strong> Functions6.5.2 Using SequencesA sequence is a database object similar to a pseudocolumn that generates uniquesequential values, often used for primary and unique keys. You can refer to sequencevalues in <strong>SQL</strong> statements with the CURRVAL and NEXTVAL pseudocolumns.To generate a sequence number, you call the sequence using the CURRVAL or NEXTVALkeywords. You must qualify CURRVAL and NEXTVAL with the name of the sequence,such as employees_seq.CURRVAL or employees_seq.NEXTVAL. Before you useCURRVAL for a sequence in your session, you must first initialize the sequence withNEXTVAL.Example 6–14 shows an example of the use of the employees_seq sequence with theemployee_id of the employees table. The employees_seq sequence is part of theHR schema and had been created for use with the employees table. When a sequenceis intended to be used with a specific table, it is a good practice to include the name ofthe table in the sequence name.Example 6–14 Using Sequences-- first initialize the employees_seq sequence with NEXTVALSELECT employees_seq.NEXTVAL FROM DUAL;-- after initializing the sequence, use CURRVAL as the next value in the sequenceINSERT INTO employees VALUES(employees_seq.CURRVAL, 'Belinda', 'Vernal', 'belinda.vernal', '555.111.2342','15-AUG-05', 'ST_CLERK', 6000, NULL, 124, 50);-- query the employees table to check the current value of the sequence-- which was inserted used as employee_id in the previous INSERT statementSELECT employee_id, last_name FROM employees WHERE last_name = 'Vernal';6.5.3 Using Character Functions<strong>Oracle</strong> Database provides a set of character functions that you can use in your <strong>SQL</strong>statements to customize the character values. With character functions, you canperform operations that upper case, lower case, trim blanks from, and concatenatecharacter data.Example 6–15 shows how to use character functions on character data.Example 6–15Using Character Functions-- you can use the UPPER function to display uppercase data, LOWER for lowercaseSELECT employee_id, UPPER(last_name), LOWER(first_name) FROM employees;-- you can use CONCAT function to concatenate character dataSELECT CONCAT('Last name: ', last_name) FROM employees;-- you can use RTRIM and LTRIM to remove spaces from the beginning or end of-- character data. Note the use of concatenation operator ||SELECT employee_id, RTRIM(first_name) || ' ' || LTRIM(last_name) FROM employees;-- you can TRIM to remove spaces from both the beginning and endSELECT employee_id, TRIM(last_name) || ', ' || TRIM(first_name) FROM employees;-- you can format the system date (SYSDATE) as a character string-- with various format masks and then display-- the following displays September 21 2005<strong>SQL</strong>: Usage Information 6-11
Using Pseudocolumns, Sequences, and <strong>SQL</strong> FunctionsSELECT TO_CHAR(SYSDATE, 'fmMonth DD YYYY') "Today" FROM DUAL;-- the following displays 21-SEP-2005 ADSELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY AD') "Today" FROM DUAL;6.5.4 Using Arithmetic OperatorsYou can use arithmetic operators to create expressions for calculations on data intables. The arithmetic operators include:■■■+ for addition- for subtraction* for multiplication■ / for divideIn an arithmetic expression, multiplication and division are evaluated first, thenaddition and subtraction. When operators have equal precedence, the expression isevaluated left to right. It is best to include parentheses to explicitly determine the orderof operators and provide clarity in the expression.Example 6–16 shows the use of arithmetic operators in expressions with the data in theemployees table. Note the use of a column alias to provide a more useful heading forthe displayed output.Example 6–16 Using Arithmetic Operators-- in the following query the commission is displayed as a percentate instead-- of the decimal that is stored in the databaseSELECT employee_id, (commission_pct * 100) "Commission %" FROM employees;-- in the following query, the proposed new annual salary is calculated-- for employees who report to the manager with Id 145SELECT employee_id, ((salary + 100) * 12) "Proposed new annual salary"FROM employees WHERE manager_id = 145;6.5.5 Using Numeric Functions<strong>Oracle</strong> Database provides a set of numeric functions that you can use in your <strong>SQL</strong>statements to manipulate the numeric values. With numeric functions, you canperform operations that upper case, lower case, trim blanks from, and concatenatecharacter data.Example 6–17 shows how to use numeric functions on numeric data in theemployees table.Example 6–17Using Numeric Functions-- you can use the ROUND function to round off numeric data, in this case to-- two decimal placesSELECT employee_id, ROUND(salary/30, 2) "Salary per day" FROM employees;-- you can use the TRUNC function to truncate numeric data, in this case to-- 0 decimal places; 0 is the default so TRUNC(salary/30) would be sameSELECT employee_id, TRUNC(salary/30, 0) "Salary per day" FROM employees;6-12 <strong>SQL</strong> <strong>Developer</strong> Online Help
Using Pseudocolumns, Sequences, and <strong>SQL</strong> Functions6.5.6 Using Date Functions<strong>Oracle</strong> Database provides various functions for calculating and converting datetimedata.See Also: <strong>Oracle</strong> Database <strong>SQL</strong> Reference for details about the datefunctionsPerforming Date Arithmetic<strong>Oracle</strong> Database provides a number of features to help with date arithmetic, so thatyou do not need to perform your own calculations on the number of seconds in a day,the number of days in each month, and so on. Some useful features include thefollowing:■■■■■■■■ADD_MONTHS function, which returns the date plus the specified number ofmonths.MONTHS_BETWEEN function, which returns the number of months between twodates.SYSDATE function, which returns the current date and time set for the operatingsystem on which the database resides.SYSTIMESTAMP function, which returns the system date, including fractionalseconds and time zone, of the system on which the database resides.TRUNC function, which when applied to a DATE value, trims off the time portionso that it represents the very beginning of the day (the stroke of midnight). Bytruncating two DATE values and comparing them, you can determine whetherthey refer to the same day. You can also use TRUNC along with a GROUP BY clauseto produce daily totals.Arithmetic operators such as + and -. For example, SYSDATE-7 refers to 7 daysbefore the current system date.INTERVAL data types, which enable you to represent constants when performingdate arithmetic rather than performing your own calculations. For example, youcan add or subtract INTERVAL constants from DATE values or subtract two DATEvalues and compare the result to an INTERVAL.Comparison operators such as >,
Using Pseudocolumns, Sequences, and <strong>SQL</strong> Functions■■■TO_TIMESTAMP, which converts character data to a value of TIMESTAMP datatypeTO_TIMESTAMP_TZ, which converts character data to a value of TIMESTAMPWITH TIME ZONE data typeTO_YMINTERVAL, which converts a character string to an INTERVAL YEAR TOMONTH typeExample 6–18 shows how to use date functions on date data.Example 6–18Using Date Functions-- in the following statement you can use MONTHS_BETWEEN to compute months-- employed for employees and then truncate the results to the whole month-- note the use of the label (alias) "Months Employed" for the computed columnSELECT employee_id, TRUNC(MONTHS_BETWEEN(SYSDATE, HIRE_DATE)) "Months Employed"FROM employees;-- the following displays the year hired for each employee idSELECT employee_id, EXTRACT(YEAR FROM hire_date) "Year Hired" FROM employees;Example 6–19 shows how to use date functions with format masks.Example 6–19Using Date Functions With Format Masks-- use TO_DATE with a format mask to display or enter dates differently than the-- current default date format-- the following displays 1998 with the 'DD-MON-RR' format maskSELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL;-- note that 'YY' in a format mask denotes the year in the current century-- the following displays 2098 with the 'DD-MON-YY' format maskSELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-YY') ,'YYYY') "Year" FROM DUAL;-- the following displays the date and time with a datetime format maskSELECT TO_TIMESTAMP ('10-Sep-05 14:10:10.123000', 'DD-Mon-RR HH24:MI:SS.FF')FROM DUAL;-- the following displays the system date and time with a format maskSELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Now" FROM DUAL;6.5.7 Using Aggregate FunctionsGroup functions operate on sets of rows to give one result per group. These sets maycomprise the entire table or the table split into groups.Example 6–18 shows how to use aggregate functions on collections of data in thedatabase. Aggregate functions include COUNT, MAX, MIN, and SUM. The GROUP BYclause is used to select groups of rows by a specified expression and returns one rowof summary information for each group.Example 6–20 Using Aggregate Functions-- you can use COUNT to count the employees with manager 122-- note the use of a column alias Employee CountSELECT COUNT(*) "Employee Count" FROM employees WHERE manager_id = 122;-- count the employees grouped by manager, also sort the groupsSELECT COUNT(*) "Employee Count", manager_id FROM employeesGROUP BY manager_id ORDER BY manager_id;6-14 <strong>SQL</strong> <strong>Developer</strong> Online Help
Using <strong>SQL</strong> Data Definition Language Statements-- you can use MIN to find the minimum salary for employees with manager 122SELECT MIN(salary) FROM employees WHERE manager_id = 122;-- this computes the minimum and maximum salary by job_id groups-- the job_ids groups are sorted in alphabetical orderSELECT MIN(salary), MAX(salary), job_id FROM employeesGROUP BY job_id ORDER BY job_id;6.6 Using <strong>SQL</strong> Data Definition Language StatementsData definition language (DDL) statements include CREATE, ALTER, and DROP fordefining database objects. When managing database objects, <strong>SQL</strong> <strong>Developer</strong> providesa simple and easy-to-use interface that can be utilized instead of <strong>SQL</strong> DDL statements.In this guide, some basic <strong>SQL</strong> DDL statements are used in the code examples and abrief description of some DDL statements are discussed here.This topic includes the following topics:■ Creating a Table With <strong>SQL</strong>■ Creating and Modifying an Index With <strong>SQL</strong>■ Creating and Modifying a Constraint With <strong>SQL</strong>■ Altering a Table With <strong>SQL</strong>■ Dropping a Table With <strong>SQL</strong>■ Creating and Dropping a Sequence■ Creating and Dropping a Synonym6.6.1 Creating a Table With <strong>SQL</strong>To create a database object, such as a table, use the <strong>SQL</strong> CREATE statement as shown inExample 6–21. When you create a table, you need to provide data types for eachcolumn. For more information about tables, see Managing Tables.Example 6–21Creating a Simple Table-- create a simple table for keeping track of birthdaysCREATE TABLE my_birthdays( first_name VARCHAR2(20),last_name VARCHAR2(25),bday_date DATE);Optionally, you can provide constraints as shown inExample 6–22. The use ofconstrains is discussed in Ensuring Data Integrity With Constraints.Example 6–22Creating a Table With Constraints-- create a table similar to the employees table in the HR schemaCREATE TABLE my_employees( employee_id NUMBER(6),first_name VARCHAR2(20),last_name VARCHAR2(25) CONSTRAINT my_emp_last_name_nn NOT NULL,emailVARCHAR2(25) CONSTRAINT my_emp_email_nn NOT NULL,phone_number VARCHAR2(20),<strong>SQL</strong>: Usage Information 6-15
Using <strong>SQL</strong> Data Definition Language Statementshire_date DATE DEFAULT SYSDATE CONSTRAINT my_emp_hire_date_nn NOT NULL,job_idVARCHAR2(10) CONSTRAINT my_emp_job_nn NOT NULL,salaryNUMBER(8,2) CONSTRAINT emy_mp_salary_nn NOT NULL,commission_pct NUMBER(2,2),manager_id NUMBER(6),department_id NUMBER(4),CONSTRAINT my_emp_salary_min CHECK (salary > 0),CONSTRAINT my_emp_email_uk UNIQUE (email));6.6.2 Creating and Modifying an Index With <strong>SQL</strong>To create, modify, or drop an index, use the <strong>SQL</strong> CREATE, ALTER, or DROP INDEXstatement as shown in Example 6–23.Example 6–23Creating, Modifying, and Dropping an Index-- create a new index on the employees table using the email columnCREATE INDEX email_ixON employees (email);-- disable the indexALTER INDEX email_ixRENAME TO my_email_ix;-- drop the indexDROP INDEX my_email_ix;-- create an index on a single column to make queries faster on that columnCREATE INDEX emp_last_name_ix ON employees (last_name);DROP INDEX emp_last_name_ix;-- create an index on two columns to make queries faster on the first column-- or both columnsCREATE INDEX emp_mgr_id_ix ON employees (employee_id, manager_id);DROP INDEX emp_mgr_id_ix;-- a function-based index precalculates the result and speeds up queries that-- use the function for searching or sorting, in this case UPPER(last_name)CREATE INDEX emp_upper_last_name_ix ON employees (UPPER(last_name));DROP INDEX emp_upper_last_name_ix;6.6.3 Creating and Modifying a Constraint With <strong>SQL</strong>To add or a modify a constraint on a table, use the <strong>SQL</strong> ALTER statement as shown inExample 6–24.Example 6–24Creating and Altering a Constraint-- add a constraint a new constraintALTER TABLE my_employeesADD CONSTRAINT ...-- remove the constraint on email in the my_employees tableALTER TABLE my_employeesDROP UNIQUE (email);6-16 <strong>SQL</strong> <strong>Developer</strong> Online Help
Using <strong>SQL</strong> Data Definition Language Statements6.6.4 Altering a Table With <strong>SQL</strong>To alter a database object, such as a table, use the <strong>SQL</strong> ALTER statement as shown inExample 6–25.Example 6–25Altering a Table-- add a new column to my_birthdaysALTER TABLE my_birthdaysADD (age NUMBER(3));-- rename the my_employees tableALTER TABLE my_employees RENAME to temp_employees;6.6.5 Dropping a Table With <strong>SQL</strong>To drop (remove completely) a table from the database use the <strong>SQL</strong> DROP statement asshown inExample 6–26. Be very careful when using the DROP statement to removedatabase objects.If you want to delete the rows in the table and keep the table, use the DELETEstatement. See "Deleting Data With the DELETE Statement" on page 6-8.Example 6–26Dropping a Table-- drop tables from the database-- use caution when use the DROP statement!DROP TABLE my_birthdays;DROP TABLE temp_employees;6.6.6 Creating and Dropping a SequenceExample 6–27 creates a sequence that can be used with the employees table. Thesequence could also be used with other tables. For more information on sequences, seeManaging Sequences.Example 6–27Creating a Sequence-- create a new sequence to use with the employees tableCREATE SEQUENCE new_employees_seq START WITH 1000 INCREMENT BY 1;-- to use the sequence, first initialize the sequence with NEXTVALSELECT new_employees_seq.NEXTVAL FROM DUAL;-- after initializing the sequence, use CURRVAL as the next value in the sequenceINSERT INTO employees VALUES(new_employees_seq.CURRVAL, 'Pilar', 'Valdivia', 'pilar.valdivia','555.111.3333', '01-SEP-05', 'AC_MGR', 9100, .1, 101, 110);-- query the employees table to check the current value of the sequence-- which was inserted used as employee_id in the previous INSERT statementSELECT employee_id, last_name FROM employees WHERE last_name = 'Valdivia';Example 6–28 drops the sequence that you previously created.<strong>SQL</strong>: Usage Information 6-17
Using <strong>SQL</strong> Data Definition Language StatementsExample 6–28Dropping a Sequence-- drop the sequenceDROP SEQUENCE new_employees_seq;6.6.7 Creating and Dropping a SynonymExample 6–29 creates a synonym that is alias for the employees table. For moreinformation on synonyms, see Managing Synonyms.Example 6–29Creating a Synonym-- create a synonym for the employees tableCREATE SYNONYM emps for HR.employees;-- query the employees table using the emps synonymSELECT employee_id, last_name FROM emps WHERE employee_id < 105;Example 6–30 drops a synonym.Example 6–30 Dropping a Synonym-- drop the synonymDROP SYNONYM emps;6-18 <strong>SQL</strong> <strong>Developer</strong> Online Help
7PL/<strong>SQL</strong>: Usage Information7.1 Overview of PL/<strong>SQL</strong>The topic discusses the development with PL/<strong>SQL</strong>. It includes the following topics:■ Overview of PL/<strong>SQL</strong> on page 7-1■ Entering and Executing PL/<strong>SQL</strong> Code on page 7-2■ Utilizing the Main Features of PL/<strong>SQL</strong> on page 7-2■ Handling PL/<strong>SQL</strong> Errors on page 7-21See Also:■■■■PL/<strong>SQL</strong> User's Guide and Reference for detailed information aboutPL/<strong>SQL</strong>.PL/<strong>SQL</strong> Packages and Types Reference for information on packagessupplied by <strong>Oracle</strong>.<strong>Oracle</strong> Database Application <strong>Developer</strong>'s Guide - Fundamentals forinformation on dynamic <strong>SQL</strong>.<strong>Oracle</strong> Database Application <strong>Developer</strong>'s Guide - Fundamentals forinformation on using PL/<strong>SQL</strong> to develop Web applications.PL/<strong>SQL</strong> is <strong>Oracle</strong>'s procedural language extension to <strong>SQL</strong>. It provides a server-side,stored procedural language that is easy-to-use, seamless with <strong>SQL</strong>, robust, portable,and secure.The PL/<strong>SQL</strong> compiler and interpreter are embedded in <strong>Oracle</strong> Database, providingdevelopers with a consistent and leveraged development model on both the client andthe server side. In addition, PL/<strong>SQL</strong> stored subprograms can be called from <strong>Oracle</strong>clients.PL/<strong>SQL</strong> enables you to mix <strong>SQL</strong> statements with procedural constructs. WithPL/<strong>SQL</strong>, you can create and run PL/<strong>SQL</strong> program units such as procedures,functions, and packages. PL/<strong>SQL</strong> program units generally are categorized asanonymous blocks, stored subprograms, and packages.The basic units (procedures, functions, and anonymous blocks) that make up aPL/<strong>SQL</strong> program can be nested inside one another.You can place declarations close to where they are used, such as inside a largesubprogram. The declarations are local to the block and cease to exist when the blockcompletes, helping to avoid cluttered namespaces for variables and procedures.PL/<strong>SQL</strong>: Usage Information 7-1
Entering and Executing PL/<strong>SQL</strong> CodeYou can nest blocks in the executable and exception-handling parts of a PL/<strong>SQL</strong> blockor subprogram, but not in the declarative part. You can define local subprograms inthe declarative part of any block. You can call local subprograms only from the blockin which they are defined.■■■Anonymous blockAn anonymous block is a PL/<strong>SQL</strong> block that appears in your application and isnot named or stored in the database. In many applications, PL/<strong>SQL</strong> blocks canappear wherever <strong>SQL</strong> statements can appear. A PL/<strong>SQL</strong> block groups relateddeclarations and statements.Stored or standalone subprogramA stored or standalone subprogram is a PL/<strong>SQL</strong> block that <strong>Oracle</strong> stores in thedatabase and can be called by name from an application. Subprograms can beprocedures or functions; the difference is that functions return a value whenexecuted. When you create a stored subprogram, <strong>Oracle</strong> parses the subprogramand stores its parsed representation in the database. See Subprograms andPackages: Usage Information.PackageA package is a group of subprograms and variable definitions that <strong>Oracle</strong> stores inthe database. Subprograms and variables in packages can be called from otherpackages or subprograms. See Subprograms and Packages: Usage Information.7.2 Entering and Executing PL/<strong>SQL</strong> CodePL/<strong>SQL</strong> code can be entered and executed from the <strong>SQL</strong> Workshop or the <strong>SQL</strong>*Pluscommand line.In the <strong>SQL</strong> Workshop, you can save your <strong>SQL</strong> statements as a script file that can be runas a <strong>SQL</strong> script with <strong>SQL</strong>*Plus.If you use <strong>SQL</strong>*Plus, simply type in each line of code at the <strong>SQL</strong> prompt. Forinformation on using <strong>SQL</strong>*Plus, see <strong>SQL</strong>*Plus: Usage Information.You can create a text file of the PL/<strong>SQL</strong> code and run that as a <strong>SQL</strong> script. Using ascript makes correcting mistakes much easier because you only need to make thenecessary updates to correct the problem rather than retyping all the PL/<strong>SQL</strong> code.For information on running <strong>SQL</strong> scripts from <strong>SQL</strong>*Plus, see Running Scripts From<strong>SQL</strong>*Plus.7.3 Utilizing the Main Features of PL/<strong>SQL</strong>PL/<strong>SQL</strong> combines the data-manipulating power of <strong>SQL</strong> with the processing power ofprocedural languages. You can control program flow with statements like IF andLOOP. As with other procedural programming languages, you can declare variables,define procedures and functions, and trap runtime errors.PL/<strong>SQL</strong> lets you break complex problems down into easily understandableprocedural code, and reuse this code across multiple applications. When a problemcan be solved through plain <strong>SQL</strong>, you can issue <strong>SQL</strong> commands directly inside yourPL/<strong>SQL</strong> programs, without learning new APIs. PL/<strong>SQL</strong> data types correspond with<strong>SQL</strong> column types, making it easy to interchange PL/<strong>SQL</strong> variables with data inside atable.■■Using PL/<strong>SQL</strong> Block StructureUsing Comments7-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>■■■■■■■■■■■■■■Declaring Variables and ConstantsUsing Identifiers in PL/<strong>SQL</strong>Assigning Values to a Variable With the Assignment OperatorUsing LiteralsDeclaring and Assigning Variables With DEFAULT or NOT NULLAssigning Values to a Variable With SELECT INTOInputting and Outputting Data with PL/<strong>SQL</strong>Using %ROWTYPE and %TYPE Attributes to Declare Data TypesUsing PL/<strong>SQL</strong> Control StructuresUsing Local PL/<strong>SQL</strong> Subprograms in PL/<strong>SQL</strong> BlocksWorking With PL/<strong>SQL</strong> Data StructuresProcessing Queries with PL/<strong>SQL</strong>Using Dynamic <strong>SQL</strong> in PL/<strong>SQL</strong>Using Bind Variables7.3.1 Using PL/<strong>SQL</strong> Block StructureAs Example 7–1 shows, a PL/<strong>SQL</strong> block has three basic parts: a declarative part(DECLARE), an executable part (BEGIN .. END), and an exception-handling(EXCEPTION) part that handles error conditions. For a discussion of exceptionhandling, see "Handling PL/<strong>SQL</strong> Errors" on page 7-21.Only the executable part is required. The optional declarative part is written first,where you define types, variables, and similar items. These items are manipulated inthe executable part. Exceptions raised during execution can be dealt with in theexception-handling part.Note the comments that are added to the PL/<strong>SQL</strong> code. See "Using Comments" onpage 7-4. Also, not the use of DBMS_OUTPUT.PUT_LINE to display output. See"Inputting and Outputting Data with PL/<strong>SQL</strong>" on page 7-9.Example 7–1Simple PL/<strong>SQL</strong> Block-- the following is an optional declarative partDECLAREmonthly_salaryNUMBER(6);number_of_days_worked NUMBER(2);pay_per_dayNUMBER(6,2);-- the following is the executable part, from BEGIN to ENDBEGINmonthly_salary := 2290;number_of_days_worked := 21;pay_per_day := monthly_salary/number_of_days_worked;-- the following displays output from the PL/<strong>SQL</strong> blockDBMS_OUTPUT.PUT_LINE('The pay per day is ' || TO_CHAR(pay_per_day));-- the following is an optional exception part that handles errorsEXCEPTIONWHEN ZERO_DIVIDE THENpay_per_day := 0;PL/<strong>SQL</strong>: Usage Information 7-3
Utilizing the Main Features of PL/<strong>SQL</strong>END;/7.3.2 Using CommentsFor another example of PL/<strong>SQL</strong> block structure, see Example 7–8 on page 7-9.The PL/<strong>SQL</strong> compiler ignores comments, but you should not. Adding comments toyour program promotes readability and help others understand your code. Generally,you use comments to describe the purpose and use of each code segment. PL/<strong>SQL</strong>supports single-line and multi-line comment styles.Single-line comments begin with a double hyphen (--) anywhere on a line and extendto the end of the line. Multi-line comments begin with a slash-asterisk (/*), end withan asterisk-slash (*/), and can span multiple lines. See Example 7–2.Example 7–2Using CommentsDECLARE -- Declare variables here.monthly_salaryNUMBER(6); -- This is the monthly salary.number_of_days_worked NUMBER(2); -- This is the days in one month.pay_per_dayNUMBER(6,2); -- Calculate this value.BEGIN-- First assign values to the variables.monthly_salary := 2290;number_of_days_worked := 21;-- Now calculate the value on the following line.pay_per_day := monthly_salary/number_of_days_worked;-- the following displays output from the PL/<strong>SQL</strong> blockDBMS_OUTPUT.PUT_LINE('The pay per day is ' || TO_CHAR(pay_per_day));EXCEPTION/* This is a simple example of an exeception handler to trap division by zero.In actual practice, it would be best to check whether a variable iszero before using it as a divisor. */WHEN ZERO_DIVIDE THENpay_per_day := 0; -- set to 0 if divisor equals 0END;/While testing or debugging a program, you might want to disable a line of code. Thefollowing example shows how you can disable a single line by making it a comment:-- pay_per_day := monthly_salary/number_of_days_worked;You can use multi-line comment delimiters to comment-out large sections of code.7.3.3 Declaring Variables and ConstantsVariables can have any <strong>SQL</strong> data type, such as VARCHAR2, DATE, or NUMBER, or aPL/<strong>SQL</strong>-only data type, such as BOOLEAN or PLS_INTEGER. You can also declarenested tables, variable-size arrays (varrays for short), and records using the TABLE,VARRAY, and RECORD composite data types. See "Working With PL/<strong>SQL</strong> DataStructures" on page 7-17.Declaring a constant is like declaring a variable except that you must add the keywordCONSTANT and immediately assign a value to the constant. No further assignments to7-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>the constant are allowed. For an example, see avg_days_worked_month inExample 7–3.For example, assume that you want to declare variables for employee data, such asemployee_id to hold 6-digit numbers and active_employee to hold the Booleanvalue TRUE or FALSE. You declare these and related employee variables and constantsas shown in Example 7–3.Note that there is a semi-colon (;) at the end of each line in the declaration section.Also, note the use of the NULL statement which enables you to execute and test thePL/<strong>SQL</strong> block.You can choose any naming convention for variables that is appropriate for yourapplication. For example, you could begin each variable name with the v_ prefix toemphasize that these are variable names.Example 7–3 Declaring Variables in PL/<strong>SQL</strong>DECLARE -- declare the variables in this sectionlast_nameVARCHAR2(30);first_nameVARCHAR2(25);employee_idNUMBER(6);active_employee BOOLEAN;monthly_salaryNUMBER(6);number_of_days_worked NUMBER(2);pay_per_dayNUMBER(6,2);avg_days_worked_month CONSTANT NUMBER(2) := 21; -- a constant variableBEGINNULL; -- NULL statement does nothing, allows this block to executed and testedEND;/7.3.4 Using Identifiers in PL/<strong>SQL</strong>See Also: PL/<strong>SQL</strong> User's Guide and Reference for information on datatypes used with PL/<strong>SQL</strong>, including the PL/<strong>SQL</strong> BOOLEAN and PLS_INTEGER data typesYou use identifiers to name PL/<strong>SQL</strong> program items and units, such as constants,variables, exceptions, and subprograms. An identifier consists of a letter optionallyfollowed by more letters, numerals, dollar signs, underscores, and number signs.The declaration section in Example 7–4 illustrates some valid identifiers. You can seeadditional examples of valid identifiers for variable names in Example 7–2 on page 7-4and Example 7–3 on page 7-5.Example 7–4Valid Identifiers for VariablesDECLARE -- all declarations use valid identifiersxNUMBER;t2NUMBER;phone#VARCHAR2(12);credit_limit NUMBER;oracle$number NUMBER;money$$$tree NUMBER;SN##VARCHAR2(9);try_againBOOLEAN;BEGINNULL;END;/PL/<strong>SQL</strong>: Usage Information 7-5
Utilizing the Main Features of PL/<strong>SQL</strong>Characters such as hyphens, slashes, and spaces are not allowed. For example thefollowing identifiers are not allowed:mine&yours is not allowed because of the ampersanddebit-amount is not allowed because of the hyphenon/off is not allowed because of the slashuser id is not allowed because of the spaceYou can use upper, lower, or mixed case to write identifiers. PL/<strong>SQL</strong> is not casesensitive except within string and character literals. Every character, including dollarsigns, underscores, and number signs, is significant. If the only difference betweenidentifiers is the case of corresponding letters, PL/<strong>SQL</strong> considers them the same, as inthe following:lastname is same as LASTNAME and LastNameLastName is the same as lastname and LASTNAMELASTNAME is same as lastname and LastNameThe size of an identifier cannot exceed 30 characters. Identifiers should be descriptive.When possible, avoid obscure names such as cpm. Instead, use meaningful names suchas cost_per_thousand.Some identifiers, called reserved words or keywords, have a special syntactic meaningto PL/<strong>SQL</strong>. For example, the words BEGIN and END are reserved. Often, reservedwords and keywords are written in upper case for readability. Neither reserved wordsor keywords should be used as identifiers and the use can cause compilation errors.See Also: PL/<strong>SQL</strong> User's Guide and Reference for information onPL/<strong>SQL</strong> reserved words and keywords7.3.5 Assigning Values to a Variable With the Assignment OperatorYou can assign values to a variable in several ways. One way uses the assignmentoperator (:=), a colon followed by an equal sign, as shown in Example 7–5. You placethe variable to the left of the operator and an expression, including function calls, tothe right. Note that you can assign a value to a variable when it is declared.Example 7–5Assigning Values to Variables With the Assignment OperatorDECLARE -- declare and assiging variableswagesNUMBER(6,2);hours_worked NUMBER := 40;hourly_salary NUMBER := 22.50;bonus NUMBER := 150;country VARCHAR2(128);counter NUMBER := 0;doneBOOLEAN := FALSE;valid_id BOOLEAN;BEGINwages := (hours_worked * hourly_salary) + bonus; -- compute wagescountry := 'France'; -- assign a string literalcountry := UPPER('Canada'); -- assign an uppercase string literaldone := (counter > 100); -- assign a BOOLEAN, in this case FALSEvalid_id := TRUE; -- assign a BOOLEANEND;/7-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>7.3.6 Using LiteralsA literal is an explicit numeric, character, string, or BOOLEAN value not represented byan identifier. For example, 147 is a numeric literal and FALSE is a BOOLEAN literal.Numeric LiteralsTwo kinds of numeric literals can be used in arithmetic expressions: integers and reals.An integer literal is an optionally signed whole number without a decimal point, suchas +6. A real literal is an optionally signed whole or fractional number with a decimalpoint, such as -3.14159. PL/<strong>SQL</strong> considers a number such as 25. to be real eventhough it has an integral value.Numeric literals cannot contain dollar signs or commas, but can be written usingscientific notation. Simply suffix the number with an E (or e) followed by anoptionally signed integer, such as -9.5e-3. E (or e) stands for times ten to the powerof.Character LiteralsA character literal is an individual character enclosed by single quotes (apostrophes),such as '(' or '7'. Character literals include all the printable characters in thePL/<strong>SQL</strong> character set: letters, numerals, spaces, and special symbols.PL/<strong>SQL</strong> is case sensitive within character literals. For example, PL/<strong>SQL</strong> considers thecharacter literals 'Z' and 'z' to be different. Also, the character literals '0'..'9' arenot equivalent to integer literals but can be used in arithmetic expressions becausethey are implicitly convertible to integers.String LiteralsA character value can be represented by an identifier or explicitly written as a stringliteral, which is a sequence of zero or more characters enclosed by single quotes, suchas 'Hello, world!' and '$1,000,000'. All string literals except the null string ('')have data type CHAR.PL/<strong>SQL</strong> is case sensitive within string literals. For example, PL/<strong>SQL</strong> considers thefollowing string literals 'baker' and 'Baker' to be different:To represent an apostrophe within a string, you can write two single quotes (''),which is not the same as writing a double quote ("). Doubling the quotation markswithin a complicated literal, particularly one that represents a <strong>SQL</strong> statement, can betricky. You can also define your own delimiter characters for the literal. You choose acharacter that is not present in the string, and then do not need to escape other singlequotation marks inside the literal, such as the following string.q'!I'm using the exclamation point for a delimiter here.!'BOOLEAN LiteralsBOOLEAN literals are the predefined values TRUE, FALSE, and NULL. NULL stands for amissing, unknown, or inapplicable value. Remember, BOOLEAN literals are values, notstrings. For example, TRUE is no less a value than the number 25.Datetime LiteralsDatetime literals have various formats depending on the datetime data type, such as'14-SEP-05' or '14-SEP-05 09:24:04 AM'.Example 7–6 shows some examples of the use of literals.PL/<strong>SQL</strong>: Usage Information 7-7
Utilizing the Main Features of PL/<strong>SQL</strong>Example 7–6 Using LiteralsDECLARE -- declare and assign variablesnumber1 PLS_INTEGER := 32000; -- numeric literalnumber2 NUMBER(8,3);char1 VARCHAR2(1) := 'x'; -- character literalchar2 VARCHAR2(1000);boolean BOOLEAN := TRUE; -- BOOLEAN literaldate1 DATE := '11-AUG-2005'; -- DATE literaltime1 TIMESTAMP;time2 TIMESTAMP WITH TIME ZONE;BEGINnumber2 := 3.125346e3; -- numeric literalnumber2 := -8300.00; -- numeric literalnumber2 := -14; -- numeric literalchar2 := q'!I'm writing an example string.!'; -- string literalchar2 := 'I''m writing an example string.'; -- need two single quotes heretime1 := '11-AUG-2005 11:01:01 PM'; -- TIMESTAMP literaltime2 := '11-AUG-2005 09:26:56.66 PM +02:00';END;/See Also:■■■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the syntax forliterals and the date and time types.<strong>Oracle</strong> Database Application <strong>Developer</strong>'s Guide - Fundamentals forexamples of performing date and time arithmetic.PL/<strong>SQL</strong> User's Guide and Reference for information on using literalswith PL/<strong>SQL</strong>.7.3.7 Declaring and Assigning Variables With DEFAULT or NOT NULLYou can use the keyword DEFAULT instead of the assignment operator to initializevariables. Use DEFAULT for variables that have a typical value. Use the assignmentoperator for variables (such as counters and accumulators) that have no typical value.You can also use DEFAULT to initialize subprogram parameters, cursor parameters,and fields in a user-defined record.Besides assigning an initial value, declarations can impose the NOT NULL constraint sothat assigning a NULL raises an error. The NOT NULL constraint must be followed by aninitialization clause.In Example 7–7 the declaration for avg_days_worked_month uses the DEFAULT toassign a value of 21 and the declarations for active_employee and monthly_salary use the NOT NULL constraint.Example 7–7Using DEFAULT and NOT NULLDECLARE -- declare and assign variableslast_nameVARCHAR2(30);first_nameVARCHAR2(25);employee_idNUMBER(6);active_employee BOOLEAN NOT NULL := TRUE; -- value cannot be NULLmonthly_salaryNUMBER(6) NOT NULL := 2000; -- value cannot be NULLnumber_of_days_worked NUMBER(2);pay_per_dayNUMBER(6,2);employee_count NUMBER(6) := 0;avg_days_worked_month NUMBER(2) DEFAULT 21; -- assign a default valueBEGIN7-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>NULL; -- NULL statement does nothing, allows this block to executed and testedEND;/7.3.8 Assigning Values to a Variable With SELECT INTOAnother way to assign values to a variable is by selecting (or fetching) database valuesinto it. In Example 7–8, 10% of an employee's salary is selected into the bonusvariable. Now you can use the bonus variable in another computation or insert itsvalue into a database table.In the example, DBMS_OUTPUT.PUT_LINE is used to display output from the PL/<strong>SQL</strong>program. For more information, see "Inputting and Outputting Data with PL/<strong>SQL</strong>" onpage 7-9.Example 7–8Assigning Values to Variables by SELECTing INTODECLARE -- declare and assign valuesbonus NUMBER(8,2);emp_id NUMBER(6) := 100; -- declare variable and assign a test valueBEGIN-- retreive a value from the employees table and assign to the bonus variableSELECT salary * 0.10 INTO bonus FROM employeesWHERE employee_id = emp_id;DBMS_OUTPUT.PUT_LINE ( 'Employee: ' || TO_CHAR(emp_id)|| ' Bonus: ' || TO_CHAR(bonus) ); -- display dataEND;/7.3.9 Inputting and Outputting Data with PL/<strong>SQL</strong>Most PL/<strong>SQL</strong> input and output is through <strong>SQL</strong> statements, to store data in databasetables or query those tables. All other PL/<strong>SQL</strong> I/O is done through APIs that interactwith other programs. For example, the DBMS_OUTPUT package has procedures such asPUT_LINE. To see the result outside of PL/<strong>SQL</strong> requires another program, such as<strong>SQL</strong>*Plus, to read and display the data passed to DBMS_OUTPUT. <strong>SQL</strong>*Plus does notdisplay DBMS_OUTPUT data unless you first issue the <strong>SQL</strong>*Plus command SETSERVEROUTPUT ON. For information on <strong>SQL</strong>*Plus SET command, see <strong>SQL</strong>*Plus SETCommands .Example 7–9 show the use of DBMS_OUTPUT.PUTLINE. Note the use of SETSERVEROUTPUT ON to enable output.Example 7–9Using DBMS_OUTPUT to Display Output-- enable SERVEROUTPUT in <strong>SQL</strong>*Plus to display with DBMS_OUTPUT.PUT_LINE-- this enables SERVEROUTPUT for this <strong>SQL</strong>*Plus session onlySET SERVEROUTPUT ONDECLAREanswer VARCHAR2(20); -- declare a variableBEGIN-- assign a value to a variableanswer := 'Maybe';-- use PUT_LINE to display data from the PL/<strong>SQL</strong> blockDBMS_OUTPUT.PUT_LINE( 'The answer is: ' || answer );END;/PL/<strong>SQL</strong>: Usage Information 7-9
Utilizing the Main Features of PL/<strong>SQL</strong>The DBMS_OUTPUT package is a predefined <strong>Oracle</strong> package. For information about<strong>Oracle</strong> supplied packages, see <strong>Oracle</strong> Product-Specific Packages.See Also:■■<strong>SQL</strong>*Plus User's Guide and Reference for information <strong>SQL</strong>*Pluscommands.PL/<strong>SQL</strong> Packages and Types Reference.for information about <strong>Oracle</strong>supplied packages.7.3.10 Using %ROWTYPE and %TYPE Attributes to Declare Data TypesAs part of the declaration for each PL/<strong>SQL</strong> variable, you declare its data type. Usually,this data type is one of the types shared between PL/<strong>SQL</strong> and <strong>SQL</strong>, such as NUMBER orVARCHAR2. For easier maintenance of code that interacts with the database, you canalso use the special qualifiers %ROWTYPE and %TYPE to declare variables that holdtable columns or table rows.7.3.10.1 Using the %ROWTYPE Attribute to Declare VariablesFor easier maintenance of code that interacts with the database, you can use the%ROWTYPE attribute to declare a variable that represents a row in a table. A PL/<strong>SQL</strong>record is the data type that stores the same information as a row in a table.In PL/<strong>SQL</strong>, records are used to group data. A record consists of a number of relatedfields in which data values can be stored. The record can store an entire row of dataselected from the table or fetched from a cursor or cursor variable. For information onrecords, see "Using Records" on page 7-18.Columns in a row and corresponding fields in a record have the same names and datatypes. In Example 7–10, you declare a record named emp_rec. Its fields have the samenames and data types as the columns in the employees table. You use dot notation toreference fields, such as emp_rec.last_name.In Example 7–10, SELECT is used to store row information from the employees tableinto the emp_rec record. When you execute the SELECT INTO statement, the value inthe first_name column of the employees table is assigned to the first_name fieldof emp_rec, the value in the last_name column is assigned to the last_name fieldof emp_rec, and so on.Example 7–10Using %ROWTYPE with a RecordDECLARE -- declare variables-- declare record variable that represents a row fetched from the employees tableemp_rec employees%ROWTYPE; -- declare variable with %ROWTYPE attributeBEGINSELECT * INTO emp_rec FROM EMPLOYEES WHERE employee_id = 120; -- retrieve recordDBMS_OUTPUT.PUT_LINE('Employee name: ' || emp_rec.first_name || ' '|| emp_rec.last_name); -- displayEND;/Declaring variables with %ROWTYPE has several advantages. First, you do not need toknow the exact data type of the table columns. Second, if you change the databasedefinition of any of the table columns, the data types associated with the %ROWTYPEdeclaration change accordingly at run time.See Also: PL/<strong>SQL</strong> User's Guide and Reference for information on%ROWTYPE7-10 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>7.3.10.2 Using the %TYPE Attribute to Declare VariablesThe %TYPE attribute provides the data type of a variable or table column. This isparticularly useful when declaring variables that will hold values of a table column.For example, suppose you want to declare variables as the same data type as columnsemployee_id and last_name in table employees. To declare variables namedempid and emplname that have the same data type as the table columns, use dotnotation and the %TYPE attribute. See Example 7–11.Example 7–11Using %TYPE With Table ColumnsDECLARE -- declare variables using %TYPE attributeempid employees.employee_id%TYPE; -- employee_id data type is NUMBER(6)emplname employees.last_name%TYPE; -- last_name data type is VARCHAR2(25)BEGINempid := 100301; -- this is OK because it fits in NUMBER(6)-- empid := 3018907; -- this is too large and will cause an overflowemplname := 'Patel'; -- this is OK because it fits in VARCHAR2(25)DBMS_OUTPUT.PUT_LINE('Employee Id: ' || empid); -- display dataDBMS_OUTPUT.PUT_LINE('Employee name: ' || emplname); -- display dataEND;/Declaring variables with %TYPE has two advantages. First, you need not know theexact data type of the table columns. Second, if you change the database definition ofcolumns, such as employee_id or last_name, the data types of empid andemplname in Example 7–11 change accordingly at run time.See Also:%TYPEPL/<strong>SQL</strong> User's Guide and Reference for information on7.3.11 Using PL/<strong>SQL</strong> Control StructuresControl structures are the most important PL/<strong>SQL</strong> extension to <strong>SQL</strong>. Not only doesPL/<strong>SQL</strong> let you manipulate <strong>Oracle</strong> data, it lets you process the data using conditional,iterative, and sequential flow-of-control statements such as IF-THEN-ELSE, CASE,FOR-LOOP, WHILE-LOOP, EXIT-WHEN, and GOTO.7.3.11.1 Conditional Control With IF-THENOften, it is necessary to take alternative actions depending on circumstances. TheIF-THEN statement lets you execute a sequence of statements conditionally. The formsof the statement can be IF-THEN, IF-THEN-ELSE, or IF-THEN-ELSEIF-ELSE. TheIF clause checks a condition, the THEN clause defines what to do if the condition istrue and the ELSE clause defines what to do if the condition is false or null.Example 7–12 shows a simple use of the IF-THEN statement.Example 7–12Using a Simple IF-THEN StatementDECLAREsales NUMBER(8,2) := 10100;quota NUMBER(8,2) := 10000;bonus NUMBER(6,2);emp_id NUMBER(6) := 120; -- use employee 120 for testingBEGINIF sales > (quota + 200) THENbonus := (sales - quota)/4;UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;END IF;PL/<strong>SQL</strong>: Usage Information 7-11
Utilizing the Main Features of PL/<strong>SQL</strong>END;/Example 7–13 shows the use of IF-THEN-ELSEIF-ELSE to determine the salary raisean employee receives based on the hire date of the employee.Example 7–13Using the IF-THEN-ELSEIF StatementDECLAREbonus NUMBER(6,2);emp_id NUMBER(6) := 120;hire_date DATE;BEGINSELECT hire_date INTO hire_date FROM employees WHERE employee_id = 120;IF hire_date > TO_DATE('01-JAN-98') THENbonus := 500;ELSIF hire_date > TO_DATE('01-JAN-96') THENbonus := 1000;ELSEbonus := 1500;END IF;UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;END;/7.3.11.2 Conditional Control With the CASE StatementTo choose among several values or courses of action, you can use CASE constructs. TheCASE expression evaluates a condition and returns a value for each case. The casestatement evaluates a condition and performs an action, such as an entire PL/<strong>SQL</strong>block, for each case. When possible, rewrite lengthy IF-THEN-ELSIF statements asCASE statements because the CASE statement is more readable and more efficient.Example 7–14 shows a simple CASE statement.Example 7–14Using the CASE-WHEN StatementDECLAREgrade CHAR(1);BEGINgrade := 'B';CASE gradeWHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good');WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good');WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair');WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor');ELSE DBMS_OUTPUT.PUT_LINE('No such grade');END CASE;END;/Example 7–15 determines the salary raise an employee receives based on the currentsalary of the employee and the job Id. This complex example combines the CASEexpression with IF-THEN-ELSE statements.Example 7–15 Using the IF-THEN_ELSE and CASE StatementDECLARE -- declare variablesjobid employees.job_id%TYPE;7-12 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>empid employees.employee_id%TYPE := 115;sal employees.salary%TYPE;sal_raise NUMBER(3,2);BEGIN-- retrieve data from employees and assign to variables jobid and salSELECT job_id, salary INTO jobid, sal from employees WHERE employee_id = empid;CASE -- check for conditionsWHEN jobid = 'PU_CLERK' THENIF sal < 3000 THEN sal_raise := .08;ELSE sal_raise := .07;END IF;WHEN jobid = 'SH_CLERK' THENIF sal < 4000 THEN sal_raise := .06;ELSE sal_raise := .05;END IF;WHEN jobid = 'ST_CLERK' THENIF sal < 3500 THEN sal_raise := .04;ELSE sal_raise := .03;END IF;ELSEBEGIN-- if no conditions met, then the followingDBMS_OUTPUT.PUT_LINE('No raise for this job: ' || jobid);END;END CASE;UPDATE employees SET salary = salary + salary * sal_raiseWHERE employee_id = empid; -- update a record in the employees tableCOMMIT;END;/A sequence of statements that uses query results to select alternative actions iscommon in database applications. Another common sequence inserts or deletes a rowonly if an associated entry is found in another table. You can bundle these commonsequences into a PL/<strong>SQL</strong> block using conditional logic.7.3.11.3 Iterative Control With LOOPsLOOP statements let you execute a sequence of statements multiple times. You placethe keyword LOOP before the first statement in the sequence and the keywords ENDLOOP after the last statement in the sequence.The FOR-LOOP statement lets you specify a range of integers, then execute a sequenceof statements once for each integer in the range. In Example 7–16 the loop displays thenumber and the square of the number for numbers 1 to 10. inserts 100 numbers, squareroots, squares, and the sum of squares into a database table:Example 7–16 Using the FOR-LOOPBEGIN-- use a FOR loop to process a series of numbersFOR i in 1..10 LOOPDBMS_OUTPUT.PUT_LINE('Number: ' || TO_CHAR(i) || ' Square: ' || TO_CHAR(i*i));END LOOP;END;/The WHILE-LOOP statement associates a condition with a sequence of statements.Before each iteration of the loop, the condition is evaluated. If the condition is true, thePL/<strong>SQL</strong>: Usage Information 7-13
Utilizing the Main Features of PL/<strong>SQL</strong>sequence of statements is executed, then control resumes at the top of the loop. If thecondition is false or null, the loop is bypassed and control passes to the next statement.In Example 7–17, you find the first employee who has a salary over $15000 and ishigher in the chain of command than employee 120:Example 7–17 Using WHILE-LOOP for Control-- create a temporary table for this exampleCREATE TABLE temp (tempid NUMBER(6), tempsal NUMBER(8,2), tempname VARCHAR2(25));DECLARE -- declare variablessal employees.salary%TYPE := 0;mgr_idemployees.manager_id%TYPE;lnameemployees.last_name%TYPE;starting_empid employees.employee_id%TYPE := 120;BEGINSELECT manager_id INTO mgr_id FROM employeesWHERE employee_id = starting_empid; -- retrieve data from employees-- use WHILE LOOP to process dataWHILE sal 15000SELECT salary, manager_id, last_name INTO sal, mgr_id, lnameFROM employees WHERE employee_id = mgr_id;END LOOP;INSERT INTO temp VALUES (NULL, sal, lname); -- insert NULL for tempid in tableCOMMIT;EXCEPTIONWHEN NO_DATA_FOUND THENINSERT INTO temp VALUES (NULL, NULL, 'Not found'); -- insert NULLsCOMMIT;END;/-- display rows in table tempSELECT * FROM temp;-- drop temporary tableDROP TABLE temp;The EXIT-WHEN statement lets you complete a loop if further processing is impossibleor undesirable. When the EXIT statement is encountered, the condition in the WHENclause is evaluated. If the condition is true, the loop completes and control passes tothe next statement. In Example 7–18, the loop completes when the value of totalexceeds 25,000:Example 7–18 Using the EXIT-WHEN StatementDECLARE -- declare and assign values to variablestotal NUMBER(9) := 0;counter NUMBER(6) := 0;BEGINLOOPcounter := counter + 1; -- increment counter variabletotal := total + counter * counter; -- compute total-- exit loop when condition is trueEXIT WHEN total > 25000; -- LOOP until condition is metEND LOOP;DBMS_OUTPUT.PUT_LINE('Counter: ' || TO_CHAR(counter) || ' Total: ' || TO_CHAR(total)); -- display dataEND;/7-14 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>7.3.11.4 Sequential Control With GOTOThe GOTO statement lets you branch to a label unconditionally. The label, anundeclared identifier enclosed by double angle brackets, must precede an executablestatement or a PL/<strong>SQL</strong> block. When executed, the GOTO statement transfers control tothe labeled statement or block, as shown in Example 7–19.Example 7–19Using the GOTO StatementDECLARE -- declare variablesp VARCHAR2(30);n PLS_INTEGER := 37; -- test any integer > 2 for prime, here 37BEGIN-- loop through divisors to determine if a prime numberFOR j in 2..ROUND(SQRT(n))LOOPIF n MOD j = 0 THEN -- test for primep := ' is NOT a prime number'; -- not a prime numberGOTO print_now;END IF;END LOOP;p := ' is a prime number';DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p); -- display dataEND;/7.3.12 Using Local PL/<strong>SQL</strong> Subprograms in PL/<strong>SQL</strong> BlocksSubprograms are named PL/<strong>SQL</strong> blocks that can be called with a set of parametersfrom inside a PL/<strong>SQL</strong> block. PL/<strong>SQL</strong> has two types of subprograms: procedures andfunctions.Example 7–20 is an example of a declaration of a PL/<strong>SQL</strong> procedure in a PL/<strong>SQL</strong>block. Note that the v1 and v2 variables are declared as IN OUT parameters to asubprogram. An IN OUT parameter passes an initial value that is read inside asubprogram and then returns a value that has been updated in the subprogram.Example 7–20 Declaring a Procedure With IN OUT ParametersDECLARE -- declare variables and subprogramsfname VARCHAR2(20) := 'randall';lname VARCHAR2(25) := 'dexter';PROCEDURE upper_name ( v1 IN OUT VARCHAR2, v2 IN OUT VARCHAR2) ASBEGINv1 := UPPER(v1); -- change the string to uppercasev2 := UPPER(v2); -- change the string to uppercaseEND;BEGINDBMS_OUTPUT.PUT_LINE(fname || ' ' || lname ); -- display initial valuesupper_name (fname, lname); -- call the procedure with parametersDBMS_OUTPUT.PUT_LINE(fname || ' ' || lname ); -- display new valuesEND;/Example 7–21 is an example of a declaration of a PL/<strong>SQL</strong> function in a PL/<strong>SQL</strong> block.Note that the value returned by the function is used directly in the DBMS_OUTPUT.PUT_LINE statement. Note that the v1 and v2 variables are declared as INparameters to a subprogram. An IN parameter passes an initial value that is readPL/<strong>SQL</strong>: Usage Information 7-15
Utilizing the Main Features of PL/<strong>SQL</strong>inside a subprogram. Any update to the value of the parameter inside the subprogramis not accessible outside the subprogram.Example 7–21Declaring a Function With IN ParametersDECLARE -- declare variables and subprogramsfname VARCHAR2(20) := 'randall';lname VARCHAR2(25) := 'dexter';FUNCTION upper_name ( v1 IN VARCHAR2, v2 IN VARCHAR2)RETURN VARCHAR2 ASv3 VARCHAR2(45); -- this variable is local to the functionBEGIN-- build a string that will be returned as the function valuev3 := v1 || ' + ' || v2 || ' = ' || UPPER(v1) || ' ' || UPPER(v2);RETURN v3; -- return the value of v3END;BEGIN-- call the function and display resultsDBMS_OUTPUT.PUT_LINE(upper_name (fname, lname));END;/In Example 7–22, both a variable and a numeric literal are passed as a parameter to amore complex procedure.Example 7–22 Declaring a Complex Procedure in a PL/<strong>SQL</strong> BlockDECLARE -- declare variables and subprogramsempid NUMBER;PROCEDURE avg_min_max_sal (empid IN NUMBER) ISjobid VARCHAR2(10);avg_sal NUMBER;min_sal NUMBER;max_sal NUMBER;BEGIN-- determine the job Id for the employeeSELECT job_id INTO jobid FROM employees WHERE employee_id = empid;-- calculate the average, minimum, and maximum salaries for that job IdSELECT AVG(salary), MIN(salary), MAX(salary) INTO avg_sal, min_sal, max_salFROM employees WHERE job_id = jobid;-- display dataDBMS_OUTPUT.PUT_LINE ('Employee Id: ' || empid || ' Job Id: ' || jobid);DBMS_OUTPUT.PUT_LINE ('The average salary for job Id: ' || jobid|| ' is ' || TO_CHAR(avg_sal));DBMS_OUTPUT.PUT_LINE ('The minimum salary for job Id: ' || jobid|| ' is ' || TO_CHAR(min_sal));DBMS_OUTPUT.PUT_LINE ('The maximum salary for job Id: ' || jobid|| ' is ' || TO_CHAR(max_sal));END avg_min_max_sal;BEGIN-- call the procedure with several employee Idsempid := 125;avg_min_max_sal(empid);avg_min_max_sal(112);END;/Subprograms can also be declared in packages. You can create subprograms that arestored in the database. These subprograms can be called from other subprograms,packages, and <strong>SQL</strong> statements. See Subprograms and Packages: Usage Information.7-16 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>7.3.13 Working With PL/<strong>SQL</strong> Data StructuresData structure are composite data types that let you work with the essential propertiesof data without being too involved with details. After you design a data structure, youcan focus on designing algorithms that manipulate the data structure.7.3.13.1 Using CursorsA cursor is a name for a specific private <strong>SQL</strong> area in which information for processingthe specific statement is kept. PL/<strong>SQL</strong> uses both implicit and explicit cursors. PL/<strong>SQL</strong>implicitly declares a cursor for all <strong>SQL</strong> data manipulation statements on a set of rows,including queries that return only one row. You can explicitly declare a cursor for onerow, as shown in Example 7–10 on page 7-10 declares an explicit cursor.For queries that return more than one row, you can explicitly declare a cursor toprocess the rows individually. See Example 7–23.Example 7–23 Fetching With a CursorDECLARE -- declare variables and cursorsjobid employees.job_id%TYPE; -- variable for job_idlastname employees.last_name%TYPE; -- variable for last_nameCURSOR c1 IS SELECT last_name, job_id FROM employeesWHERE job_id LIKE '%CLERK';employees employees%ROWTYPE;-- record variable for rowCURSOR c2 is SELECT * FROM employeesWHERE job_id LIKE '%MAN' OR job_id LIKE '%MGR';BEGINOPEN c1; -- open the cursor before fetchingLOOPFETCH c1 INTO lastname, jobid; -- fetches 2 columns into variablesEXIT WHEN c1%NOTFOUND;DBMS_OUTPUT.PUT_LINE( RPAD(lastname, 25, ' ') || jobid );END LOOP;CLOSE c1;DBMS_OUTPUT.PUT_LINE( '-------------------------------------' );OPEN c2;LOOPFETCH c2 INTO employees; -- fetches entire row into the employees recordEXIT WHEN c2%NOTFOUND;DBMS_OUTPUT.PUT_LINE( RPAD(employees.last_name, 25, ' ') ||employees.job_id );END LOOP;CLOSE c2;END;/In Example 7–23, LIKE is used to specify the records to return with the query. Forinformation on LIKE, see Restricting Data Using the WHERE Clause.See Also: PL/<strong>SQL</strong> User's Guide and Reference for information onmanaging cursors with PL/<strong>SQL</strong>7.3.13.2 Using CollectionsPL/<strong>SQL</strong> collection types let you declare high-level data types similar to arrays, sets,and hash tables found in other languages. In PL/<strong>SQL</strong>, array types are known asvarrays (short for variable-size arrays), set types are known as nested tables, and hashtable types are known as associative arrays. Each kind of collection is an orderedgroup of elements, all of the same type. Each element has a unique subscript thatPL/<strong>SQL</strong>: Usage Information 7-17
Utilizing the Main Features of PL/<strong>SQL</strong>determines its position in the collection. When declaring collections, you use a TYPEdefinition.To reference an element, use subscript notation with parentheses, as shown inExample 7–24.Example 7–24Using a PL/<strong>SQL</strong> Collection TypeDECLARE -- declare variablesTYPE jobids_array IS VARRAY(12) OF VARCHAR2(10); -- declare VARRAYjobids jobids_array; -- declare a variable of type jobids_arrayhowmany NUMBER; -- declare a variable to hold employee countBEGIN-- initialize the arrary with some job Id valuesjobids := jobids_array('AC_ACCOUNT', 'AC_MGR', 'AD_ASST', 'AD_PRES', 'AD_VP','FI_ACCOUNT', 'FI_MGR', 'HR_REP', 'IT_PROG', 'SH_CLERK','ST_CLERK', 'ST_MAN');FOR i IN jobids.FIRST..jobids.LAST LOOP -- loop through all the varray values-- determine the number of employees for each job Id in the arraySELECT COUNT(*) INTO howmany FROM employees WHERE job_id = jobids(i);DBMS_OUTPUT.PUT_LINE ( 'Job Id: ' || jobids(i) ||' Number of employees: ' || TO_CHAR(howmany));END LOOP;END;/Collections can be passed as parameters, so that subprograms can process arbitrarynumbers of elements.You can use collections to move data into and out of databasetables using high-performance language features known as bulk <strong>SQL</strong>.See Also:■PL/<strong>SQL</strong> User's Guide and Reference for information on PL/<strong>SQL</strong>collections.7.3.13.3 Using RecordsRecords are composite data structures whose fields can have different data types. Youcan use records to hold related items and pass them to subprograms with a singleparameter. When declaring records, you use the TYPE definition.Example 7–25 shows how are records are declared.Example 7–25Declaring a Record TypeDECLARE -- declare RECORD type variablesTYPE timerec IS RECORD (hours SMALLINT, minutes SMALLINT);TYPE meetin_typ IS RECORD (date_held DATE,duration timerec, -- nested recordlocation VARCHAR2(20),purpose VARCHAR2(50));BEGIN-- NULL does nothing but allows unit to be compiled and testedNULL;END;/You can use the %ROWTYPE attribute to declare a record that represents a row in a tableor a row from a query result set, without specifying the names and types for the fields.7-18 <strong>SQL</strong> <strong>Developer</strong> Online Help
Utilizing the Main Features of PL/<strong>SQL</strong>When using %ROWTYPE, the record type definition is implied and the TYPE keyword isnot necessary, as shown in Example 7–26.Example 7–26Using %ROWTYPE with a CursorDECLARE -- declare variablesCURSOR c1 ISSELECT * FROM employeesWHERE employee_id = 120; -- declare cursor-- declare record variable that represents a row fetched from the employees tableemployee_rec c1%ROWTYPE; -- declare variable with %ROWTYPE attributeBEGIN-- open the explicit cursor c1 and use it to fetch data into employee_recOPEN c1;FETCH c1 INTO employee_rec; -- retrieve recordDBMS_OUTPUT.PUT_LINE('Employee name: ' || employee_rec.last_name); -- displayEND;/See Also:■PL/<strong>SQL</strong> User's Guide and Reference for information on PL/<strong>SQL</strong>records.7.3.14 Processing Queries with PL/<strong>SQL</strong>Processing a <strong>SQL</strong> query with PL/<strong>SQL</strong> is like processing files with other languages.This process includes opening a file, reading the file contents, processing each line,then closing the file. In the same way, a PL/<strong>SQL</strong> program issues a query and processesthe rows from the result set as shown in Example 7–27.Example 7–27Processing Query Results in a LOOPBEGIN-- use values from SELECT for FOR LOOP processingFOR someone IN (SELECT * FROM employees WHERE employee_id < 120 )LOOPDBMS_OUTPUT.PUT_LINE('First name = ' || someone.first_name ||', Last name = ' || someone.last_name);END LOOP;END;/You can use a simple loop like the one shown here, or you can control the processprecisely by using individual statements to perform the query, retrieve data, and finishprocessing.7.3.15 Using Dynamic <strong>SQL</strong> in PL/<strong>SQL</strong>PL/<strong>SQL</strong> supports both dynamic and static <strong>SQL</strong>. Dynamic <strong>SQL</strong> enables you to build<strong>SQL</strong> statements dynamically at runtime while static <strong>SQL</strong> statements are known inadvance. You can create more general purpose, flexible applications by using dynamic<strong>SQL</strong> because the full text of a <strong>SQL</strong> statement may be unknown at compilation. Foradditional information about dynamic <strong>SQL</strong>, see <strong>Oracle</strong> Database Application <strong>Developer</strong>'sGuide - Fundamentals.To process most dynamic <strong>SQL</strong> statements, you use the EXECUTE IMMEDIATEstatement. To process a multi-row query (SELECT statement), you use the OPEN-FOR,FETCH, and CLOSE statements.PL/<strong>SQL</strong>: Usage Information 7-19
Utilizing the Main Features of PL/<strong>SQL</strong>Example 7–28 illustrates several uses of dynamic <strong>SQL</strong>.Example 7–28Examples of Dynamic <strong>SQL</strong>-- create a standalone procedureCREATE OR REPLACE PROCEDURE raise_emp_salary (column_value NUMBER,emp_column VARCHAR2, amount NUMBER) IScolumn VARCHAR2(30);sql_stmt VARCHAR2(200);BEGIN-- determine if a valid column name has been given as inputSELECT COLUMN_NAME INTO column FROM USER_TAB_COLSWHERE TABLE_NAME = 'EMPLOYEES' AND COLUMN_NAME = emp_column;sql_stmt := 'UPDATE employees SET salary = salary + :1 WHERE '|| column || ' = :2';EXECUTE IMMEDIATE sql_stmt USING amount, column_value;IF <strong>SQL</strong>%ROWCOUNT > 0 THENDBMS_OUTPUT.PUT_LINE('Salaries have been updated for: ' || emp_column|| ' = ' || column_value);END IF;EXCEPTIONWHEN NO_DATA_FOUND THENDBMS_OUTPUT.PUT_LINE ('Invalid Column: ' || emp_column);END raise_emp_salary;/DECLAREplsql_block VARCHAR2(500);BEGIN-- note the semi-colons (;) inside the quotes '...'plsql_block := 'BEGIN raise_emp_salary(:cvalue, :cname, :amt); END;';EXECUTE IMMEDIATE plsql_block USING 110, 'DEPARTMENT_ID', 10;EXECUTE IMMEDIATE 'BEGIN raise_emp_salary(:cvalue, :cname, :amt); END;'USING 112, 'EMPLOYEE_ID', 10;END;/DECLAREsql_stmtVARCHAR2(200);columnVARCHAR2(30) := 'DEPARTMENT_ID';dept_id NUMBER(4) := 46;dept_nameVARCHAR2(30) := 'Special Projects';mgr_id NUMBER(6) := 200;loc_id NUMBER(4) := 1700;BEGIN-- note that there is no semi-colon (;) inside the quotes '...'EXECUTE IMMEDIATE 'CREATE TABLE bonus (id NUMBER, amt NUMBER)';sql_stmt := 'INSERT INTO departments VALUES (:1, :2, :3, :4)';EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, mgr_id, loc_id;EXECUTE IMMEDIATE 'DELETE FROM departments WHERE ' || column || ' = :num'USING dept_id;EXECUTE IMMEDIATE 'ALTER SESSION SET <strong>SQL</strong>_TRACE TRUE';EXECUTE IMMEDIATE 'DROP TABLE bonus';END;/-- rollback the changesROLLBACK;-- delete the procedureDROP PROCEDURE raise_emp_salary;7-20 <strong>SQL</strong> <strong>Developer</strong> Online Help
Handling PL/<strong>SQL</strong> Errors7.3.16 Using Bind VariablesWhen you embed an INSERT, UPDATE, DELETE, or SELECT <strong>SQL</strong> statement directly inyour PL/<strong>SQL</strong> code, PL/<strong>SQL</strong> turns the variables in the WHERE and VALUES clauses intobind variables automatically. <strong>Oracle</strong> can reuse these <strong>SQL</strong> statement each time the samecode is executed. To run similar statements with different variable values, you can saveparsing overhead by calling a stored procedure that accepts parameters, then issuesthe statements with the parameters substituted in the appropriate places.You do need to specify bind variables with dynamic <strong>SQL</strong>, in clauses like WHERE andVALUES where you normally use variables. Instead of concatenating literals andvariable values into a single string, replace the variables with the names of bindvariables (prefixed by a colon) and specify the corresponding PL/<strong>SQL</strong> variables withthe USING clause. Using the USING clause, instead of concatenating the variables intothe string, reduces parsing overhead and lets <strong>Oracle</strong> reuse the <strong>SQL</strong> statements.In Example 7–28, :1 and :2 are bind variables for amount and column_value. In thesame example, there are additional bind variables, such as :cvalue, :cname, and:amt.7.4 Handling PL/<strong>SQL</strong> ErrorsPL/<strong>SQL</strong> makes it easy to detect and process error conditions known as exceptions.When an error occurs, an exception is raised: normal execution stops and controltransfers to special exception-handling code, which comes at the end of any PL/<strong>SQL</strong>block. Each different exception is processed by a particular exception handler.PL/<strong>SQL</strong> exception handling is different from the manual checking you might be usedto from C programming, where you insert a check to make sure that every operationsucceeded. Instead, the checks and calls to error routines are performed automatically,similar to the exception mechanism in Java programming.Predefined exceptions are raised automatically for certain common error conditionsinvolving variables or database operations. For example, if you try to divide a numberby zero, PL/<strong>SQL</strong> raises the predefined exception ZERO_DIVIDE automatically. See"Summary of Predefined PL/<strong>SQL</strong> Exceptions" on page 7-21.You can declare exceptions of your own, for conditions that you decide are errors, or tocorrespond to database errors that normally result in ORA- error messages. When youdetect a user-defined error condition, you execute a RAISE statement. See "DeclaringPL/<strong>SQL</strong> Exceptions" on page 7-23.This topic includes the following topics:■ Summary of Predefined PL/<strong>SQL</strong> Exceptions■ Using the Exception Handler■ Declaring PL/<strong>SQL</strong> Exceptions■ Scope Rules for PL/<strong>SQL</strong> Exceptions■ Continuing After an Exception is Raised7.4.1 Summary of Predefined PL/<strong>SQL</strong> ExceptionsAn internal exception is raised automatically if your PL/<strong>SQL</strong> program violates an<strong>Oracle</strong> rule or exceeds a system-dependent limit. PL/<strong>SQL</strong> predefines some common<strong>Oracle</strong> errors as exceptions. For example, PL/<strong>SQL</strong> raises the predefined exception NO_DATA_FOUND if a SELECT INTO statement returns no rows.PL/<strong>SQL</strong>: Usage Information 7-21
Handling PL/<strong>SQL</strong> ErrorsTo handle unexpected <strong>Oracle</strong> errors, you can use the OTHERS handler. Within thishandler, you can call the functions <strong>SQL</strong>CODE and <strong>SQL</strong>ERRM to return the <strong>Oracle</strong> errorcode and message text.PL/<strong>SQL</strong> declares predefined exceptions globally in package STANDARD. You need notdeclare them yourself. You can write handlers for predefined exceptions using thenames in Table 7–1.Table 7–1ExceptionACCESS_INTO_NULLCASE_NOT_FOUNDCOLLECTION_IS_NULLCURSOR_ALREADY_OPENDUP_VAL_ON_INDEXINVALID_CURSORINVALID_NUMBERLOGIN_DENIEDNO_DATA_FOUNDNOT_LOGGED_ONPROGRAM_ERRORROWTYPE_MISMATCHSELF_IS_NULLSTORAGE_ERRORSUBSCRIPT_BEYOND_COUNTSUBSCRIPT_OUTSIDE_LIMITSYS_INVALID_ROWIDTIMEOUT_ON_RESOURCEPredefined PL/<strong>SQL</strong> ExceptionsDescriptionA program attempts to assign values to the attributes of an uninitialized objectNone of the choices in the WHEN clauses of a CASE statement is selected, andthere is no ELSE clause.A program attempts to apply collection methods other than EXISTS to anuninitialized nested table or varray, or the program attempts to assign values tothe elements of an uninitialized nested table or varray.A program attempts to open an already open cursor. A cursor must be closedbefore it can be reopened. A cursor FOR loop automatically opens the cursor towhich it refers, so your program cannot open that cursor inside the loop.A program attempts to store duplicate values in a column that is constrained bya unique index.A program attempts a cursor operation that is not allowed, such as closing anunopened cursor.n a <strong>SQL</strong> statement, the conversion of a character string into a number failsbecause the string does not represent a valid number. (In procedural statements,VALUE_ERROR is raised.) This exception is also raised when the LIMIT-clauseexpression in a bulk FETCH statement does not evaluate to a positive number.A program attempts to log on to <strong>Oracle</strong> with an invalid username or password.A SELECT INTO statement returns no rows, or your program references adeleted element in a nested table or an uninitialized element in an index-bytable.Because this exception is used internally by some <strong>SQL</strong> functions to signalcompletion, you should not rely on this exception being propagated if you raiseit within a function that is called as part of a query.A program issues a database call without being connected to <strong>Oracle</strong>.PL/<strong>SQL</strong> has an internal problem.The host cursor variable and PL/<strong>SQL</strong> cursor variable involved in anassignment have incompatible return types. When an open host cursor variableis passed to a stored subprogram, the return types of the actual and formalparameters must be compatible.A program attempts to call a MEMBER method, but the instance of the objecttype has not been initialized. The built-in parameter SELF points to the object,and is always the first parameter passed to a MEMBER method.PL/<strong>SQL</strong> runs out of memory or memory has been corrupted.A program references a nested table or varray element using an index numberlarger than the number of elements in the collection.A program references a nested table or varray element using an index number(-1 for example) that is outside the legal range.The conversion of a character string into a universal rowid fails because thecharacter string does not represent a valid rowid.A time out occurs while <strong>Oracle</strong> is waiting for a resource.7-22 <strong>SQL</strong> <strong>Developer</strong> Online Help
Handling PL/<strong>SQL</strong> ErrorsExceptionTOO_MANY_ROWSVALUE_ERRORZERO_DIVIDETable 7–1(Cont.) Predefined PL/<strong>SQL</strong> ExceptionsDescriptionA SELECT INTO statement returns more than one row.An arithmetic, conversion, truncation, or size-constraint error occurs. Forexample, when your program selects a column value into a character variable, ifthe value is longer than the declared length of the variable, PL/<strong>SQL</strong> aborts theassignment and raises VALUE_ERROR. In procedural statements, VALUE_ERRORis raised if the conversion of a character string into a number fails. (In <strong>SQL</strong>statements, INVALID_NUMBER is raised.)A program attempts to divide a number by zero.7.4.2 Using the Exception HandlerUsing exceptions for error handling has several advantages. With exceptions, you canreliably handle potential errors from many statements with a single exception handler:Example 7–29Managing Multiple Errors With a Single Exception HandlerDECLARE -- declare variablesemp_column VARCHAR2(30) := 'last_name';table_name VARCHAR2(30) := 'emp'; -- set value to raise errortemp_varVARCHAR2(30);BEGINtemp_var := emp_column;SELECT COLUMN_NAME INTO temp_var FROM USER_TAB_COLSWHERE TABLE_NAME = 'EMPLOYEES' AND COLUMN_NAME = UPPER(emp_column);-- processing heretemp_var := table_name;SELECT OBJECT_NAME INTO temp_var FROM USER_OBJECTSWHERE OBJECT_NAME = UPPER(table_name) AND OBJECT_TYPE = 'TABLE';-- processing hereEXCEPTIONWHEN NO_DATA_FOUND THEN -- catches all 'no data found' errorsDBMS_OUTPUT.PUT_LINE ('No Data found for SELECT on ' || temp_var);END;/7.4.3 Declaring PL/<strong>SQL</strong> ExceptionsExceptions can be declared only in the declarative part of a PL/<strong>SQL</strong> block,subprogram, or package. You declare an exception by introducing its name, followedby the keyword EXCEPTION. In Example 7–30, you declare an exception namedpast_due that is raised when the due_date is less than the today's date.Exception and variable declarations are similar. But remember, an exception is an errorcondition, not a data item. Unlike variables, exceptions cannot appear in assignmentstatements or <strong>SQL</strong> statements. However, the same scope rules apply to variables andexceptions.7.4.4 Scope Rules for PL/<strong>SQL</strong> ExceptionsYou cannot declare an exception twice in the same block. You can, however, declare thesame exception in two different blocks.Exceptions declared in a block are considered local to that block and global to all itssub-blocks. Because a block can reference only local or global exceptions, enclosingblocks cannot reference exceptions declared in a sub-block.PL/<strong>SQL</strong>: Usage Information 7-23
Handling PL/<strong>SQL</strong> ErrorsIf you redeclare a global exception in a sub-block, the local declaration prevails. Thesub-block cannot reference the global exception, unless the exception is declared in alabeled block and you qualify its name with the block label:block_label.exception_nameExample 7–30 illustrates the scope rules:Example 7–30Scope of PL/<strong>SQL</strong> ExceptionsDECLAREpast_due EXCEPTION;acct_num NUMBER;BEGINDECLARE ---------- sub-block beginspast_due EXCEPTION; -- this declaration prevailsacct_num NUMBER;due_date DATE := SYSDATE - 1; -- set on purpose to raise exceptiontodays_date DATE := SYSDATE;BEGINIF due_date < todays_date THENRAISE past_due; -- this is not handledEND IF;END; ------------- sub-block endsEXCEPTIONWHEN past_due THEN -- does not handle raised exceptionDBMS_OUTPUT.PUT_LINE('Handling PAST_DUE exception.');WHEN OTHERS THENDBMS_OUTPUT.PUT_LINE('Could not recognize PAST_DUE_EXCEPTION in this scope.');END;/The enclosing block does not handle the raised exception because the declaration ofpast_due in the sub-block prevails. Though they share the same name, the twopast_due exceptions are different, just as the two acct_num variables share the samename but are different variables. Thus, the RAISE statement and the WHEN clause referto different exceptions. To have the enclosing block handle the raised exception, youmust remove its declaration from the sub-block or define an OTHERS handler.7.4.5 Continuing After an Exception is RaisedBy default, you put an exception handler at the end of a subprogram to handleexceptions that are raised anywhere inside the subprogram. To continue executingfrom the spot where an exception happens, enclose the code that might raise anexception inside another BEGIN-END block with its own exception handler. Forexample, you might put separate BEGIN-END blocks around groups of <strong>SQL</strong> statementsthat might raise NO_DATA_FOUND, or around arithmetic operations that might raiseDIVIDE_BY_ZERO. By putting a BEGIN-END block with an exception handler inside aloop, you can continue executing the loop even if some loop iterations raiseexceptions.You can still handle an exception for a statement, then continue with the nextstatement. Place the statement in its own sub-block with its own exception handlers. Ifan error occurs in the sub-block, a local handler can catch the exception. When thesub-block ends, the enclosing block continues to execute at the point where thesub-block ends, as shown in Example 7–31.7-24 <strong>SQL</strong> <strong>Developer</strong> Online Help
Handling PL/<strong>SQL</strong> ErrorsExample 7–31Continuing After an Exception-- create a temporary table for this exampleCREATE TABLE employees_temp ASSELECT employee_id, salary, commission_pct FROM employees;DECLAREsal_calc NUMBER(8,2);BEGININSERT INTO employees_temp VALUES (303, 2500, 0);BEGIN -- sub-block beginsSELECT salary / commission_pct INTO sal_calc FROM employees_tempWHERE employee_id = 303;EXCEPTIONWHEN ZERO_DIVIDE THENsal_calc := 2500;END; -- sub-block endsINSERT INTO employees_temp VALUES (304, sal_calc/100, .1);EXCEPTIONWHEN ZERO_DIVIDE THENNULL;END;/-- view the resultsSELECT * FROM employees_temp WHERE employee_id = 303 OR employee_id = 304;-- drop the temporary tableDROP TABLE employees_temp;In this example, if the SELECT INTO statement raises a ZERO_DIVIDE exception, thelocal handler catches it and sets sal_calc to 2500. Execution of the handler iscomplete, so the sub-block terminates, and execution continues with the INSERTstatement.PL/<strong>SQL</strong>: Usage Information 7-25
Handling PL/<strong>SQL</strong> Errors7-26 <strong>SQL</strong> <strong>Developer</strong> Online Help
8Subprograms and Packages: UsageInformationThe topic discusses the development of packages and subprograms with PL/<strong>SQL</strong>. Itincludes the following topics:■■■■Overview of Packages and SubprogramsManaging SubprogramsManaging Packages<strong>Oracle</strong> Product-Specific PackagesSee Also:■■"Using PL/<strong>SQL</strong> Packages" in PL/<strong>SQL</strong> User's Guide and Reference foradditional information on PL/<strong>SQL</strong> packages."Using PL/<strong>SQL</strong> Subprograms" in PL/<strong>SQL</strong> User's Guide andReference for information on PL/<strong>SQL</strong> subprogramsNote: Many examples use the <strong>Oracle</strong> HR sample schema. Forinformation on the sample schemas, see <strong>Oracle</strong> Database SampleSchemas.8.1 Overview of Packages and Subprograms<strong>Oracle</strong> offers the capability to store programs in the database. This functionalityenables commonly required code to be written and tested once and then accessed byany application that requires the code. Database-resident program units also ensurethat the same processing is applied to the data when the code is invoked, making thedevelopment of applications easier and providing consistency between developers.You can write database-resident programs in PL/<strong>SQL</strong> and manage source types suchas PL/<strong>SQL</strong> packages, procedures, functions, and triggers. The actions include creating,compiling, creating synonyms for, granting privileges on, and showing dependenciesfor these source types.Subprograms and Packages: Usage Information describes the main types of PL/<strong>SQL</strong>program units: packages, package bodies, and subprograms.You can use PL/<strong>SQL</strong> to develop packages and stored (standalone) subprograms. Bothpackages and stored subprograms are saved and stored in the database and can beused as building blocks for applications.Subprograms and Packages: Usage Information 8-1
Overview of Packages and SubprogramsThis topic includes the following topics:■■Stored SubprogramsPackages8.1.1 Stored Subprograms8.1.2 PackagesSee Also: PL/<strong>SQL</strong> User's Guide and Reference to learn about PL/<strong>SQL</strong>code and program units.Subprograms, which are either functions or procedures, can be compiled and stored inan <strong>Oracle</strong> database, ready to be executed. Once compiled, it is a schema object knownas a stored procedure or stored function, which can be referenced by any number ofapplications connected to that database.The <strong>SQL</strong> CREATE PROCEDURE statement is used to create stored procedures that arestored in the database. The <strong>SQL</strong> CREATE FUNCTION statement is used to create storedfunctions that are stored in an <strong>Oracle</strong> database.See Also:■■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on CREATEPROCEDURE.<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on CREATEFUNCTION.Subprograms are stored in a compact compiled form. When called, they are loadedand processed immediately. Subprograms take advantage of shared memory, so thatonly one copy of a subprogram is loaded into memory for execution by multiple users.See Also: <strong>Oracle</strong> Database Express Edition 2 Day DBA Guide forinformation on managing memory with <strong>Oracle</strong> DatabaseStored subprograms defined within a package are known as packaged subprograms.Those defined independently are called stored or standalone subprograms.Subprograms nested inside other subprograms or within a PL/<strong>SQL</strong> block are knownas local subprograms, which cannot be referenced by other applications and exist onlyinside the enclosing block.Stored subprograms are the key to modular, reusable PL/<strong>SQL</strong> code. Wherever youmight use a JAR file in Java, a module in Perl, a shared library in C++, or a DLL inVisual Basic, you should use PL/<strong>SQL</strong> stored procedures, stored functions, andpackages.You can call stored subprograms from a database trigger, another stored subprogram,or interactively from <strong>SQL</strong>*Plus. You can also configure a web server so that the HTMLfor a web page is generated by a stored subprogram, making it simple to provide aweb interface for data entry and report generation.A package is a schema object that groups logically related PL/<strong>SQL</strong> types, variables,and subprograms. Packages usually have two parts, a specification (spec) and a body;sometimes the body is unnecessary. The specification is the interface to the package. Itdeclares the types, variables, constants, exceptions, cursors, and subprograms that canbe referenced from outside the package. The body defines the queries for the cursorsand the code for the subprograms.8-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
Managing PackagesYou can think of the spec as an interface and of the body as a black box. You candebug, enhance, or replace a package body without changing the package spec.The <strong>SQL</strong> CREATE PACKAGE statement is used to create package specification (specs).The CREATE PACKAGE BODY statement is used to define the package body.See Also:The spec holds public declarations, which are visible to stored procedures and othercode outside the package. You must declare subprograms at the end of the spec afterall other items (except pragmas that name a specific function; such pragmas mustfollow the function spec).The body holds implementation details and private declarations, which are hiddenfrom code outside the package. Following the declarative part of the package body isthe optional initialization part, which holds statements that initialize package variablesand do any other one-time setup steps.8.2 Managing SubprogramsSubprograms do not have to belong to a package. Program units that are createdoutside of a package are called stored or standalone subprograms. Stored subprogramscan be either functions or procedures. These subprograms are stored in the databaseand can be reused by multiple applications. Both procedures and functions can acceptparameters when they are executed (called). To execute a stored subprogram, you onlyneed to include its object name.A PL/<strong>SQL</strong> procedure is a subprogram that performs a specific action. You specify thename of the procedure, its parameters, its local variables, and the BEGIN-END blockthat contains its code and handles any exceptions. A function is a subprogram thatcomputes a value. Functions and procedures are structured alike, except that functionsreturn a value. For information on subprograms in PL/<strong>SQL</strong> blocks, see Using LocalPL/<strong>SQL</strong> Subprograms in PL/<strong>SQL</strong> Blocks.8.3 Managing Packages■■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the CREATEPACKAGE <strong>SQL</strong> statement.<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the CREATEPACKAGE BODY <strong>SQL</strong> statement.With PL/<strong>SQL</strong>, you can break an application down into manageable, well-definedmodules. Using PL/<strong>SQL</strong> code, you can write program units that are stored as databaseobjects that can be reused. These objects include packages, subprograms, and triggers.Subprograms and packages are discussed in this topic; triggers are discussed inTriggers: Usage Information.When writing packages, keep them general so they can be reused in futureapplications. Become familiar with the <strong>Oracle</strong>-supplied packages, and avoid writingpackages that duplicate features already provided by <strong>Oracle</strong>.Design and define package specs before the package bodies. Place in a spec only thosethings that must be visible to calling programs. That way, other developers cannotbuild unsafe dependencies on your implementation details.To reduce the need for recompiling when code is changed, place as few items aspossible in a package spec. Changes to a package body do not require recompilingSubprograms and Packages: Usage Information 8-3
Managing Packagescalling procedures. Changes to a package spec require <strong>Oracle</strong> to recompile everystored subprogram that references the package.8.3.1 Calling Subprograms in PackagesPackages are stored in the database, where they can be shared by many applications.Calling a packaged subprogram for the first time loads the whole package and cachesit in memory, saving on disk I/O for subsequent calls. Thus, packages enhance reuseand improve performance in a multiuser, multi-application environment.If a subprogram does not take any parameters, you can include an empty set ofparentheses or omit the parentheses, both in PL/<strong>SQL</strong> and in functions called from <strong>SQL</strong>queries. For calls to a method that takes no parameters, an empty set of parentheses isoptional within PL/<strong>SQL</strong> scopes but required within <strong>SQL</strong> scopes.8.3.2 Accessing Variables in PackagesYou can create a package specification that is designated only to supply commonvariables to other packages or subprograms. With the variables in one package, theycan be easily maintained for all subprograms that use the variables, rather thanmaintaining the variables in all the individual subprograms. These common variablesare typically used in multiple subprograms, such as a sales tax rate.In Example 8–1, the variables my_pi and my_e can be used by any subprogram. If youchange the value of my_pi or my_e, then all subprograms that use the variable get thenew value without having to change anything in those individual subprograms.Note that you need to use of the package name as a prefix to the variable name, suchas my_pkg.my_pi.Example 8–1Using Variables in PackagesCREATE PACKAGE my_pkg ASmy_pi NUMBER := 3.14016408289008292431940027343666863227;my_e NUMBER := 2.71828182845904523536028747135266249775;my_sales_tax NUMBER := 0.0825END my_pkg;/CREATE PROCEDURE circle_area(radius NUMBER) ISmy_area NUMBER;my_datatype VARCHAR2(30);BEGINmy_area := my_pkg.my_pi * radius;DBMS_OUTPUT.PUT_LINE('Radius: ' || TO_CHAR(radius)|| ' Area: ' || TO_CHAR(my_area) );END;/-- call the circle_area procedure with radius equal to 3CALL circle_area(3);-- call the circle_area procedure with radius equal to 4BEGINcircle_area(3);END;/-- cleanup: drop package and procedureDROP PROCEDURE circle_area;DROP PACKAGE my_pkg;8-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>Oracle</strong> Product-Specific Packages8.4 <strong>Oracle</strong> Product-Specific Packages<strong>Oracle</strong> and various <strong>Oracle</strong> tools are supplied with product-specific packages thatdefine application programming interfaces (APIs) you can call from PL/<strong>SQL</strong>, <strong>SQL</strong>,Java, or other programming environments. This topic includes a summary of twowidely used packages and a list of the most common packages with a briefdescription.See Also:■PL/<strong>SQL</strong> Packages and Types Reference for information on and usageof product-specific packages.About the DBMS_OUTPUT PackagePackage DBMS_OUTPUT enables you to display output from PL/<strong>SQL</strong> blocks,subprograms, packages, and triggers. The package is especially useful for displayingPL/<strong>SQL</strong> debugging information. The procedure PUT_LINE outputs information to abuffer that can be read by another trigger, procedure, or package. You display theinformation by calling the procedure GET_LINE or by setting SERVEROUTPUT ON in<strong>SQL</strong>*Plus. See Inputting and Outputting Data with PL/<strong>SQL</strong>.Example 8–2 shows how to display output from a PL/<strong>SQL</strong> block.Example 8–2Using PUT_LINE in the DBMS_OUTPUT Package-- set server output to ON to display output from DBMS_OUTPUTSET SERVEROUTPUT ONBEGINDBMS_OUTPUT.PUT_LINE('These are the tables that ' || USER || ' owns:');FOR item IN (SELECT table_name FROM user_tables)LOOPDBMS_OUTPUT.PUT_LINE(item.table_name);END LOOP;END;/About the UTL_FILE PackagePackage UTL_FILE lets PL/<strong>SQL</strong> programs read and write operating system (OS) textfiles. It provides a restricted version of standard OS stream file I/O, including open,put, get, and close operations.When you want to read or write a text file, you call the function FOPEN, which returnsa file handle for use in subsequent procedure calls. For example, the procedure PUT_LINE writes a text string and line terminator to an open file, and the procedure GET_LINE reads a line of text from an open file into an output buffer.Common <strong>Oracle</strong> Supplied PackagesTable 8–1 provides a list of the common PL/<strong>SQL</strong> packages included with <strong>Oracle</strong>Database.Table 8–1Package NameDBMS_ALERTSummary of <strong>Oracle</strong> Supplied PL/<strong>SQL</strong> PackagesDBMS_APPLICATION_INFODescriptionProvides support for the asynchronous notification ofdatabase events.Lets you register an application name with the databasefor auditing or performance tracking purposes.Subprograms and Packages: Usage Information 8-5
<strong>Oracle</strong> Product-Specific PackagesTable 8–1Package NameDBMS_AQDBMS_AQADMDBMS_AQELMDBMS_AQINDBMS_CHANGE_NOTIFICATIONDBMS_CRYPTODBMS_DATAPUMPDBMS_DB_VERSIONDBMS_DDLDBMS_DEBUGDBMS_DESCRIBEDBMS_EPGDBMS_ERRLOGDMBS_FILE_TRANSFERDMBS_FLASHBACKDBMS_JOBDBMS_LOBDBMS_LOCK(Cont.) Summary of <strong>Oracle</strong> Supplied PL/<strong>SQL</strong> PackagesDescriptionLets you add a message (of a predefined object type)onto a queue or to dequeue a message.Lets you perform administrative functions on a queue orqueue table for messages of a predefined object type.Provides procedures to manage the configuration ofAdvanced Queuing asynchronous notification by e-mailand HTTP.Plays a part in providing secure access to the <strong>Oracle</strong> JMSinterfaces.Is part of a set of features that clients use to receivenotifications when result sets of a query have changed.The package contains interfaces that can be used bymid-tier clients to register objects and specify deliverymechanisms.Lets you encrypt and decrypt stored data, can be used inconjunction with PL/<strong>SQL</strong> programs running networkcommunications, and supports encryption and hashingalgorithms.Lets you move all, or part of, a database betweendatabases, including both data and metadata.Specifies the <strong>Oracle</strong> version numbers and otherinformation useful for simple conditional compilationselections based on <strong>Oracle</strong> versions.Provides access to some <strong>SQL</strong> DDL statements fromstored procedures, and provides special administrationoperations not available as DDLs.Implements server-side debuggers and provides a wayto debug server-side PL/<strong>SQL</strong> program units.Describes the arguments of a stored procedure with fullname translation and security checking.Implements the embedded PL/<strong>SQL</strong> gateway thatenables a web browser to invoke a PL/<strong>SQL</strong> storedprocedure through an HTTP listener.Provides a procedure that enables you to create an errorlogging table so that DML operations can continue afterencountering errors rather than abort and roll back.Lets you copy a binary file within a database or totransfer a binary file between databases.Lets you flash back to a version of the database at aspecified wall-clock time or a specified system changenumber (SCN).Lets you schedule administrative procedures that youwant performed at periodic intervals; it is also theinterface for the job queue.Provides general purpose routines for operations on<strong>Oracle</strong> Large Object (LOBs) data types - BLOB, CLOB(read/write), and BFILEs (read-only).Lets you request, convert and release locks through<strong>Oracle</strong> Lock Management services.8-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>Oracle</strong> Product-Specific PackagesTable 8–1Package NameDBMS_METADATADBMS_OBFUSCATION_TOOLKITDBMS_OUTPUTDBMS_PIPEDBMS_RANDOMDBMS_RESUMABLEDBMS_ROWIDDBMS_SCHEDULERDBMS_SERVER_ALERTDBMS_SESSIONDBMS_<strong>SQL</strong>DBMS_TDBDBMS_TTSDBMS_TYPESDBMS_UTILITYDBMS_WARNINGDBMS_XDBDBMS_XDB_VERSIONDBMS_XDBTDBMS_XDBZDBMS_XMLDOMDBMS_XMLGENDBMS_XMLPARSERDMBS_XMLQUERY(Cont.) Summary of <strong>Oracle</strong> Supplied PL/<strong>SQL</strong> PackagesDescriptionLets callers easily retrieve complete database objectdefinitions (metadata) from the dictionary.Provides procedures for Data Encryption Standards.Accumulates information in a buffer so that it can beretrieved later.Provides a DBMS pipe service which enables messagesto be sent between sessions.Provides a built-in random number generator.Lets you suspend large operations that run out of spaceor reach space limits after executing for a long time, fixthe problem, and make the statement resume execution.Provides procedures to create rowids and to interprettheir contents.Provides a collection of scheduling functions that arecallable from any PL/<strong>SQL</strong> program.Lets you issue alerts when some threshold has beenviolated.Provides access to <strong>SQL</strong> ALTER SESSION statements,and other session information, from stored procedures.Lets you use dynamic <strong>SQL</strong> to access the database.Reports whether a database can be transported betweenplatforms using the RMAN CONVERT DATABASEcommand. It verifies that databases on the current hostplatform are of the same endian format as the destinationplatform, and that the state of the current database doesnot prevent transport of the database.Checks if the transportable set is self-contained.Consists of constants, which represent the built-in anduser-defined types.Provides various utility routines.Provides the interface to query, modify and deletecurrent system or session settings.Describes Resource Management and Access ControlAPIs for PL/<strong>SQL</strong>Describes versioning APIsDescribes how an administrator can create a ConTextindex on the XML DB hierarchy and configure it forautomatic maintenanceControls the <strong>Oracle</strong> XML DB repository security, which isbased on Access Control Lists (ACLs).Explains access to XMLType objectsConverts the results of a <strong>SQL</strong> query to a canonical XMLformat.Explains access to the contents and structure of XMLdocuments.Provides database-to-XMLType functionality.Subprograms and Packages: Usage Information 8-7
<strong>Oracle</strong> Product-Specific PackagesTable 8–1Package NameDBMS_XMLSAVEDBMS_XMLSCHEMADBMS_XMLSTOREDBMS_XPLANDBMS_XSLPROCESSORHTFHTMLDB_APPLICATIONHTMLDB_CUSTOM_AUTHHTMLDB_ITEMHTMLDB_UTILHTPOWA_CACHEOWA_COOKIEOWA_CUSTOMOWA_IMAGEOWA_OPT_LOCKOWA_PATTERNOWA_SECOWA_TEXTOWA_UTILUTL_COLLUTL_COMPRESSUTL_DBWS(Cont.) Summary of <strong>Oracle</strong> Supplied PL/<strong>SQL</strong> PackagesDescriptionProvides XML-to-database-type functionality.Explains procedures to register and delete XML schemas.Provides the ability to store XML data in relationaltables.Describes how to format the output of the EXPLAINPLAN command.Explains access to the contents and structure of XMLdocuments.Hypertext functions generate HTML tags.Enables users to take advantage of global variablesEnables users to create form elements dynamically basedon a <strong>SQL</strong> query instead of creating individual items pageby page.Enables users to create form elements dynamically basedon a <strong>SQL</strong> query instead of creating individual items pageby page.Provides utilities for getting and setting session state,getting files, checking authorizations for users, resettingdifferent states for users, and also getting and settingpreferences for users.Hypertext procedures generate HTML tags.Provides an interface that enables the PL/<strong>SQL</strong> Gatewaycache to improve the performance of PL/<strong>SQL</strong> webapplications.Provides an interface for sending and retrieving HTTPcookies from the client's browser.Provides a Global PL<strong>SQL</strong> Agent Authorization callbackfunctionProvides an interface to access the coordinates where auser clicked on an image.Contains subprograms that impose optimistic lockingstrategies so as to prevent lost updates.Provides an interface to locate text patterns withinstrings and replace the matched string with anotherstring.Provides an interface for custom authentication.Contains subprograms used by OWA_PATTERN formanipulating strings. They are externalized so you canuse them directly.Contains utility subprograms for performing operationssuch as getting the value of CGI environment variables,printing the data that is returned to the client, andprinting the results of a query in an HTML table.Enables PL/<strong>SQL</strong> programs to use collection locators toquery and update.Provides a set of data compression utilities.Provides database web services.8-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>Oracle</strong> Product-Specific PackagesTable 8–1Package NameUTL_ENCODEUTL_FILEUTL_HTTPUTL_I18NUTL_INADDRUTL_LMSUTL_MAILUTL_RAWUTL_RECOMPUTL_REFUTL_SMTPUTL_TCPUTL_URL(Cont.) Summary of <strong>Oracle</strong> Supplied PL/<strong>SQL</strong> PackagesDescriptionProvides functions that encode RAW data into astandard encoded format so that the data can betransported between hosts.Enables your PL/<strong>SQL</strong> programs to read and writeoperating system text files and provides a restrictedversion of standard operating system stream file I/O.Enables HTTP callouts from PL/<strong>SQL</strong> and <strong>SQL</strong> to accessdata on the Internet or to call <strong>Oracle</strong> Web ServerCartridges.Provides a set of services (<strong>Oracle</strong> Globalization Service)that help developers build multilingual applications.Provides a procedure to support internet addressing.Retrieves and formats error messages in differentlanguages.A utility for managing email which includes commonlyused email features, such as attachments, CC, BCC, andreturn receipt.Provides <strong>SQL</strong> functions for RAW data types that concat,substr to and from RAWS.Recompiles invalid PL/<strong>SQL</strong> modules, Java classes,indextypes and operators in a database, eithersequentially or in parallel.Enables a PL/<strong>SQL</strong> program to access an object byproviding a reference to the object.Provides PL/<strong>SQL</strong> functionality to send emails.Provides PL/<strong>SQL</strong> functionality to support simpleTCP/IP-based communications between servers and theoutside world.Provides escape and unescape mechanisms for URLcharacters.Subprograms and Packages: Usage Information 8-9
<strong>Oracle</strong> Product-Specific Packages8-10 <strong>SQL</strong> <strong>Developer</strong> Online Help
9Triggers: Usage InformationThis topic discusses the use of database triggers with <strong>Oracle</strong> Express. Triggers aredatabase objects that can be created with PL/<strong>SQL</strong> code. This topic includes thefollowing topics:■■Overview of TriggersDesigning Triggers9.1 Overview of TriggersA database trigger is a stored subprogram associated with a database table, view, orevent. The trigger can be called once, when some event occurs, or many times, once foreach row affected by an INSERT, UPDATE, or DELETE statement. The trigger can becalled after the event, to record it or take some follow-up action. Or, the trigger can becalled before the event to prevent erroneous operations or fix new data so that itconforms to business rules. The executable part of a trigger can contain proceduralstatements as well as <strong>SQL</strong> data manipulation statements.Triggers are created using the <strong>SQL</strong> CREATE TRIGGER statement. The CREATE (orCREATE OR REPLACE) statement fails if any errors exist in the PL/<strong>SQL</strong> block.■■■■■■■■See Also:■■■<strong>Oracle</strong> Database Concepts for information on triggers.<strong>Oracle</strong> Database Application <strong>Developer</strong>'s Guide - Fundamentals forinformation on triggers.<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the CREATETRIGGER <strong>SQL</strong> statement.Types of TriggersNaming TriggersWhen Is the Trigger Fired?Controlling When a Trigger Is FiredAccessing Column Values in Row TriggersDetecting the DML Operation That Fired a TriggerEnabled and Disabled Trigger ModesError Conditions and Exceptions in the Trigger BodySee Also: <strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on triggercreation syntaxTriggers: Usage Information 9-1
Overview of Triggers9.1.1 Types of Triggers9.1.2 Naming TriggersA trigger is either a stored PL/<strong>SQL</strong> block or a PL/<strong>SQL</strong>, or C procedure associated witha table, view, schema, or the database itself. <strong>Oracle</strong> automatically executes a triggerwhen a specified event takes place, which usually is a DML statement being issuedagainst the table.You can create triggers to be fired on any of the following:■ DML statements (DELETE, INSERT, UPDATE)■■DDL statements (CREATE, ALTER, DROP)Database operations (LOGON, LOGOFF)Trigger names must be unique with respect to other triggers in the same schema.Trigger names do not need to be unique with respect to other schema objects, such astables, views, and procedures. For example, a table and a trigger can have the samename; however, to avoid confusion, this is not recommended.9.1.3 When Is the Trigger Fired?A trigger is fired based on a triggering statement, which specifies:■The <strong>SQL</strong> statement or the system event, database event, or DDL event that firesthe trigger body. The options include DELETE, INSERT, and UPDATE. One, two, orall three of these options can be included in the triggering statement specification.■ The table, view, DATABASE, or SCHEMA associated with the trigger.If a trigger contained the following statement:AFTER DELETE OR INSERT OR UPDATE ON employees ...then any of the following statements would fire the trigger:DELETE FROM employees WHERE ...;INSERT INTO employees VALUES ( ... );INSERT INTO employees SELECT ... FROM ... ;UPDATE employees SET ... ;An UPDATE statement might include a list of columns. If a triggering statementincludes a column list, the trigger is fired only when one of the specified columns isupdated. If a triggering statement omits a column list, the trigger is fired when anycolumn of the associated table is updated. A column list cannot be specified forINSERT or DELETE triggering statements.9.1.4 Controlling When a Trigger Is FiredThere are several ways to control when a trigger is fired.9.1.4.1 Firing Triggers With the BEORE and AFTER OptionsThe BEFORE or AFTER option in the CREATE TRIGGER statement specifies exactlywhen to fire the trigger body in relation to the triggering statement that is being run. Ina CREATE TRIGGER statement, the BEFORE or AFTER option is specified just before thetriggering statement.In general, you use BEFORE or AFTER triggers to achieve the following results:9-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
Overview of Triggers■■Use a BEFORE row trigger to modify the row before the row data is written to disk.Use an AFTER row trigger to obtain, and perform operations, using the row Id.Note: BEFORE row triggers are slightly more efficient than AFTERrow triggers. With AFTER row triggers, affected data blocks must beread (logical read, not physical read) once for the trigger and thenagain for the triggering statement. Alternatively, with BEFORE rowtriggers, the data blocks must be read only once for both the triggeringstatement and the trigger.If an UPDATE or DELETE statement detects a conflict with a concurrent UPDATE, then<strong>Oracle</strong> performs a transparent ROLLBACK and restarts the update. This can occurmany times before the statement completes successfully. Each time the statement isrestarted, the BEFORE statement trigger is fired again. The rollback does not undochanges to any package variables referenced in the trigger. Your package shouldinclude a counter variable to detect this situation.9.1.4.2 Firing Triggers With the FOR EACH ROW OptionThe FOR EACH ROW option determines whether the trigger is a row trigger or astatement trigger. If you specify FOR EACH ROW, then the trigger fires once for each rowof the table that is affected by the triggering statement. These triggers are referred to asrow-level triggers.The absence of the FOR EACH ROW option indicates that the trigger fires only once foreach applicable statement, but not separately for each row affected by the statement.These triggers are referred to as statement-level triggers and are useful for performingvalidation checks for the entire statement.9.1.4.3 Firing Triggers Based on Conditions (WHEN Clause)An optional trigger restriction can be included in the definition of a row trigger byspecifying a Boolean <strong>SQL</strong> expression in a WHEN clause.If included, then the expression in the WHEN clause is evaluated for each row that thetrigger affects. If the expression evaluates to TRUE for a row, then the trigger body isfired on behalf of that row.The expression in a WHEN clause must be a <strong>SQL</strong> expression, and it cannot include asubquery. You cannot use a PL/<strong>SQL</strong> expression (including user-defined functions) inthe WHEN clause. A WHEN clause cannot be included in the definition of a statementtrigger.9.1.5 Accessing Column Values in Row TriggersWithin a trigger body of a row trigger, the PL/<strong>SQL</strong> code and <strong>SQL</strong> statements haveaccess to the old and new column values of the current row affected by the triggeringstatement. Two correlation names exist for every column of the table being modified:one for the old column value, and one for the new column value. These columns in thetable are identified by :OLD.colum_name and :NEW.column_name.Depending on the type of triggering statement, certain correlation names might nothave any meaning.■A trigger fired by an INSERT statement has meaningful access to new columnvalues only. Because the row is being created by the INSERT, the old values arenull.Triggers: Usage Information 9-3
Overview of Triggers■■A trigger fired by an UPDATE statement has access to both old and new columnvalues for both BEFORE and AFTER row triggers.A trigger fired by a DELETE statement has meaningful access to :OLD columnvalues only. Because the row no longer exists after the row is deleted, the :newvalues are NULL and cannot be modified.Old and new values are available in both BEFORE and AFTER row triggers. A newcolumn value can be assigned in a BEFORE row trigger, but not in an AFTER rowtrigger (because the triggering statement takes effect before an AFTER row trigger isfired). If a BEFORE row trigger changes the value of NEW.column, then an AFTER rowtrigger fired by the same statement sees the change assigned by the BEFORE rowtrigger.Correlation names can also be used in the Boolean expression of a WHEN clause. Acolon (:) must precede the OLD and NEW qualifiers when they are used in a triggerbody, but a colon is not allowed when using the qualifiers in the WHEN clause.9.1.6 Detecting the DML Operation That Fired a TriggerIf more than one type of DML operation can fire a trigger, such as ON INSERT ORUPDATE, the trigger body can use the conditional predicates INSERTING, DELETING,and UPDATING to check which type of statement fire the trigger.Within the code of the trigger body, you can execute blocks of code depending on thekind of DML operation fired the trigger.In an UPDATE trigger, a column name can be specified with an UPDATING conditionalpredicate to determine if the named column is being updated. For example, assume atrigger is defined as the following:CREATE OR REPLACE TRIGGER ...... UPDATE OF salary ON employees ...BEGIN... IF UPDATING ('salary') THEN ... END IF;...The code in the THEN clause runs only if the triggering UPDATE statement updates thesalary column. This way, the trigger can minimize its overhead when the column ofinterest is not being changed.9.1.7 Enabled and Disabled Trigger ModesA trigger can be in enabled or disabled modes. You would disable a trigger if you didnot want the trigger to execute, perhaps during maintenance activities on the database.■■Enabled. An enabled trigger executes its trigger body if a triggering statement isentered and the trigger restriction (if any) evaluates to TRUE.Disabled. A disabled trigger does not execute its trigger body, even if a triggeringstatement is entered and the trigger restriction (if any) evaluates to TRUE.9.1.8 Error Conditions and Exceptions in the Trigger BodyIf a predefined or user-defined error condition or exception is raised during theexecution of a trigger body, then all effects of the trigger body, as well as the triggeringstatement, are rolled back unless the error is trapped by an exception handler.Therefore, a trigger body can prevent the execution of the triggering statement by9-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
Designing Triggersraising an exception. User-defined exceptions are commonly used in triggers thatenforce complex security authorizations or integrity constraints.9.2 Designing TriggersThis topic discusses the design of triggers. It includes the following topics:■Guidelines For Triggers9.2.1 Guidelines For Triggers■■Restrictions on Creating TriggersPrivileges Needed to Work with TriggersUse the following guidelines when designing your triggers:■■Use triggers to guarantee that when a specific operation is performed, relatedactions are performed.Do not define triggers that duplicate features already built into <strong>Oracle</strong> Database.For example, do not define triggers to reject bad data if you can do the samechecking through declarative integrity constraints.■ Limit the size of triggers. If the logic for your trigger requires much more than 60lines of PL/<strong>SQL</strong> code, it is better to include most of the code in a stored procedureand call the procedure from the trigger. The size of the trigger cannot be more than32K.■■■Use triggers only for centralized, global operations that should be fired for thetriggering statement, regardless of which user or database application issues thestatement.Do not create recursive triggers. For example, creating an AFTER UPDATEstatement trigger on the employees table that itself issues an UPDATE statementon employees, causes the trigger to fire recursively until it has run out ofmemory.Use triggers on DATABASE judiciously. They are executed for every user everytime the event occurs on which the trigger is created.9.2.2 Restrictions on Creating TriggersWhen creating triggers with PL/<strong>SQL</strong> code, there are some restrictions that are notrequired for standard PL/<strong>SQL</strong> blocks. The following topics discuss these restrictions.<strong>SQL</strong> Statements Allowed in Trigger BodiesThe body of a trigger can contain DML <strong>SQL</strong> statements. It can also contain SELECTstatements, but they must be SELECT... INTO... statements or the SELECT statement inthe definition of a cursor.DDL statements are not allowed in the body of a trigger. Also, no transaction controlstatements are allowed in a trigger. ROLLBACK, COMMIT, and SAVEPOINT cannot beused.For system triggers, {CREATE/ALTER/DROP} TABLE statements andALTER...COMPILE are allowed.Triggers: Usage Information 9-5
Designing TriggersNote: A procedure called by a trigger cannot run the previoustransaction control statements, because the procedure runs within thecontext of the trigger body.Statements inside a trigger can reference remote schema objects. However, pay specialattention when calling remote procedures from within a local trigger. If a timestamp orsignature mismatch is found during execution of the trigger, then the remoteprocedure is not run, and the trigger is invalidated.System Trigger RestrictionsOnly committed triggers are fired. For example, if you create a trigger that should befired after all CREATE events, then the trigger itself does not fire after the creation,because the correct information about this trigger was not committed at the time whenthe trigger on CREATE events was fired.For example, if you execute the following <strong>SQL</strong> statement:CREATE OR REPLACE TRIGGER my_triggerAFTER CREATE ON DATABASEBEGINNULL;END;Then, trigger my_trigger is not fired after the creation of my_trigger. <strong>Oracle</strong>Database does not fire a trigger that is not committed.9.2.3 Privileges Needed to Work with TriggersTo create a trigger in your schema, you must have the CREATE TRIGGER systemprivilege, and either:■■Own the table specified in the triggering statement, orHave the ALTER privilege for the table in the triggering statement, or■ Have the ALTER ANY TABLE system privilegeTo create a trigger in another user's schema, or to reference a table in another schemafrom a trigger in your schema, you must have the CREATE ANY TRIGGER systemprivilege. With this privilege, the trigger can be created in any schema and can beassociated with any user's table. In addition, the user creating the trigger must alsohave EXECUTE privilege on the referenced procedures, functions, or packages.To create a trigger on DATABASE, you must have the ADMINISTER DATABASETRIGGER privilege. If this privilege is later revoked, then you can drop the trigger, butnot alter it.The object privileges to the schema objects referenced in the trigger body must begranted to the trigger owner explicitly (not through a role). The statements in thetrigger body operate under the privilege domain of the trigger owner, not the privilegedomain of the user issuing the triggering statement. This is similar to the privilegemodel for stored procedures.9-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
10<strong>SQL</strong>*Plus: Usage Information<strong>SQL</strong>*Plus is an interactive and batch command-line query tool that is installed with<strong>Oracle</strong> Database. This topic includes the following topics:■■Overview of <strong>SQL</strong>*PlusUsing <strong>SQL</strong>*Plus10.1 Overview of <strong>SQL</strong>*Plus10.2 Using <strong>SQL</strong>*Plus<strong>SQL</strong>*Plus is a command-line tool for accessing <strong>Oracle</strong> Database. It enables you to enterand execute <strong>SQL</strong>, PL/<strong>SQL</strong>, and <strong>SQL</strong>*Plus commands to:■■■■Query, insert, and update dataExecute PL/<strong>SQL</strong> proceduresExamine table and object definitionsDevelop and run batch scripts■ Perform database administrationYou can use <strong>SQL</strong>*Plus to generate reports interactively, to generate reports as batchprocesses, and to output the results to text file, to screen, or to HTML file for browsingon the Internet.This topic describes <strong>SQL</strong>*Plus, <strong>Oracle</strong>'s command line tool for executing <strong>SQL</strong> andPL/<strong>SQL</strong>.■■■■■See Also:■■<strong>SQL</strong>*Plus User's Guide and Reference for complete informationabout <strong>SQL</strong>*Plus<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on using <strong>SQL</strong>statementsStarting and Exiting <strong>SQL</strong>*PlusDisplaying Help With <strong>SQL</strong>*PlusEntering and Executing <strong>SQL</strong> Statements and Commands<strong>SQL</strong>*Plus DESCRIBE Command<strong>SQL</strong>*Plus SET Commands<strong>SQL</strong>*Plus: Usage Information 10-1
Using <strong>SQL</strong>*Plus■■■Running Scripts From <strong>SQL</strong>*PlusSpooling From <strong>SQL</strong>*PlusUsing Variables With <strong>SQL</strong>*Plus10.2.1 Starting and Exiting <strong>SQL</strong>*PlusTo start <strong>SQL</strong>*Plus from the operating system command prompt, enter the following:sqlplusWhen prompted, enter the username and password of the user account (schema) thatyou want to access. For example, enter HR for the username and your_hr_passwordwhen prompted.After you have started <strong>SQL</strong>*Plus, the <strong>SQL</strong>> prompt displays for you to type in <strong>SQL</strong>statements, as follows:<strong>SQL</strong>>When you want to quit or exit <strong>SQL</strong>*Plus, type EXIT or QUIT at the <strong>SQL</strong> prompt, asfollows:<strong>SQL</strong>> EXIT10.2.2 Displaying Help With <strong>SQL</strong>*PlusTo display a list of help topics for <strong>SQL</strong>*Plus commands enter HELP INDEX at the <strong>SQL</strong>prompt as follows:<strong>SQL</strong>> HELP INDEXFrom the list of <strong>SQL</strong>*Plus help topics, you can display help on an individual topic byentering HELP with a topic name. For example the following displays help on the<strong>SQL</strong>*Plus COLUMN command, which enables you to format column output:<strong>SQL</strong>> HELP COLUMN10.2.3 Entering and Executing <strong>SQL</strong> Statements and CommandsTo enter and execute <strong>SQL</strong> statements or commands, type in the statement or commandat the <strong>SQL</strong> prompt. At the end of a <strong>SQL</strong> statement, put a semi-colon (;) and then pressthe Enter key to execute the statement. For example:<strong>SQL</strong>> SELECT * FROM employees;If the statement does not fit on one line, type in the first line and press the Enter key.Continue entering lines, terminating the last line with a semi-colon (;). For example:<strong>SQL</strong>> SELECT employee_id, first_name, last_name2 FROM employees3 WHERE employee_id >= 105 AND employee_id
Using <strong>SQL</strong>*Plus110 John Chen6 rows selected.Note that a terminating semi-colon (;) is optional with <strong>SQL</strong> *Plus commands, butrequired with <strong>SQL</strong> statements.10.2.4 <strong>SQL</strong>*Plus DESCRIBE Command<strong>SQL</strong>*Plus provides the DESCRIBE to display a description of a database object. Forexample, the following displays the structure of the employees table. Thisdescription is useful when constructing <strong>SQL</strong> statements that manipulate theemployees table.<strong>SQL</strong>> DESCRIBE employeesNameNull? Type---------------------------------------- -------- ------------EMPLOYEE_ID NOT NULL NUMBER(6)FIRST_NAME VARCHAR2(20)LAST_NAME NOT NULL VARCHAR2(25)EMAIL NOT NULL VARCHAR2(25)PHONE_NUMBER VARCHAR2(20)HIRE_DATE NOT NULL DATEJOB_ID NOT NULL VARCHAR2(10)SALARY NUMBER(8,2)COMMISSION_PCT NUMBER(2,2)MANAGER_ID NUMBER(6)DEPARTMENT_ID NUMBER(4)10.2.5 <strong>SQL</strong>*Plus SET CommandsThe <strong>SQL</strong>*Plus SET commands can be used to specify various <strong>SQL</strong>*Plus settings, suchas the format of the output from <strong>SQL</strong>*Plus statements. For example, the following SETcommands specify the number of lines per page display and the number of charactersper line in the output:<strong>SQL</strong>> SET PAGESIZE 200<strong>SQL</strong>> SET LINESIZE 140To enable output from PL/<strong>SQL</strong> blocks with DBMS_OUTPUTTo view all the settings, enter the following at the <strong>SQL</strong> prompt:<strong>SQL</strong>> SHOW ALLFor information about the <strong>SQL</strong>*Plus SERVEROUTPUT setting to display output from aPL/<strong>SQL</strong> program, see Inputting and Outputting Data with PL/<strong>SQL</strong>.See Also:10.2.6 Running Scripts From <strong>SQL</strong>*Plus■<strong>SQL</strong>*Plus User's Guide and Reference for information setting up the<strong>SQL</strong>*Plus environment with a login fileYou can use a text editor to create <strong>SQL</strong>*Plus script files containing <strong>SQL</strong>*Plus, <strong>SQL</strong>, andPL/<strong>SQL</strong> statements. For consistency, use the .sql extension for the script file name.<strong>SQL</strong>*Plus: Usage Information 10-3
Using <strong>SQL</strong>*PlusA <strong>SQL</strong> script file is executed with a START or @ command. For example, on a Windowsenvironment you could execute a <strong>SQL</strong> script as follows:<strong>SQL</strong>> @c:\my_scripts\my_sql_script.sqlA <strong>SQL</strong> script file could be executed on a Linux environment as follows:<strong>SQL</strong>> START /home/cjones/my_scripts/my_sql_script.sqlYou can use SET ECHO ON to cause a script to echo each statement that is executed. Youcan use SET TERMOUT OFF to prevent the script output from displaying on the screen.When running a script, you should include the full path name unless the script islocated in the directory where <strong>SQL</strong>*Plus was launched.10.2.7 Spooling From <strong>SQL</strong>*PlusThe SPOOL command can be used to direct the output from <strong>SQL</strong>*Plus to a disk file,which enables you to save the output for future review.To start spooling the output to an operating system file, you can enter:<strong>SQL</strong>> SPOOL my_log_file.logIf you want to append the output to an existing file:<strong>SQL</strong>> SPOOL my_log_file.log APPENDTo stop spooling and close a file, enter the following:<strong>SQL</strong>> SPOOL OFF10.2.8 Using Variables With <strong>SQL</strong>*PlusYou can write queries that use variables to make your SELECT statements moreflexible. You can define the variable prior to running a <strong>SQL</strong> statement or you canprompt for a variable value at the time that the <strong>SQL</strong> statement is run.When using a variable in a <strong>SQL</strong> statement, the variable name must be begin with anampersand (&).This topic includes the following topics:■ Prompting for a Variable■ Defining a Variable Value for a QueryFor information on using bind variables in PL/<strong>SQL</strong> code, see Using Bind Variables.10.2.8.1 Prompting for a VariableIn Example 10–1, including the variable &emp_id causes the <strong>SQL</strong> statement to promptfor a value when the statement is executed. You can then enter the employee_id thatyou want to display, such as employee Id 125.Example 10–1 Defining a Variable-- prompt for employee_id in a query, you need to enter a valid Id such as 125SELECT employee_id, last_name, job_id FROM employees WHERE employee_id = &emp_id;When you run the previous SELECT statement, the output is similar to:Enter value for emp_id: 125...EMPLOYEE_ID LAST_NAME JOB_ID10-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
Using <strong>SQL</strong>*Plus----------- ------------------------- ----------125 Nayer ST_CLERK10.2.8.2 Defining a Variable Value for a QueryIn Example 10–2, the variable &jobid is defined prior to running the <strong>SQL</strong> statementand the defined value is substituted for the variable when the statement is executed.Example 10–2 Prompting for a Variable-- define a variable value for a query as followsDEFINE jobid = "ST_CLERK"-- run a query using the defined value for jobid (ST_CLERK)SELECT employee_id, last_name FROM employees WHERE job_id = '&jobid';<strong>SQL</strong>*Plus: Usage Information 10-5
Using <strong>SQL</strong>*Plus10-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
11Working in a Global EnvironmentThis topic describes how to use <strong>Oracle</strong>'s database access products with Unicode andprovides useful information for <strong>SQL</strong> and PL/<strong>SQL</strong> programming in a globalizationsupport environment. It includes the following topics:■■■■Overview of Globalization SupportSetting up the Globalization Support Environment<strong>SQL</strong> and PL/<strong>SQL</strong> Programming with UnicodeLocale-Dependent <strong>SQL</strong> Functions with Optional NLS ParametersSee Also:■■■11.1 Overview of Globalization Support<strong>Oracle</strong> Database Globalization Support Guide for a completediscussion of globalization support with <strong>Oracle</strong> Database,including setting up the globalization support environment.<strong>Oracle</strong> Database Reference for information on initializationparameters used for globalization support<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on date and timeformats.<strong>Oracle</strong>'s globalization support enables you to store, process, and retrieve data in nativelanguages. It ensures that database utilities, error messages, sort order, and date, time,monetary, numeric, and calendar conventions automatically adapt to any nativelanguage and locale.<strong>Oracle</strong>'s globalization support includes National Language Support (NLS) features.National Language Support is the ability to choose a national language and store datain a specific character set. Globalization support enables you to develop multilingualapplications and software products that can be accessed and run from anywhere in theworld simultaneously. An application can render content of the user interface andprocess data in the native users' languages and locale preferences.Note: The National Language Support Parameters report lists thevalues of parameters for globalization support. For information aboutthis and other <strong>SQL</strong> <strong>Developer</strong> reports, see Reports.<strong>Oracle</strong>'s standard features include:■Language SupportWorking in a Global Environment 11-1
Overview of Globalization Support■■■■■■■■The database enables you to store, process, and retrieve data in native languages.Through the use of Unicode databases and data types, the <strong>Oracle</strong> databasesupports most contemporary languages.See "Setting NLS Parameters".Territory SupportThe database supports cultural conventions that are specific to geographicallocations. The default local time format, date format, and numeric and monetaryconventions depend on the local territory setting.See "Language and Territory Parameters".Date and Time FormatsDifferent conventions for displaying the hour, day, month, and year can behandled in local formats. Time zones and daylight saving support are alsoavailable.See "Date and Time Parameters".Monetary and Numeric FormatsCurrency, credit, debit symbols, and numbers can be represented in local formats.See "Monetary Parameters" and "Numeric and List Parameters" on page 11-11.Calendars Feature<strong>Oracle</strong> supports seven different calendar systems in use around the world:Gregorian, Japanese Imperial, ROC Official (Republic of China), Thai Buddha,Persian, English Hijrah, and Arabic Hijrah.See "Calendar Definitions".Linguistic Sorting<strong>Oracle</strong> provides linguistic definitions for culturally accurate sorting and caseconversion.See "Linguistic Sorting and Searching".Character Set Support<strong>Oracle</strong> supports a large number of single-byte, multibyte, and fixed-widthencoding schemes that are based on national, international, and vendor-specificstandards.Character Semantics<strong>Oracle</strong> provides character semantics. It is useful for defining the storagerequirements for multibyte strings of varying widths in terms of characters insteadof bytes.See "Length Semantics".Unicode SupportUnicode is a universal encoded character set that enables you to store informationin any language, using a single character set. <strong>Oracle</strong> Database provides productssuch as <strong>SQL</strong> and PL/<strong>SQL</strong> for inserting and retrieving Unicode data.See "<strong>SQL</strong> and PL/<strong>SQL</strong> Programming with Unicode".11-2 <strong>SQL</strong> <strong>Developer</strong> Online Help
Setting up the Globalization Support Environment11.2 Setting up the Globalization Support EnvironmentThis topic discusses how to set up a globalization support environment. It includes thefollowing topics:■■■■■■■■■Setting NLS ParametersChoosing a Locale with the NLS_LANG Environment VariableLanguage and Territory ParametersDate and Time ParametersCalendar DefinitionsNumeric and List ParametersMonetary ParametersLinguistic Sorting and SearchingLength Semantics11.2.1 Setting NLS ParametersNLS (National Language Support) parameters determine the locale-specific behavioron both the client and the server. NLS parameters can be specified several ways. In thisguide, altering parameters for the user session and overriding the parameters in <strong>SQL</strong>functions are discussed. Both of these techniques accomplished through the use of <strong>SQL</strong>statements.You can alter the NLS parameters settings by:■ Setting NLS parameters in an ALTER SESSION statement to override the defaultvalues that are set for the session in the initialization parameter file, or that are setby the client with environment variables. For example:ALTER SESSION SET NLS_SORT = french;Note that the changes that you make with ALTER SESSION apply only to thecurrent user session and are not present the next time you log in.See Also:■■■"Setting NLS Parameters" in <strong>Oracle</strong> Database GlobalizationSupport Guide for details on setting the NLS parameters<strong>Oracle</strong> Database <strong>SQL</strong> Reference for more information about theALTER SESSION statement<strong>Oracle</strong> Database Administrator's Guide for information on theinitialization parameter file■Using NLS parameters within a <strong>SQL</strong> function to override the default values thatare set for the session in the initialization parameter file, set for the client withenvironment variables, or set for the session by the ALTER SESSION statement.For example:TO_CHAR(hiredate,'DD/MON/YYYY','nls_date_language = FRENCH')Working in a Global Environment 11-3
Setting up the Globalization Support EnvironmentAdditional methods for setting the NLS parameters require that you shutdown andrestart the database. These techniques include the following:■See Also:■■"Setting NLS Parameters" in <strong>Oracle</strong> Database GlobalizationSupport Guide for details on setting the NLS parameters<strong>Oracle</strong> Database <strong>SQL</strong> Reference for more information about <strong>SQL</strong>functions, including the TO_CHAR functionIncluding parameters in the <strong>Oracle</strong> Database initialization parameter file to specifythe default session NLS environment on the server side. For example:NLS_TERRITORY = "CZECH REPUBLIC"See Also: <strong>Oracle</strong> Database installation guide for Linux orWindows for information on setting globalization parameters andenvironmental variables.■Using NLS environment variables on the client, which may beplatform-dependent, to specify locale-dependent behavior for the client and alsoto override the default values set for the session in the initialization parameter file.For example, on a Linux system:% setenv NLS_SORT FRENCHSee Also: <strong>Oracle</strong> Database installation guide for Linux orWindows for information on setting globalization parameters andenvironmental variables.11.2.2 Choosing a Locale with the NLS_LANG Environment VariableA locale is a linguistic and cultural environment in which a system or program isrunning. Setting the NLS_LANG environment parameter is the simplest way to specifylocale behavior for <strong>Oracle</strong> software. It sets the language and territory used by the clientapplication and the database server. It also sets the client's character set, which is thecharacter set for data entered or displayed by a client program.The NLS_LANG parameter sets the language and territory environment used by boththe server session (for example, <strong>SQL</strong> command execution) and the client application(for example, display formatting in <strong>Oracle</strong> tools).You might want to modify the NLS environment dynamically during the session. Todo so, you can use the ALTER SESSION statement to change NLS_LANGUAGE, NLS_TERRITORY, and other NLS parameters.Note: You cannot modify the setting for the client character setwith the ALTER SESSION statement.The ALTER SESSION statement modifies only the session environment. The localclient NLS environment is not modified, unless the client explicitly retrieves the newsettings and modifies its local environment.11-4 <strong>SQL</strong> <strong>Developer</strong> Online Help
Setting up the Globalization Support EnvironmentSee Also:■■<strong>Oracle</strong> Database installation guides for information on theNLS_LANG environmental variable<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on the ALTERSESSION statement.11.2.3 Language and Territory ParametersSetting different NLS parameters for local territories allows the database session to usedifferent cultural settings. For example, you can set the euro (EUR) as the primarycurrency and the Japanese yen (JPY) as the secondary currency for a given databasesession even when the territory is defined as AMERICA.This topic contains information about the following parameters:■ NLS_LANGUAGE■ NLS_TERRITORY11.2.3.1 NLS_LANGUAGEThe NLS_LANGUAGE parameter can be set to any valid language name and the defaultis derived from the NLS_LANG setting. NLS_LANGUAGE specifies the defaultconventions for the following session characteristics:■■■Language for server messagesLanguage for day and month names and their abbreviations (specified in the <strong>SQL</strong>functions TO_CHAR and TO_DATE)Symbols for equivalents of AM, PM, AD, and BC.■ Default sorting sequence for character data when ORDER BY is specified. (GROUPBY uses a binary sort unless ORDER BY is specified.)Example 11–1 and Example 11–2 show the results from setting NLS_LANGUAGE todifferent values. In Example 11–1, the ALTER SESSION statement is issued to set NLS_LANGUAGE to Italian.Example 11–1NLS_LANGUAGE=ITALIANALTER SESSION SET NLS_LANGUAGE=Italian;-- enter a SELECT to check the format of the output after the ALTER SESSIONSELECT last_name, hire_date, ROUND(salary/8,2) salary FROM employeesWHERE employee_id IN (111, 112, 113);You should see results similar to the following:LAST_NAME HIRE_DATE SALARY------------------------- --------- ----------Sciarra 30-SET-97 962.5Urman 07-MAR-98 975Popp 07-DIC-99 862.5Note that the month name abbreviations are in Italian.In Example 11–2, the ALTER SESSION statement is issued to change the language toGerman.Working in a Global Environment 11-5
Setting up the Globalization Support EnvironmentExample 11–2NLS_LANGUAGE=GERMANALTER SESSION SET NLS_LANGUAGE=German;SELECT last_name, hire_date, ROUND(salary/8,2) salary FROM employeesWHERE employee_id IN (111, 112, 113);You should see results similar to the following:LAST_NAME HIRE_DATE SALARY------------------------- --------- ----------Sciarra 30-SEP-97 962.5Urman 07-MRZ-98 975Popp 07-DEZ-99 862.5Note that the language of the month abbreviations has changed to German.11.2.3.2 NLS_TERRITORYThe NLS_TERRITORY parameter can be set to any valid territory name and the defaultis derived from the NLS_LANG setting. NLS_TERRITORY specifies the conventions forthe following default date and numeric formatting characteristics:■■■■See Also:■■Date format<strong>Oracle</strong> Database installation guides for information on thesupported languages in the <strong>Oracle</strong> Database.<strong>Oracle</strong> Database Globalization Support Guide for more informationon supported languages.Decimal character and group separatorLocal currency symbolISO currency symbol■ Dual currency symbolThe territory can be modified dynamically during the session by specifying the newNLS_TERRITORY value in an ALTER SESSION statement. For example, to change theterritory to France during a session, issue the following ALTER SESSION statement:ALTER SESSION SET NLS_TERRITORY = France;Modifying NLS_TERRITORY resets all derived NLS session parameters to defaultvalues for the new territory. Example 11–3 and Example 11–4 show behavior thatresults from different settings of NLS_TERRITORY and NLS_LANGUAGE.Example 11–3NLS_LANGUAGE=AMERICAN, NLS_TERRITORY=AMERICA-- set NLS_LANAGUAGE and NLS_TERRITORYALTER SESSION SET NLS_LANGUAGE = American NLS_TERRITORY = America;-- enter the following SELECT to view the format of the output for currencySELECT TO_CHAR(salary,'L99G999D99') salary FROM employeesWHERE employee_id IN (100, 101, 102);When NLS_TERRITORY is set to AMERICA and NLS_LANGUAGE is set to AMERICAN,results similar to the following should appear:SALARY11-6 <strong>SQL</strong> <strong>Developer</strong> Online Help
Setting up the Globalization Support Environment--------------------$24,000.00$17,000.00$17,000.00In Example 11–4 an ALTER SESSION statement is issued to change the territory toGermany.Example 11–4NLS_LANGUAGE=AMERICAN, NLS_TERRITORY=GERMANY-- set NLS_TERRITORY to Germany for this sessionALTER SESSION SET NLS_TERRITORY = Germany;SELECT TO_CHAR(salary,'L99G999D99') salary FROM employeesWHERE employee_id IN (100, 101, 102);You should see results similar to the following:SALARY-------------------€24.000,00€17.000,00€17.000,00Note that the currency symbol has changed from $ to €. The numbers have notchanged because the underlying data is the same.See Also:■■<strong>Oracle</strong> Database installation guides for information on thesupported territories in the <strong>Oracle</strong> Database.<strong>Oracle</strong> Database Globalization Support Guide for more informationon supported territories11.2.4 Date and Time Parameters<strong>Oracle</strong> enables you to control the display of date and time, allowing differentconventions for displaying the hour, day, month, and year to be handled in localformats. For example, in the United Kingdom, the date is displayed using theDD/MM/YYYY format, while China commonly uses the YYYY-MM-DD format.This topic contains the following topics:■ Date Formats■ Time Formats11.2.4.1 Date FormatsDifferent date formats are shown in Table 11–1.Table 11–1Examples of Short Date FormatsCountry Description ExampleEstonia dd.mm.yyyy 28.02.2005Germany dd.mm.rr 28.02.05Working in a Global Environment 11-7
Setting up the Globalization Support EnvironmentTable 11–1 (Cont.) Examples of Short Date FormatsCountry Description ExampleChina yyyy-mm-dd 2005-02-28UK dd/mm/yyyy 28/02/2005US mm/dd/yyyy 02/28/2005This topic includes the following parameters:■■NLS_DATE_FORMATNLS_DATE_LANGUAGE11.2.4.1.1 NLS_DATE_FORMAT The NLS_DATE_FORMAT parameter defines the defaultdate format to use with the TO_CHAR and TO_DATE functions. The NLS_TERRITORYparameter determines the default value of NLS_DATE_FORMAT. The value of NLS_DATE_FORMAT can be any valid date format mask. For example:NLS_DATE_FORMAT = "MM/DD/YYYY"The <strong>Oracle</strong> default date format may not always corresponds to the cultural specificconvention used in a given territory. You can utilize the short date and long dateformat in <strong>SQL</strong>, using the 'DS' and 'DL' format masks respectively, to obtain dates ina more localized formats. The examples in this topic show the differences betweensome of the date formats.Example 11–5Using the Default, Short, and Long Date Formats-- Use an ALTER SESSION statement to change the territory to America,-- and the language to AmericanALTER SESSION SET NLS_TERRITORY = America NLS_LANGUAGE = American;-- After the session is altered, select the dates with the format masksSELECT hire_date, TO_CHAR(hire_date,'DS') "Short",TO_CHAR(hire_date,'DL') "Long" FROM employeesWHERE employee_id IN (111, 112, 113);The results of the query in Example 11–5 are similar to the following:HIRE_DATE Short Long--------- ---------- -----------------------------30-SEP-97 9/30/1997 Tuesday, September 30, 199707-MAR-98 3/7/1998 Saturday, March 07, 199807-DEC-99 12/7/1999 Tuesday, December 07, 1999To add string literals to the date format, enclose the string literal with double quotes.Note that when double quotes are included in the date format, the entire value mustbe enclosed by single quotes. For example:NLS_DATE_FORMAT = '"Date: "MM/DD/YYYY'11.2.4.1.2 NLS_DATE_LANGUAGE The NLS_DATE_LANGUAGE parameter specifies thelanguage for the day and month names produced by the TO_CHAR and TO_DATEfunctions. NLS_DATE_LANGUAGE overrides the language that is specified implicitly byNLS_LANGUAGE. NLS_DATE_LANGUAGE has the same syntax as the NLS_LANGUAGEparameter, and all supported languages are valid values.NLS_DATE_LANGUAGE also determines the language used for:■Month and day abbreviations returned by the TO_CHAR and TO_DATE functions11-8 <strong>SQL</strong> <strong>Developer</strong> Online Help
Setting up the Globalization Support Environment■ Month and day abbreviations used by the default date format (NLS_DATE_FORMAT)Example 11–6 shows how to use NLS_DATE_LANGUAGE to set the date language toFrench.Example 11–6 NLS_DATE_LANGUAGE=FRENCH, Month and Day Names-- set NLS_DATE_LANAGUAGE for this user sessionALTER SESSION SET NLS_DATE_LANGUAGE = FRENCH;-- display the current system dateSELECT TO_CHAR(SYSDATE, 'Day:Dd Month yyyy') FROM DUAL;You should see output similar to the following, depending on the current system date:TO_CHAR(SYSDATE,'DAY:DDMON--------------------------Jeudi :06 Octobre 2005The default date format uses the month abbreviations determined by NLS_DATE_LANGUAGE. For example, if the default date format is DD-MON-YYYY and NLS_DATE_LANGUAGE = FRENCH, then insert a date as follows:INSERT INTO table_name VALUES ('12-Févr.-1997');See Also: <strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on dateformat models11.2.4.2 Time FormatsDifferent time formats are shown in Table 11–2.Table 11–2Examples of Time FormatsCountry Description ExampleEstonia hh24:mi:ss 13:50:23Germany hh24:mi:ss 13:50:23China hh24:mi:ss 13:50:23UK hh24:mi:ss 13:50:23US hh:mi:ssxff am 1:50:23.555 PMThis topic contains information about the following parameters:■■NLS_TIMESTAMP_FORMATNLS_TIMESTAMP_TZ_FORMAT11.2.4.2.1 NLS_TIMESTAMP_FORMAT NLS_TIMESTAMP_FORMAT defines the defaultdate format for the TIMESTAMP and TIMESTAMP WITH LOCAL TIME ZONE datatypes. The NLS_TERRITORY parameter determines the default value of NLS_TIMESTAMP_FORMAT. The value of NLS_TIMESTAMP_FORMAT can be any validdatetime format mask.The following example shows a value for NLS_TIMESTAMP_FORMAT:NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH:MI:SS.FF'Working in a Global Environment 11-9
Setting up the Globalization Support Environment11.2.4.2.2 NLS_TIMESTAMP_TZ_FORMAT NLS_TIMESTAMP_TZ_FORMAT defines thedefault date format for the TIMESTAMP and TIMESTAMP WITH LOCAL TIME ZONEdata types. It is used with the TO_CHAR and TO_TIMESTAMP_TZ functions. The NLS_TERRITORY parameter determines the default value of NLS_TIMESTAMP_TZ_FORMAT. The value of NLS_TIMESTAMP_TZ_FORMAT can be any valid datetimeformat mask.The format value must be surrounded by quotation marks. For example:NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH:MI:SS.FF TZH:TZM'In Example 11–7 the TO_TIMESTAMP_TZ function uses the format value that wasspecified for NLS_TIMESTAMP_TZ_FORMAT.Example 11–7Setting NLS_TIMESTAMP_TZ_FORMAT-- display August 20, 2005 using the format of NLS_TIMPSTAMP_TZ_FORMATSELECT TO_TIMESTAMP_TZ('2005-08-20, 05:00:00.55 America/Los_Angeles','yyyy-mm-dd hh:mi:ss.ff TZR') "TIMESTAMP_TZ Format" FROM DUAL;You should see output similar to the following:TIMESTAMP_TZ Format--------------------------------------------------------20-AUG-05 05.00.00.550000000 AM AMERICA/LOS_ANGELES11.2.5 Calendar DefinitionsThis topic includes the following topics:■■Calendar FormatsNLS_CALENDAR11.2.5.1 Calendar FormatsThe following calendar information is stored for each territory:■ First Day of the Week on page 11-10■ First Calendar Week of the Year on page 11-10■ Number of Days and Months in a Year on page 11-11■ First Year of Era on page 11-1111.2.5.1.1 First Day of the Week Some cultures consider Sunday to be the first day of theweek. Others consider Monday to be the first day of the week. A German calendarstarts with Monday.The first day of the week is determined by the NLS_TERRITORY parameter.11.2.5.1.2 First Calendar Week of the Year Some countries use week numbers forscheduling, planning, and bookkeeping. <strong>Oracle</strong> supports this convention. In the ISOstandard, the week number can be different from the week number of the calendaryear. For example, 1st Jan 1988 is in ISO week number 53 of 1987. An ISO weekalways starts on a Monday and ends on a Sunday.To support the ISO standard, <strong>Oracle</strong> provides the IW date format element. It returnsthe ISO week number.The first calendar week of the year is determined by the NLS_TERRITORY parameter.11-10 <strong>SQL</strong> <strong>Developer</strong> Online Help
Setting up the Globalization Support Environment11.2.5.1.3 Number of Days and Months in a Year <strong>Oracle</strong> supports six calendar systems inaddition to Gregorian, the default:■■Japanese Imperial—uses the same number of months and days as Gregorian, butthe year starts with the beginning of each Imperial EraROC Official—uses the same number of months and days as Gregorian, but theyear starts with the founding of the Republic of China■ Persian—has 31 days for each of the first six months. The next five months have 30days each. The last month has either 29 days or 30 days (leap year).■■■Thai Buddha—uses a Buddhist calendarArabic Hijrah—has 12 months with 354 or 355 daysEnglish Hijrah—has 12 months with 354 or 355 daysThe calendar system is specified by the NLS_CALENDAR parameter.11.2.5.1.4 First Year of Era The Islamic calendar starts from the year of the Hegira.The Japanese Imperial calendar starts from the beginning of an Emperor's reign. Forexample, 1998 is the tenth year of the Heisei era.11.2.5.2 NLS_CALENDARMany different calendar systems are in use throughout the world. NLS_CALENDARspecifies which calendar system <strong>Oracle</strong> uses. The default value is Gregorian. Thevalue can be any valid calendar format name.NLS_CALENDAR can have one of the following values:■■■■■■■Arabic HijrahEnglish HijrahGregorianJapanese ImperialPersianROC Official (Republic of China)Thai BuddhaIn Example 11–8 NLS_CALENDAR is set to English Hijrah.Example 11–8NLS_CALENDAR='English Hijrah'-- set NLS_CALENDAR with ALTER SESSIONALTER SESSION SET NLS_CALENDAR='English Hijrah';-- display the current system dateSELECT SYSDATE FROM DUAL;You should see output similar to the following, depending on the current system date:SYSDATE--------------------24 Ramadan 142211.2.6 Numeric and List ParametersThis topic includes the following topics:Working in a Global Environment 11-11
Setting up the Globalization Support Environment■■Numeric FormatsNLS_NUMERIC_CHARACTERS11.2.6.1 Numeric FormatsThe database must know the number-formatting convention used in each session tointerpret numeric strings correctly. For example, the database needs to know whethernumbers are entered with a period or a comma as the decimal character (234.00 or234,00). Similarly, applications must be able to display numeric information in theformat expected at the client site.Examples of numeric formats are shown in Table 11–3.Table 11–3CountryExamples of Numeric FormatsNumeric FormatsEstonia 1 234 567,89Germany 1.234.567,89China 1,234,567.89UK 1,234,567.89US 1,234,567.89Numeric formats are derived from the setting of the NLS_TERRITORY parameter, butthey can be overridden by the NLS_NUMERIC_CHARACTERS parameter.11.2.6.2 NLS_NUMERIC_CHARACTERSThe NLS_NUMERIC_CHARACTERS parameter specifies the decimal character andgroup separator. The group separator is the character that separates integer groups toshow thousands and millions, for example. The group separator is the characterreturned by the G number format mask. The decimal character separates the integerand decimal parts of a number. Setting NLS_NUMERIC_CHARACTERS overrides thedefault values derived from the setting of NLS_TERRITORY. The value can be any twovalid numeric characters for the decimal character and group separator.Any character can be the decimal character or group separator. The two charactersspecified must be single-byte, and the characters must be different from each other.The characters cannot be any numeric character or any of the following characters:plus (+), hyphen (-), less than sign (). Either character can be aspace.To set the decimal character to a comma and the grouping separator to a period, defineNLS_NUMERIC_CHARACTERS as follows:ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ",.";<strong>SQL</strong> statements can include numbers represented as numeric or text literals. Numericliterals are not enclosed in quotes. They are part of the <strong>SQL</strong> language syntax andalways use a dot as the decimal character and never contain a group separator. Textliterals are enclosed in single quotes. They are implicitly or explicitly converted tonumbers, if required, according to the current NLS settings.The following SELECT statement formats the number 4000 with the decimal characterand group separator specified in the ALTER SESSION statement:ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ",.";SELECT TO_CHAR(4000, '9G999D99') FROM DUAL;11-12 <strong>SQL</strong> <strong>Developer</strong> Online Help
Setting up the Globalization Support EnvironmentYou should see output similar to the following:TO_CHAR(4---------4.000,0011.2.7 Monetary Parameters<strong>Oracle</strong> enables you to define radix symbols and thousands separators by locales. Forexample, in the US, the decimal point is a dot (.), while it is a comma (,) in France.Because the amount $1,234 has different meanings in different countries, it isimportant to display the amount appropriately by locale.This topic includes the following topics:■ Currency Formats■ NLS_CURRENCY■ NLS_ISO_CURRENCY■ NLS_DUAL_CURRENCY11.2.7.1 Currency FormatsDifferent currency formats are used throughout the world. Some typical ones areshown in Table 11–4.Table 11–4CountryEstoniaCurrency Format ExamplesExample1 234,56 krGermany 1.234,56€China ¥1,234.56UK £1,234.56US $1,234.5611.2.7.2 NLS_CURRENCYNLS_CURRENCY specifies the character string returned by the L number format mask,the local currency symbol. Setting NLS_CURRENCY overrides the default settingdefined implicitly by NLS_TERRITORY. The value can be any valid currency symbolstring.Example 11–9 Displaying the Local Currency Symbol-- select and format the salary column from employeesSELECT TO_CHAR(salary, 'L099G999D99') "salary" FROM employeesWHERE salary > 11000;You should see output similar to the following:SALARY---------------------$024,000.00$017,000.00$017,000.00Working in a Global Environment 11-13
Setting up the Globalization Support Environment$012,000.00$014,000.00$013,500.00$012,000.00$011,500.00$013,000.00$012,000.0011.2.7.3 NLS_ISO_CURRENCYNLS_ISO_CURRENCY specifies the character string returned by the C number formatmask, the ISO currency symbol. Setting NLS_ISO_CURRENCY overrides the defaultvalue defined implicitly by NLS_TERRITORY. The value can be any valid string.Local currency symbols can be ambiguous. For example, a dollar sign ($) can refer toUS dollars or Australian dollars. ISO specifications define unique currency symbols forspecific territories or countries. For example, the ISO currency symbol for the USdollar is USD. The ISO currency symbol for the Australian dollar is AUD.NLS_ISO_CURRENCY has the same syntax as the NLS_TERRITORY parameter, and allsupported territories are valid values.To specify the ISO currency symbol for France, set NLS_ISO_CURRENCY as shown inExample 11–10.Example 11–10Setting NLS_ISO_CURRENCY-- set NLS_ISO_CURRENCY to FranceALTER SESSION SET NLS_ISO_CURRENCY = FRANCE;-- display the salary of selected employeesSELECT TO_CHAR(salary, 'C099G999D99') "Salary" FROM employeesWHERE department_id = 60;You should see output similar to the following:Salary--------------------EUR009,000.00EUR006,000.00EUR004,800.00EUR004,800.00EUR004,200.0011.2.7.4 NLS_DUAL_CURRENCYUse NLS_DUAL_CURRENCY to override the default dual currency symbol definedimplicitly by NLS_TERRITORY. The value can be any valid symbol.NLS_DUAL_CURRENCY was introduced to support the euro currency symbol duringthe euro transition period.11.2.8 Linguistic Sorting and SearchingDifferent languages have their own sorting rules. Some languages are collatedaccording to the letter sequence in the alphabet, some according to the number ofstroke counts in the letter, and some are ordered by the pronunciation of the words.11-14 <strong>SQL</strong> <strong>Developer</strong> Online Help
Setting up the Globalization Support EnvironmentTreatment of letter accents also differs among languages. For example, in Danish, Æ issorted after Z, while Y and Ü are considered to be variants of the same letter.You can define how to sort data by using linguistic sort parameters. The basiclinguistic definition treats strings as sequences of independent characters.This topic includes the following topics:■ NLS_SORT■ NLS_COMP11.2.8.1 NLS_SORTThe NLS_SORT parameter specifies the collating sequence for ORDER BY queries. Itoverrides the default NLS_SORT value that is derived from NLS_LANGUAGE. The valueof NLS_SORT can be BINARY or any valid linguistic sort name:NLS_SORT = BINARY | sort_nameIf the value is BINARY, then the collating sequence is based on the numeric code of thecharacters in the underlying encoding scheme. Depending on the data type, this willeither be in the binary sequence order of the database character set or the nationalcharacter set. If the value is a named linguistic sort, sorting is based on the order of thedefined sort. Most, but not all, languages supported by the NLS_LANGUAGE parameteralso support a linguistic sort with the same name.You can set the NLS_SORT parameter to change the linguistic sorting behavior of theyour <strong>SQL</strong> session. Spain traditionally treats ch, ll as well as ñ as letters of their own,ordered after c, l and n respectively. Example 11–11 and Example 11–12 illustrate theeffect of using a Spanish sort against the employee names Chen and Chung. InExample 11–11, the NLS_SORT parameter is set to BINARY.In Example 11–11, LIKE is used to specify the records to return with the query. Forinformation on LIKE, see Restricting Data Using the WHERE Clause.Example 11–11Setting NLS_SORT to BINARY-- set the NLS_SORT for this user sessionALTER SESSION SET NLS_SORT=binary;-- select the last name of those employees whose last name begin with CSELECT last_name FROM employeesWHERE last_name LIKE 'C%' ORDER BY last_name;The output of Example 11–11 appears:LAST_NAME--------------CabrioCambraultCambraultChenChungColmenaresIn Example 11–12, the NLS_SORT parameter is set to SPANISH_M.Example 11–12 Setting NLS_SORT to Spanish-- set the NLS_SORT for this user sessionALTER SESSION SET NLS_SORT=spanish_m;Working in a Global Environment 11-15
Setting up the Globalization Support Environment-- select the last name of those employees whose last name begin with CSELECT last_name FROM employeesWHERE last_name LIKE 'C%' ORDER BY last_name;The output of Example 11–12 appears:LAST_NAME--------------CabrioCambraultCambraultColmenaresChenChungNote that the order of last names in the output from the SELECT statement inExample 11–11 and Example 11–12 is different.See Also:■<strong>Oracle</strong> Database Globalization Support Guide for more informationon supported linguistic sorts.11.2.8.2 NLS_COMPWhen using comparison operators, characters are compared according to their binarycodes in the designated encoding scheme. A character is greater than another if it has ahigher binary code. Because the binary sequence of characters may not match thelinguistic sequence for a particular language, such comparisons might not belinguistically correct.The value of the NLS_COMP parameter affects the comparison behavior of <strong>SQL</strong>operations. The value can be BINARY (default) or LINGUISTIC. You can use NLS_COMP to avoid the cumbersome process of using the NLSSORT function in <strong>SQL</strong>statements when you want to perform a linguistic comparison instead of a binarycomparison. When NLS_COMP is set to LINGUISTIC, <strong>SQL</strong> operations perform alinguistic comparison based on the value of NLS_SORT.Example 11–13 and Example 11–14 illustrate the effect of performing a binarycomparison follow by a Spanish linguistic sensitive comparison against the employeenames. In Example 11–13 the NLS_COMP parameter is set to BINARY while NLS_SORTis set to Spanish.Example 11–13 Setting NLS_COMP to BINARY-- set NLS_SORT and NLS_COMP for this user sessionALTER SESSION SET NLS_SORT=spanish_m NLS_COMP=binary;-- select the last name of those employees whose last name begin with CSELECT last_name FROM employeesWHERE last_name LIKE 'C%';The output of Example 11–13 appears:LAST_NAME--------------CabrioCambraultCambrault11-16 <strong>SQL</strong> <strong>Developer</strong> Online Help
Setting up the Globalization Support EnvironmentChenChungColmenaresIn Example 11–14 the NLS_COMP parameter is set to LINGUISTIC while NLS_SORT isset to Spanish.Example 11–14 Setting NLS_COMP to BINARY-- set NLS_SORT and NLS_COMP for this user sessionALTER SESSION SET NLS_SORT=spanish_m NLS_COMP=linguistic;-- select the last name of those employees whose last name begin with CSELECT last_name FROM employeesWHERE last_name LIKE 'C%';The output of Example 11–14 appears:LAST_NAME--------------CabrioCambraultCambraultColmenaresNote the difference in the output of Example 11–13 and Example 11–14. In Spanish chis treated as a separate character following c so ch is excluded when a Spanishlinguistic sensitive comparison is performed in Example 11–14.11.2.8.3 Case and Accent Insensitive SearchingOperations inside a database are sensitive to the case and the accents of the characters.Sometimes you might need to perform case-insensitive or accent-insensitivecomparisons. Use the NLS_SORT session parameter to specify a case-insensitive oraccent insensitive sort.To specify a case-insensitive or accent-insensitive sort:■Append _CI to an <strong>Oracle</strong> sort name for a case-insensitive sort. For example:BINARY_CI: accent sensitive and case insensitive binary sortGENERIC_M_CI: accent sensitive and case insensitive GENERIC_M sort■Append _AI to an <strong>Oracle</strong> sort name for an accent-insensitive and case-insensitivesort. For example:BINARY_AI: accent insensitive and case insensitive binary sortFRENCH_M_AI: accent insensitive and case insensitive FRENCH_M sort11.2.9 Length SemanticsIn single-byte character sets, the number of bytes and the number of characters in astring are the same. In multibyte character sets, a character or code point consists ofone or more bytes. Calculating the number of characters based on byte lengths can bedifficult in a variable-width character set. Calculating column lengths in bytes is calledbyte semantics, while measuring column lengths in characters is called charactersemantics.Working in a Global Environment 11-17
<strong>SQL</strong> and PL/<strong>SQL</strong> Programming with UnicodeCharacter semantics is useful for defining the storage requirements for multibytestrings of varying widths. For example, in a Unicode database (AL32UTF8), supposethat you need to define a VARCHAR2 column that can store up to five Chinesecharacters together with five English characters. Using byte semantics, this columnrequires 15 bytes for the Chinese characters, which are three bytes long, and 5 bytes forthe English characters, which are one byte long, for a total of 20 bytes. Using charactersemantics, the column requires 10 characters.The expressions in the following list use byte semantics. Note the BYTE qualifier in theVARCHAR2 expression and the B suffix in the <strong>SQL</strong> function name.■VARCHAR2(20 BYTE)■ SUBSTRB(string, 1, 20)The expressions in the following list use character semantics. Note the CHAR qualifierin the VARCHAR2 expression.■VARCHAR2(20 CHAR)■ SUBSTR(string, 1, 20)This topic includes the following topic:■ NLS_LENGTH_SEMANTICS on page 11-1811.2.9.1 NLS_LENGTH_SEMANTICSThe NLS_LENGTH_SEMANTICS parameter specifies BYTE (default) or CHAR semantics.By default, the character data types CHAR and VARCHAR2 are specified in bytes, notcharacters. Hence, the specification CHAR(20) in a table definition allows 20 bytes forstoring character data.NLS_LENGTH_SEMANTICS enables you to create CHAR, VARCHAR2, and LONG columnsusing either byte or character length semantics. NCHAR, NVARCHAR2, CLOB, and NCLOBcolumns are always character-based. Existing columns are not affected.Example 11–15 shows an example of creating a table. When the database character setis WE8MSWIN1252, the last_name column of the table can hold up to 10 WesternEuropean characters, occupying a maximum of 10 bytes. When the database characterset is Unicode (AL32UTF8), last_name can still hold up to 10 Unicode charactersregardless of the language; however, it can occupy a maximum of 40 bytes.Example 11–15 Length Semantics and CREATE TABLECREATE TABLE temp_employees_table( employee_id NUMBER(4), last_name VARCHAR2(10 CHAR), job_id VARCHAR2(9),manager_id NUMBER(4), hire_date DATE, salary NUMBER(7,2),department_id NUMBER(2)) ;See Also:■<strong>Oracle</strong> Database Concepts for more information about lengthsemantics11.3 <strong>SQL</strong> and PL/<strong>SQL</strong> Programming with Unicode<strong>SQL</strong> is the fundamental language with which all programs and users access data in an<strong>Oracle</strong> database either directly or indirectly. PL/<strong>SQL</strong> is a procedural language thatcombines the data manipulating power of <strong>SQL</strong> with the data processing power of11-18 <strong>SQL</strong> <strong>Developer</strong> Online Help
<strong>SQL</strong> and PL/<strong>SQL</strong> Programming with Unicodeprocedural languages. Both <strong>SQL</strong> and PL/<strong>SQL</strong> can be embedded in other programminglanguages.<strong>Oracle</strong> Express provides products such as <strong>SQL</strong> and PL/<strong>SQL</strong> for inserting andretrieving Unicode data. Data is transparently converted between the database andclient programs, which ensures that client programs are independent of the databasecharacter set and national character set. In addition, client programs are sometimeseven independent of the character data type, such as NCHAR or CHAR, used in thedatabase.The PL/<strong>SQL</strong> and <strong>SQL</strong> engines process PL/<strong>SQL</strong> programs and <strong>SQL</strong> statements onbehalf of client-side programs such as server-side PL/<strong>SQL</strong> stored procedures. Theyallow PL/<strong>SQL</strong> programs to declare CHAR, VARCHAR2, NCHAR, and NVARCHAR2variables and to access <strong>SQL</strong> CHAR and NCHAR data types in the database.This topic describes Unicode-related features in <strong>SQL</strong> and PL/<strong>SQL</strong> that you can deployfor multilingual applications. It includes the following topics:■■■Overview of Unicode<strong>SQL</strong> NCHAR Data TypesUnicode String LiteralsSee Also:■■<strong>Oracle</strong> Database <strong>SQL</strong> Reference for information on <strong>SQL</strong>PL/<strong>SQL</strong> User's Guide and Reference for information on PL/<strong>SQL</strong>11.3.1 Overview of UnicodeUnicode is a universal encoded character set that enables you to store information inany language, using a single character set. Unicode provides a unique code value forevery character, regardless of the platform, program, or language.Unicode has the following advantages:■ It simplifies character set conversion and linguistic sort functions.■ It improves performance compared with native multibyte character sets.■ It supports the Unicode data type based on the Unicode standard.You can store Unicode characters in an <strong>Oracle</strong> database in two ways:■ You can create a Unicode database that enables you to store UTF-8 encodedcharacters as <strong>SQL</strong> CHAR data types.■11.3.2 <strong>SQL</strong> NCHAR Data TypesYou can support multilingual data in specific columns by using Unicode datatypes. You can store Unicode characters into columns of the <strong>SQL</strong> NCHAR data typesregardless of how the database character set has been defined. The NCHAR datatype is an exclusively Unicode data type.There are three <strong>SQL</strong> NCHAR data types:■ The NCHAR Data Type on page 11-20■ The NVARCHAR2 Data Type on page 11-20Working in a Global Environment 11-19
<strong>SQL</strong> and PL/<strong>SQL</strong> Programming with Unicode11.3.2.1 The NCHAR Data TypeWhen you define a table column or a PL/<strong>SQL</strong> variable as the NCHAR data type, thelength is always specified as the number of characters. For example, the followingstatement creates a column with a maximum length of 30 characters:CREATE TABLE table1 (column1 NCHAR(30));The maximum number of bytes for the column is determined as follows:maximum number of bytes =(maximum number of characters) x (maximum number of bytes for each character)For example, if the national character set is UTF8, then the maximum byte length is 30characters times 3 bytes for each character, or 90 bytes.The national character set, which is used for all NCHAR data types, is defined when thedatabase is created. The national character set can be either UTF8 or AL16UTF16. Thedefault is AL16UTF16.The maximum column size allowed is 2000 characters when the national character setis UTF8 and 1000 when it is AL16UTF16. The actual data is subject to the maximumbyte limit of 2000. The two size constraints must be satisfied at the same time. InPL/<strong>SQL</strong>, the maximum length of NCHAR data is 32767 bytes. You can define an NCHARvariable of up to 32767 characters, but the actual data cannot exceed 32767 bytes. Ifyou insert a value that is shorter than the column length, then <strong>Oracle</strong> pads the valuewith blanks to whichever length is smaller: maximum character length or maximumbyte length.Note: UTF8 may affect performance because it is a variable-widthcharacter set. Excessive blank padding of NCHAR fields decreasesperformance. Consider using the NVARCHAR data type or changingto the AL16UTF16 character set for the NCHAR data type.11.3.2.2 The NVARCHAR2 Data TypeThe NVARCHAR2 data type specifies a variable length character string that uses thenational character set. When you create a table with an NVARCHAR2 column, youspecify the maximum number of characters for the column. Lengths for NVARCHAR2are always in units of characters, just as for NCHAR. <strong>Oracle</strong> subsequently stores eachvalue in the column exactly as you specify it, if the value does not exceed the column'smaximum length. <strong>Oracle</strong> does not pad the string value to the maximum length.The maximum column size allowed is 4000 characters when the national character setis UTF8 and 2000 when it is AL16UTF16. The maximum length of an NVARCHAR2column in bytes is 4000. Both the byte limit and the character limit must be met, so themaximum number of characters that is actually allowed in an NVARCHAR2 column isthe number of characters that can be written in 4000 bytes.In PL/<strong>SQL</strong>, the maximum length for an NVARCHAR2 variable is 32767 bytes. You candefine NVARCHAR2 variables up to 32767 characters, but the actual data cannot exceed32767 bytes.The following statement creates a table with one NVARCHAR2 column whosemaximum length in characters is 2000 and maximum length in bytes is 4000.CREATE TABLE table2 (column2 NVARCHAR2(2000));11-20 <strong>SQL</strong> <strong>Developer</strong> Online Help
Locale-Dependent <strong>SQL</strong> Functions with Optional NLS Parameters11.3.3 Unicode String LiteralsYou can input Unicode string literals in <strong>SQL</strong> and PL/<strong>SQL</strong> as follows:■■Put a prefix N before a string literal that is enclosed with single quote marks. Thisexplicitly indicates that the following string literal is an NCHAR string literal. Forexample, N'résumé' is an NCHAR string literal. This has the same limitation asenclosing the string literal with single quote marks, where the data can be lostduring the conversion to the server's database character set. To avoid the potentialloss of data, you can set the environment variable ORA_NCHAR_LITERAL_REPLACE to true. This will transparently replace the N' internally and preservethe text literal for <strong>SQL</strong> processing. By default, this environment variable is set tofalse to maintain backward compatibility.Use the NCHR(n) <strong>SQL</strong> function, which returns a unit of character code in thenational character set, which is AL16UTF16 or UTF8. The result of concatenatingseveral NCHR(n) functions is NVARCHAR2 data. In this way, you can bypass theclient and server character set conversions and create an NVARCHAR2 stringdirectly. For example, NCHR(32) represents a blank character.Because NCHR(n) is associated with the national character set, portability of theresulting value is limited to applications that run with the same national characterset. If this is a concern, then use the UNISTR function to remove portabilitylimitations.■ Use the UNISTR('string') <strong>SQL</strong> function. UNISTR('string') converts a string tothe national character set. To ensure portability and to preserve data, include onlyASCII characters and Unicode encoding in the following form: \xxxx, wherexxxx is the hexadecimal value of a character code value in UTF-16 encodingformat. For example, UNISTR('G\0061ry') represents 'Gary'. The ASCIIcharacters are converted to the database character set and then to the nationalcharacter set. The Unicode encoding is converted directly to the national characterset.The last two methods can be used to encode any Unicode string literals.11.4 Locale-Dependent <strong>SQL</strong> Functions with Optional NLS ParametersAll <strong>SQL</strong> functions whose behavior depends on globalization support conventionsallow NLS parameters to be specified. These functions are:TO_CHARTO_DATETO_NUMBERNLS_UPPERNLS_LOWERNLS_INITCAPNLSSORTExplicitly specifying the optional NLS parameters for these functions enables thefunctions to be evaluated independently of the session's NLS parameters. This featurecan be important for <strong>SQL</strong> statements that contain numbers and dates as string literals.For example, the following query is evaluated correctly if the language specified fordates is AMERICAN:SELECT last_name FROM employees WHERE hire_date > '01-JAN-1999';Working in a Global Environment 11-21
Locale-Dependent <strong>SQL</strong> Functions with Optional NLS ParametersSuch a query can be made independent of the current date language by using astatement similar to the following:SELECT last_name FROM employeesWHERE hire_date > TO_DATE('01-JAN-1999','DD-MON-YYYY','NLS_DATE_LANGUAGE = AMERICAN');In this way, <strong>SQL</strong> statements that are independent of the session language can bedefined where necessary. Such statements are necessary when string literals appear in<strong>SQL</strong> statements in views, CHECK constraints, or triggers.Note: Only <strong>SQL</strong> statements that must be independent of thesession NLS parameter values should explicitly specify optionalNLS parameters in locale-dependent <strong>SQL</strong> functions. Using sessiondefault values for NLS parameters in <strong>SQL</strong> functions usually resultsin better performance.All character functions support both single-byte and multibyte characters. Exceptwhere explicitly stated, character functions operate character by character, rather thanbyte by byte.The rest of this topic includes the following topics:■ Default Values for NLS Parameters in <strong>SQL</strong> Functions■ Specifying NLS Parameters in <strong>SQL</strong> Functions■ Unacceptable NLS Parameters in <strong>SQL</strong> Functions11.4.1 Default Values for NLS Parameters in <strong>SQL</strong> FunctionsWhen <strong>SQL</strong> functions evaluate views and triggers, default values from the currentsession are used for the NLS function parameters. When <strong>SQL</strong> functions evaluateCHECK constraints, they use the default values that were specified for the NLSparameters when the database was created.11.4.2 Specifying NLS Parameters in <strong>SQL</strong> FunctionsNLS parameters are specified in <strong>SQL</strong> functions as 'parameter = value'. For example:'NLS_DATE_LANGUAGE = AMERICAN'The following NLS parameters can be specified in <strong>SQL</strong> functions:NLS_DATE_LANGUAGENLS_NUMERIC_CHARACTERSNLS_CURRENCYNLS_ISO_CURRENCYNLS_DUAL_CURRENCYNLS_CALENDARNLS_SORTTable 11–5 shows which NLS parameters are valid for specific <strong>SQL</strong> functions.Table 11–5<strong>SQL</strong> FunctionTO_DATE<strong>SQL</strong> Functions and Their Valid NLS ParametersValid NLS ParametersNLS_DATE_LANGUAGE,NLS_CALENDAR11-22 <strong>SQL</strong> <strong>Developer</strong> Online Help
Locale-Dependent <strong>SQL</strong> Functions with Optional NLS ParametersTable 11–5<strong>SQL</strong> FunctionTO_NUMBERTO_CHARTO_NCHARNLS_UPPERNLS_LOWERNLS_INITCAPNLSSORT(Cont.) <strong>SQL</strong> Functions and Their Valid NLS ParametersValid NLS ParametersNLS_NUMERIC_CHARACTERS,NLS_CURRENCY,NLS_DUAL_CURRENCY,NLS_ISO_CURRENCY,NLS_DATE_LANGUAGE,NLS_NUMERIC_CHARACTERS,NLS_CURRENCY,NLS_ISO_CURRENCY,NLS_DUAL_CURRENCY,NLS_CALENDARNLS_DATE_LANGUAGE,NLS_NUMERIC_CHARACTERS,NLS_CURRENCY,NLS_ISO_CURRENCY,NLS_DUAL_CURRENCY,NLS_CALENDARNLS_SORTNLS_SORTNLS_SORTNLS_SORTExample 11–16 illustrates how to use NLS parameters in <strong>SQL</strong> functions.Example 11–16Using NLS Parameters in <strong>SQL</strong> FunctionsSELECT TO_DATE('1-JAN-99', 'DD-MON-YY','NLS_DATE_LANGUAGE = American') "01/01/99" FROM DUAL;SELECT TO_CHAR(hire_date, 'DD/MON/YYYY','NLS_DATE_LANGUAGE = French') "Hire Date" FROM employees;SELECT TO_CHAR(SYSDATE, 'DD/MON/YYYY','NLS_DATE_LANGUAGE = ''Traditional Chinese'' ') "System Date" FROM DUAL;SELECT TO_CHAR(13000, '99G999D99','NLS_NUMERIC_CHARACTERS = '',.''') "13K" FROM DUAL;SELECT TO_CHAR(salary, '99G999D99L', 'NLS_NUMERIC_CHARACTERS = '',.''NLS_CURRENCY = ''EUR''') salary FROM employees;SELECT TO_CHAR(salary, '99G999D99C', 'NLS_NUMERIC_CHARACTERS = ''.,''NLS_ISO_CURRENCY = Japan') salary FROM employees;SELECT NLS_UPPER(last_name, 'NLS_SORT = Swiss') "Last Name" FROM employees;SELECT last_name FROM employeesORDER BY NLSSORT(last_name, 'NLS_SORT = German');Note: In some languages, some lowercase characters correspondto more than one uppercase character or vice versa. As a result, thelength of the output from the NLS_UPPER, NLS_LOWER, and NLS_INITCAP functions can differ from the length of the input.Working in a Global Environment 11-23
Locale-Dependent <strong>SQL</strong> Functions with Optional NLS Parameters11.4.3 Unacceptable NLS Parameters in <strong>SQL</strong> FunctionsThe following NLS parameters are not accepted in <strong>SQL</strong> functions except for NLSSORT:■■NLS_LANGUAGENLS_TERRITORY■ NLS_DATE_FORMATNLS_DATE_FORMAT and NLS_TERRITORY_FORMAT are not accepted as parametersbecause they can interfere with required format masks. A date format must always bespecified if an NLS parameter is in a TO_CHAR or TO_DATE function. As a result, NLS_DATE_FORMAT and NLS_TERRITORY_FORMAT are not valid NLS parameters for theTO_CHAR or TO_DATE functions. If you specify NLS_DATE_FORMAT or NLS_TERRITORY_FORMAT in the TO_CHAR or TO_DATE function, then an error is returned.NLS_LANGUAGE can interfere with the session value of NLS_DATE_LANGUAGE. If youspecify NLS_LANGUAGE in the TO_CHAR function, for example, then its value isignored if it differs from the session value of NLS_DATE_LANGUAGE.11-24 <strong>SQL</strong> <strong>Developer</strong> Online Help
IndexSymbols:= assignment operator, 7-6Aaccelerator keysfor menus, 1-2ACCESS_INTO_NULL exception, 7-22AFTER triggerscorrelation names and, 9-4specifying, 9-2aliasestables, 6-6ALTER INDEX statement, 6-16ALTER TABLE statement, 6-16, 6-17analyzing tables, 1-10anonymous PL/<strong>SQL</strong> blocks, 7-2apostrophes, 7-7Apply Filter, 1-3arraysPL/<strong>SQL</strong>, 7-17assignment operator, 7-6assignmentsIN OUT parameters, 7-15associationsfile types, 3-22attributes%ROWTYPE, 7-10%TYPE, 7-11autocommitpreference for database connections, 1-31autocomplete preferences, 1-5BBEFORE triggerscorrelation names and, 9-4specifying, 9-2BEGINblock structure, 7-3BINARY_DOUBLEdata types, 5-5BINARY_FLOATdata types, 5-5bind variablesfor reports, 1-23PL/<strong>SQL</strong>, 7-21blocksanonymous, 7-2BEGIN, 7-3DECLARE, 7-3END, 7-3EXCEPTION, 7-3nesting, 7-1, 7-2structure, 7-3BODYCREATE PACKAGE <strong>SQL</strong> statement, 8-3with <strong>SQL</strong> CREATE PACKAGE statement, 8-3Booleanliterals, 7-7breakpointscreating and editing, 3-25CC number format mask, 11-14calendarsparameter, 11-10CASE expressionsoverview, 7-12case sensitivityidentifier, 7-6string literal, 7-7CASE_NOT_FOUND exception, 7-22centurydate format masks, 5-7character datastoring, 5-1character literals, 7-7quoting, 6-3using in <strong>SQL</strong> statements, 6-3character setnational, 11-20character setsnational, 11-20check constraints, 3-12, 4-5how to use, 4-6Check for Updates feature, 3-2Clear Filter, 1-3coalescing an index, 1-7code fragments, 1-21Index-1
COLLECTION_IS_NULL exception, 7-22collectionsPL/<strong>SQL</strong>, 7-17column aliasusing with SELECT, 6-4column constraints, 4-4columnsaccessing in triggers, 9-3data types, 4-2decrypting, 1-10encrypting, 1-10listing in an UPDATE trigger, 9-4unique key, 4-5commentsin PL/<strong>SQL</strong>, 7-4COMMIT statement, 6-8, 6-9Compact option for shrinking a table, 1-10comparison operatorsBETWEEN, 6-4equality, 6-4IN, 6-4LIKE, 6-4NULL, 6-4compilingfunction, 1-7with debug, 1-7procedure, 1-8with debug, 1-8view, 1-11completion<strong>SQL</strong> <strong>Developer</strong> preferences, 1-5composite keysforeign, 4-6conditional predicatestrigger bodies, 9-4configuring file type associations, 3-22connectionscreating, editing, or selecting, 3-2explanation, 1-11CONSTANTfor declaring constants, 7-4constantsdeclaring, 7-4declaring in PL/<strong>SQL</strong>, 7-4constraintscheck, 3-12, 4-5column, 4-4disabled, 1-24ensuring data integrity, 4-3NOT NULL, 7-8table-level, 4-4types, 4-4unique, 3-11control structuresPL/<strong>SQL</strong>, 7-11correlation names, 9-3NEW, 9-3OLD, 9-3when preceded by a colon, 9-4CREATEwith PROCEDURE statement, 8-2CREATE FUNCTION statement, 8-2CREATE INDEX statement, 6-16CREATE PROCEDURE statement, 8-2CREATE SEQUENCE statement, 6-17CREATE statementpackages, 8-3with FUNCTION, 8-2CREATE SYNONYM statement, 6-18CREATE TABLE statement, 6-15CREATE TRIGGER statement, 9-1creatingfunctions, 8-2packages, 8-3procedures, 8-2creating a constraintusing <strong>SQL</strong> statement, 6-16creating a tableusing <strong>SQL</strong> statement, 6-15creating an index<strong>SQL</strong> statement, 6-16creating indexes for use with constraints, 4-7currenciesformats, 11-13CURSOR_ALREADY_OPEN exception, 7-22cursorsdefinition, 7-17explicit, 7-17implicit, 7-17customizing <strong>SQL</strong> <strong>Developer</strong>setting preferences, 1-28Ddataentering and modifying, 1-13integrity checking on input, 5-3data definition language (DDL)<strong>SQL</strong> statements, 6-15data integrity rulesas constraints, 4-4data manipulation languagedescribed, 6-7data structuresPL/<strong>SQL</strong>, 7-17data typesBINARY_DOUBLE, 5-5BINARY_FLOAT, 5-5CHAR, 5-1character, 5-1creating, 3-18description, 4-2floating-point number, 5-4in table columns, 4-2NCHAR, 5-1NUMBER, 5-3numeric, 5-2NVARCHAR2, 5-1overview, 5-1VARCHAR2, 5-1Index-2
database connectionscreating, editing, or selecting, 3-2explanation, 1-11database linkcreating and editing, 3-4database objects, 1-6exporting, 3-22managing, 4-1naming, 4-1database resident program units, 8-1database triggers, 9-1date and time datastoring, 5-5date and time parameters, 11-7DATE data type, 5-5date formats, 11-7, 11-8datesISO standard, 11-10NLS_DATE_LANGUAGE parameter, 11-9datetimeliterals, 7-7daysformat element, 11-9DBMS_OUTPUTprocedures for displaying output in PL/<strong>SQL</strong>, 7-9DBMS_OUTPUT packagedisplaying output, 7-9displaying output from PL/<strong>SQL</strong>, 8-5using PUT_LINE to display output, 7-9DBMS_OUTPUT pane, 1-20debugging PL/<strong>SQL</strong> function or procedure, 1-14dialog box, 3-25declarationsconstants, 7-4exceptions in PL/<strong>SQL</strong>, 7-23PL/<strong>SQL</strong> %ROWTYPE and %TYPE, 7-10PL/<strong>SQL</strong> subprograms, 7-15using NOT NULL constraint, 7-8declarative partof PL/<strong>SQL</strong> block, 7-3DECLAREblock structure, 7-3decryptiondata in a table column, 1-10DELETE statement, 6-7, 6-8column values and triggers, 9-4dependenciesschema objectstrigger management, 9-6DESCRIBE command<strong>SQL</strong>*Plus, 10-3design considerations<strong>Oracle</strong> Database, 4-1dialog boxes and tabs, 3-1directories (directory objects), 1-6disabled constraints, 1-24disabled triggerdefinition, 9-4disablingtriggers, 9-4displaying outputfrom PL/<strong>SQL</strong>, 7-9setting SERVEROUTPUT, 7-9, 8-5using DBMS_OUTPUT.PUT_LINE, 7-9displaying PL/<strong>SQL</strong> outputwith DBMS_OUTPUT, 7-9distributed databasestriggers and, 9-6dot notation, 7-11DROP INDEX statement, 6-16DROP SEQUENCE statement, 6-17DROP SYNONYM statement, 6-18DROP TABLE statement, 6-17droppingindexes, 4-10dropping a sequenceusing <strong>SQL</strong> statement, 6-17dropping a synonymusing <strong>SQL</strong> statement, 6-18dropping a tableusing <strong>SQL</strong> statement, 6-17DUALdummy table, 6-10dummy tableDUAL, 6-10DUP_VAL_ON_INDEX exception, 7-22dynamic <strong>SQL</strong>, 7-19Eenabled triggerdefinition, 9-4enablingtriggers, 9-4encryptiondata in a table column, 1-10ENDblock structure, 7-3ensuring data integritywith constraints, 4-3entering data in tables, 1-13error handlingPL/<strong>SQL</strong>, 7-21EXCEPTIONblock structure, 7-3exception handlersPL/<strong>SQL</strong>, 7-21exception-handling partof PL/<strong>SQL</strong> block, 7-3exceptionsadvantages of PL/<strong>SQL</strong>, 7-23declaring in PL/<strong>SQL</strong>, 7-23during trigger execution, 9-4list of predefined in PL/<strong>SQL</strong>, 7-22predefined in PL/<strong>SQL</strong>, 7-21scope rules in PL/<strong>SQL</strong>, 7-23executable partof PL/<strong>SQL</strong> block, 7-3execution plan, 1-19EXIT-WHEN statementIndex-3
overview, 7-14EXPLAIN PLANexecution plan, 1-19exportingdatabase objects, 3-22table data, 1-10, 3-23extensions<strong>SQL</strong> <strong>Developer</strong>, 1-33external tablesproperties, 3-16FF10 keyfor File menu, 1-2FALSE value, 7-7file I/O, 8-5file typesassociating with <strong>SQL</strong> <strong>Developer</strong>, 3-22filterapplying, 1-3clearing, 1-3floating-point numberdata types, 5-4floating-point numbers, 5-2foldersfor user-defined reports, 1-28, 3-19FOR EACH ROW clause, 9-3foreign keyreferential integrity between tables, 4-6foreign keys, 3-12format elementsday, 11-9month, 11-9format masks, 11-12TO_DATE function, 5-7formatscurrency, 11-13date, 11-8numeric, 11-12time, 11-9Freeze Viewpinning an object’s display, 1-3, 1-13FUNCTIONwith CREATE statement, 8-2functionscompiling, 1-7compiling with debug, 1-7creating, 8-2creating and editing, 3-6debugging, 3-25execute, 8-3managing, 8-3overview, 8-1running, 3-25<strong>SQL</strong> aggregate, 6-14<strong>SQL</strong> arithmetic operators, 6-12<strong>SQL</strong> character, 6-11<strong>SQL</strong> date, 6-13<strong>SQL</strong> numeric, 6-12Gglobalization supportaltering NLS parameter settings, 11-3calendar definitions, 11-10date and time parameter settings, 11-7default values for NLS parameters in <strong>SQL</strong>functions, 11-22features, 11-1language and territory parameter settings, 11-5linguistic sorting and searching, 11-14locale, 11-4monetary parameter settings, 11-13National Language Support (NLS) features, 11-1NLS_LANG parameter setting, 11-4numeric and list parameter settings, 11-11overview, 11-1programming with unicode, 11-18setting up the environment, 11-3specifying values for NLS parameters in <strong>SQL</strong>functions, 11-22unacceptable NLS parameters in <strong>SQL</strong>functions, 11-24GOTO statementoverview, 7-15graphical user interface (GUI), 1-1Hhelpusing the online help, 1-35HELP command<strong>SQL</strong>*Plus, 10-2Iidentifiersmaximum length, 7-6IF-THEN-ELSE statementoverview, 7-11indexes, 3-12ascending, 4-7choose the correct order of columns forcomposites, 4-9coalescing, 1-7column, 4-7concatenated, 4-7creating and editing, 3-5creating for use with constraints, 4-7descending, 4-7drop if not required, 4-10dropping, 4-10explanation, 1-7function-based, 4-7guidelines, 4-8limit the number, 4-9making unusable, 1-7managing, 4-6normal type, 4-7order of columns, 4-9rebuilding, 1-7Index-4
single column, 4-7types, 4-7index-organized tablesproperties, 3-15initializationusing DEFAULT, 7-8INSERT statement, 6-7column values and triggers, 9-3integrity constraintsCHECK, 4-6triggers vs., 9-5INTERVAL DAY TO SECOND data type, 5-5INTERVAL YEAR TO MONTH data type, 5-5introduction, 1-1, 4-1, 5-1, 6-1, 7-1, 8-1, 9-1, 10-1, 11-1INVALID_CURSOR exception, 7-22INVALID_NUMBER exception, 7-22ISO standard date format, 11-10Jjoinsdisplaying data from multiple tables withSELECT, 6-6Kkeywordsuse in PL/<strong>SQL</strong>, 7-6Llanguage support, 11-2length semantics, 11-17linguistic sortsparameters, 11-14linkdatabase, 3-4list parameter, 11-11literalsBoolean, 7-7character, 7-7datetime, 7-7numeric, 7-7string, 7-7types of PL/<strong>SQL</strong>, 7-7local subprograms, 8-2localeglobalization support, 11-4locking a table, 1-10LOGIN_DENIED exception, 7-22LOOP statementoverview, 7-13lowercase characters in object namesquotation marks required, 3-1Mmanaging database objectsoverview, 4-1managing indexes, 4-6managing tables, 4-2materialized view logs, 1-8materialized views, 1-7options when creating or editing, 3-20maximum sizeidentifier, 7-6MOD_PL<strong>SQL</strong>OWA output, 1-20modifying a constraintusing <strong>SQL</strong> statement, 6-16modifying a tableusing <strong>SQL</strong> statement, 6-17modifying an index<strong>SQL</strong> statement, 6-16modifying data in tables, 1-13modularity, 8-3monetary parameters, 11-13monthsformat element, 11-9moving a table to another tablespace, 1-10multi-line comments, 7-4Nnational character literalsquoting, 6-3national character set, 11-20National Language Support (NLS)features, 11-1globalization support, 11-1NCHAR data type, 5-1, 11-20NCHR <strong>SQL</strong> function, 11-21nested tablesPL/<strong>SQL</strong>, 7-17nestingblock, 7-1, 7-2NEW correlation name, 9-3NLS parametersdefault values in <strong>SQL</strong> functions, 11-22settings, 11-3specifying in <strong>SQL</strong> functions, 11-22unacceptable in <strong>SQL</strong> functions, 11-24NLS_CALENDAR parameter, 11-11NLS_COMP parameter, 11-16NLS_CURRENCY parameter, 11-13NLS_DATE_FORMAT parameter, 5-7, 11-8NLS_DATE_LANGUAGE parameter, 11-8NLS_DUAL_CURRENCY parameter, 11-14NLS_INITCAP <strong>SQL</strong> function, 11-21NLS_ISO_CURRENCY parameter, 11-14NLS_LANG parameter, 11-4choosing a locale, 11-4NLS_LANGUAGE parameter, 11-5NLS_LOWER <strong>SQL</strong> function, 11-21NLS_NUMERIC_CHARACTERS parameter, 11-12NLS_SORT parameter, 11-15NLS_TERRITORY parameter, 11-6NLS_TIMESTAMP_FORMAT parameterparametersNLS_TIMESTAMP_FORMAT, 11-9, 11-10NLS_UPPER <strong>SQL</strong> function, 11-21Index-5
NLSSORT <strong>SQL</strong> function, 11-21NO_DATA_FOUND exception, 7-22NOT NULL constraintusing in variable declaration, 7-8NOT_LOGGED_ON exception, 7-22NUMBER data type, 5-3numeric data types, 5-2numeric formats, 11-12numeric literals, 7-7numeric parameters, 11-11NVARCHAR2 data type, 5-1, 11-20Oobjectsdatabase, 1-6exporting, 3-22OLD correlation name, 9-3online helpusing, 1-35<strong>Oracle</strong> Databasedesign considerations, 4-1<strong>Oracle</strong> Web Agent (OWA), 1-20ORDER BY clauseusing with SELECT, 6-5overview, 1-1, 4-1, 5-1, 6-1, 7-1, 8-1, 9-1, 10-1, 11-1data types, 5-1functions, 8-1globalization support, 11-1managing database objects, 4-1packages, 8-1PL/<strong>SQL</strong>, 7-1procedures, 8-1<strong>SQL</strong>, 6-1<strong>SQL</strong>*Plus, 10-1subprograms, 8-1triggers, 9-1OWA_OUTPUT pane, 1-20PPACKAGEwith <strong>SQL</strong> CREATE statement, 8-3packagewriting with PL/<strong>SQL</strong>, 8-3PACKAGE BODYwith <strong>SQL</strong> CREATE statement, 8-3packaged subprograms, 8-2packagesaccessing variables, 8-4body, 8-2creating, 8-3creating and editing, 3-6debugging, 3-25guidelines for writing, 8-3hidden declarations, 8-3overview, 8-1overview of <strong>Oracle</strong> supplied, 8-5product-specific, 8-5running, 3-25specification, 8-2understanding, 8-2variables, 8-4visibility of contents, 8-3parameterscalendar, 11-10linguistic sorts, 11-14monetary, 11-13NLS_CALENDAR, 11-11NLS_COMP, 11-16NLS_CURRENCY, 11-13NLS_DATE_FORMAT, 11-8NLS_DATE_LANGUAGE, 11-8NLS_DUAL_CURRENCY, 11-14NLS_ISO_CURRENCY, 11-14NLS_LANG, 11-4NLS_LANGUAGE, 11-5NLS_NUMERIC_CHARACTERS, 11-12NLS_SORT, 11-15NLS_TERRITORY, 11-6numeric, 11-11setting, 11-4time and date, 11-7time zone, 11-9, 11-10partitioned tablespartition definitions, 3-15partitioning options, 3-14subpartitioning options (templates), 3-14performanceindex column order, 4-9pinning an object’s display, 1-3, 1-13PL/<strong>SQL</strong>, 7-1%ROWTYPE attribute, 7-10%TYPE attribute, 7-10anonymous blocks, 7-2arrays, 7-17assigning values with SELECT INTO, 7-9assignment operator, 7-6bind variables, 7-21block structure, 7-3collections, 7-17comments, 7-4control structures, 7-11cursor, 7-17data structures, 7-17declarations using DEFAULT, 7-8declarations using NOT NULL, 7-8declaring constants, 7-4declaring variables, 7-4DEFAULT keyword for assignments, 7-8displaying output, 7-9, 8-5entering and executing code, 7-2error handling, 7-21exception handling, 7-21identifiers, 7-5input data, 7-9literals, 7-7local subprograms, 7-15nested tables, 7-17output data, 7-9Index-6
overview of, 7-1processing queries, 7-19program units, 7-1programming with unicode, 11-18records, 7-18SELECT INTO, 7-9stored procedures, 7-2trigger bodies, 9-3using dynamic <strong>SQL</strong>, 7-19using features, 7-2variable assignments, 7-6writing reusable code, 8-3PL/<strong>SQL</strong> and <strong>SQL</strong> and Unicode, 11-19PL/<strong>SQL</strong> subprogramscreating and editing, 3-6debugging, 3-25breakpoints, 3-25running, 3-25preferencescustomizing <strong>SQL</strong> <strong>Developer</strong>, 1-28primary key, 3-10for a table, 4-5PRIMARY KEY constraintsmultiple columns in, 4-5UNIQUE key constraint vs., 4-5private synonyms, 3-7privilegesneeded on triggers, 9-6triggers, 9-6PROCEDUREwith CREATE statement, 8-2procedures, 7-2called by triggers, 9-6compiling, 1-8compiling with debug, 1-8creating, 8-2creating and editing, 3-6execute, 8-3managing, 8-3overview, 8-1stored procedures, 7-2program units, 7-1, 8-3PROGRAM_ERROR exception, 7-22pseudocolumnsROWNUM, 6-10SYSDATE, 6-10USER, 6-10using in <strong>SQL</strong> statements, 6-10public synonyms, 3-7PUT_LINEdisplaying output with, 7-9Qqueriesin DML, 6-7quotation marksfor name with lowercase characters, specialcharacters, or spaces, 3-1quoting character literals, 6-3Rraising exceptionstriggers, 9-4rebuilding an index, 1-7recompilingview, 1-11recordsdefinition, 7-10PL/<strong>SQL</strong>, 7-18Recycle bin, 1-9report navigator, 1-22reports, 1-22bind variables for, 1-23user-definedcreating and editing, 3-18explanation, 1-27folders for, 1-28, 3-19UserReports.xml, 1-27reserved wordssyntactic meaning in PL/<strong>SQL</strong>, 7-6restrictionssystem triggers, 9-6ROLLBACK statement, 6-8, 6-9row triggersdefining, 9-3timing, 9-2UPDATE statements and, 9-4ROWNUMpseudocolumn, 6-10ROWTYPE attributedeclaring, 7-10ROWTYPE_MISMATCH exception, 7-22running PL/<strong>SQL</strong> function or procedure, 1-14dialog box, 3-25Sscalegreater than precision, 5-3schema objects, 1-6description, 4-1tables, 4-2schemasdescription, 4-1scientific notation, 7-7scopeexceptions in PL/<strong>SQL</strong>, 7-23script runner, 1-19scriptsrunning, 1-19SELECT INTOPL/<strong>SQL</strong>, 7-9SELECT statements, 6-2SELF_IS_NULL exception, 7-22sequencescreating and editing, 3-6description, 4-10managing, 4-10using in <strong>SQL</strong> statements, 6-11SERVEROUTPUTIndex-7
displaying output from PL/<strong>SQL</strong>, 7-9setting ON to display output, 8-5SET commandfor <strong>SQL</strong>*Plus settings, 10-3shortcut keysfor menus, 1-2shrinking a table, 1-10single-line comments, 7-4snippets, 1-21sortingspecifying nondefault linguistic sorts, 11-15,11-16source typesdescription, 8-1managing, 8-1spaces in object namesquotation marks required, 3-1special characters in object namesquotation marks required, 3-1splitdata pane for a table or view, 1-13SPOOL command<strong>SQL</strong>*Plus, 10-4<strong>SQL</strong>aggregate functions, 6-14arithmetic operators, 6-12character functions, 6-11character literals in statements, 6-3column alias, 6-4committing changes with COMMIT, 6-9comparison operators, 6-4creating a constraint, 6-16creating a table, 6-15creating an index, 6-16data definition language (DDL), 6-15data manipulation language (DML), 6-7date functions, 6-13deleting rows in a table with DELETE, 6-8displaying data from multiple tables, 6-6dropping a sequence, 6-17dropping a synonym, 6-18dropping a table, 6-17dynamic, 7-19functions, 6-10inserting rows in a table with INSERT, 6-7joining tables in SELECT, 6-6modifying a constraint, 6-16modifying a table, 6-17modifying an index, 6-16numeric functions, 6-12ORDER BY clause in SELECT, 6-5overview of, 6-1PL/<strong>SQL</strong> and, 7-1programming with unicode, 11-18pseudocolumns, 6-10querying data, 6-2retrieving data from tables, 6-2SELECT statement, 6-2sequences, 6-10, 6-11statement types, 6-2transaction control statements, 6-8types of statements, 6-2undoing changes with ROLLBACK, 6-9updating data in a table with UPDATE, 6-8using with <strong>Oracle</strong> Database, 6-1WHERE clause in SELECT, 6-4<strong>SQL</strong> <strong>Developer</strong> preferences, 1-28<strong>SQL</strong> functionsdefault values for NLS parameters, 11-22NCHR, 11-21NLS_INITCAP, 11-21NLS_LOWER, 11-21NLS_UPPER, 11-21NLSSORT, 11-21specifying NLS parameters, 11-22TO_CHAR, 11-21TO_DATE, 11-21TO_NUMBER, 11-21unacceptable NLS parameters, 11-24UNISTR, 11-21<strong>SQL</strong> scriptsrunning, 1-19<strong>SQL</strong> statementscategories, 6-2in trigger bodies, 9-3, 9-5not allowed in triggers, 9-5<strong>SQL</strong> Worksheetusing, 1-16<strong>SQL</strong>*Plusdefining a variable, 10-5DESCRIBE command, 10-3displaying help, 10-2entering commands and statements, 10-2executing commands and statements, 10-2exiting, 10-2HELP command, 10-2location of executable, 3-27location of executable (<strong>SQL</strong> <strong>Developer</strong>preference), 1-31overview, 10-1prompting for a variable, 10-4running <strong>SQL</strong> scripts, 10-3SET command, 10-3settings, 10-3SPOOL command, 10-4spooling output, 10-4starting from the operating system commandprompt, 10-2using, 1-21using variables, 10-4<strong>SQL</strong>DEVELOPER_USER_DIR environmentvariable, 1-35standalone subprograms, 8-2execute, 8-3managing, 8-3statement triggersconditional code for statements, 9-4specifying <strong>SQL</strong> statement, 9-2timing, 9-2UPDATE statements and, 9-4Index-8
valid <strong>SQL</strong> statements, 9-5statisticscomputing table and column, 1-10estimating table and column, 1-10storage options, 3-13STORAGE_ERROR exception, 7-22stored procedures, 7-2stored subprograms, 8-2in <strong>Oracle</strong> database, 8-2storing, 5-2string literals, 7-7Unicode, 11-21Structured Query Language (<strong>SQL</strong>), 6-1subpartitionstemplates, 3-14subprogramscreating and editing, 3-6debugging, 3-25declaring PL/<strong>SQL</strong>, 7-15functions, 8-2local, 8-2managing, 8-3overview, 8-1packaged, 8-2procedures, 8-2running, 3-25standalone, 8-2stored, 8-2SUBSCRIPT_BEYOND_COUNT exception, 7-22SUBSCRIPT_OUTSIDE_LIMIT exception, 7-22substitution variables, 1-19synonymscreating and editing, 3-7description, 4-11managing, 4-11SYS_INVALID_ROWID exception, 7-22SYSDATEpseudocolumn, 6-10Ttable-level constraints, 4-4tablesaliases, 6-6analyzing, 1-10compacting, 1-10computing statistics, 1-10creating and editing, 3-9creating quickly, 3-8decrypting column data, 1-10encrypting column data, 1-10entering and modifying data, 1-13estimating statistics, 1-10exporting data, 1-10, 3-23externalproperties, 3-16index-organizedproperties, 3-15locking, 1-10managing, 4-2moving to another tablespace, 1-10partitionedpartition definitions, 3-15partitioning options, 3-14subpartitioning options (templates), 3-14primary key, 4-5shrinking, 1-10splitting the data pane, 1-13temporary, 3-9truncating, 1-10temporary tables, 3-9territory definition, 11-6territory support, 11-2time and date datastoring, 5-5time and date parameters, 11-7time zoneparameters, 11-9, 11-10TIMEOUT_ON_RESOURCE exception, 7-22TIMESTAMP data type, 5-5TIMESTAMP WITH LOCAL TIME ZONE datatype, 5-5TIMESTAMP WITH TIME ZONE data type, 5-5tnsnames.ora file, 1-12TO_CHAR <strong>SQL</strong> function, 11-21default date format, 11-8group separator, 11-12language for dates, 11-8spelling of days and months, 11-9TO_DATE function, 5-7TO_DATE <strong>SQL</strong> function, 11-21default date format, 11-8language for dates, 11-8spelling of days and months, 11-9TO_NUMBER <strong>SQL</strong> function, 11-21TOO_MANY_ROWS exception, 7-23transaction control statements, 6-8transactionstransaction control statements, 6-8triggerdisableddefinition, 9-4enableddefinition, 9-4triggersaccessing column values, 9-3AFTER, 9-2, 9-4AFTER option, 9-2as a stored PL/<strong>SQL</strong> subprogram, 9-1BEFORE, 9-2, 9-4BEFORE option, 9-2body, 9-5column list in UPDATE, 9-4conditional predicates, 9-4controlling when fired, 9-2correlation names, 9-3creating, 9-1, 9-5creating and editing, 3-17designing, 9-5detecting the operation that fired a trigger, 9-4Index-9
disabling, 9-4enabling, 9-4error conditions and exceptions, 9-4errors, 9-4events, 9-2exceptions, 9-4fired multiple times with BEFORE option, 9-3FOR EACH ROW clause, 9-3FOR EACH ROW option, 9-3guidelines for design, 9-5illegal <strong>SQL</strong> statements, 9-5integrity constraints vs., 9-5naming, 9-2NEW column value, 9-3OLD column value, 9-3overview, 9-1privileges, 9-6privileges needed, 9-6procedures and, 9-6remote dependencies and, 9-6restrictions, 9-3, 9-5row, 9-3triggering statement, 9-2types, 9-2WHEN clause, 9-3when fired, 9-2TRUE value, 7-7truncating a table, 1-10tutorialcreating objects for a small database, 2-1TYPE attributedeclaring, 7-11typescreating, 3-18UUnicodePL/<strong>SQL</strong> and <strong>SQL</strong>, 11-19programming, 11-2programming with <strong>SQL</strong> and PL/<strong>SQL</strong>, 11-18string literals, 11-21unique constraints, 3-11unique keyon a column, 4-5UNIQUE key constraintsPRIMARY KEY constraint vs., 4-5UNISTR <strong>SQL</strong> function, 11-21unusable indexes, 1-7UPDATE statement, 6-7, 6-8column values and triggers, 9-4triggers and, 9-4updateschecking for <strong>SQL</strong> <strong>Developer</strong> updates, 3-2USERpseudocolumn, 6-10user information location, 1-34user interface (UI), 1-1user-defined reportscreating and editing, 3-18explanation, 1-27folders for, 1-28, 3-19UserReports.xml, 1-27user-defined typescreating, 3-18UserReports.xml, 1-27UTL_FILE package, 8-5VVALUE_ERROR exception, 7-23VARCHAR2 data type, 5-1variablesaccessing in packages, 8-4bind, 7-21declaring in PL/<strong>SQL</strong>, 7-4passing as IN OUT parameter, 7-15using with <strong>SQL</strong>*Plus, 10-4viewscompiling, 1-11creating and editing, 3-19description, 4-10managing, 4-10options when creating or editing, 3-20recompiling, 1-11splitting the data pane, 1-13visibilityof package contents, 8-3WWHEN clause, 9-3cannot contain PL/<strong>SQL</strong> expressions, 9-3correlation names, 9-4WHERE clauseusing with SELECT, 6-4WHILE-LOOP statementoverview, 7-13ZZERO_DIVIDE exception, 7-23Index-10