You are on page 1of 188

Oracle® Database Express Edition

2 Day Developer Guide


10g Release 2 (10.2)
B25108-01

October 2005

Beta Draft
Oracle Database Express Edition 2 Day Developer Guide, 10g Release 2 (10.2)

B25108-01

Copyright © 2005, Oracle. All rights reserved.

The Programs (which include both the software and documentation) contain proprietary information; they
are provided under a license agreement containing restrictions on use and disclosure and are also protected
by 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 other
independently 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 in
the 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 these
Programs may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose.

If the Programs are delivered to the United States Government or anyone licensing or using the Programs on
behalf of the United States Government, the following notice is applicable:

U.S. GOVERNMENT RIGHTS Programs, software, databases, and related documentation and technical data
delivered 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. As
such, use, duplication, disclosure, modification, and adaptation of the Programs, including documentation
and technical data, shall be subject to the licensing restrictions set forth in the applicable Oracle license
agreement, and, to the extent applicable, the additional rights set forth in FAR 52.227-19, Commercial
Computer Software—Restricted Rights (June 1987). Oracle Corporation, 500 Oracle Parkway, Redwood City,
CA 94065

The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently
dangerous 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 such
purposes, and we disclaim liability for any damages caused by such use of the Programs.

Oracle, JD Edwards, PeopleSoft, and Retek are registered trademarks of Oracle Corporation and/or its
affiliates. 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 third
parties. Oracle 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 services
from a third party, the relationship is directly between you and the third party. Oracle is not responsible for:
(a) the quality of third-party products or services; or (b) fulfilling any of the terms of the agreement with the
third party, including delivery of products or services and warranty obligations related to purchased
products or services. Oracle is not responsible for any loss or damage of any sort that you may incur from
dealing with any third party.

Alpha and Beta Draft documentation are considered to be in prerelease status. This documentation is
intended for demonstration and preliminary use only. We expect that you may encounter some errors,
ranging from typographical errors to data inaccuracies. This documentation is subject to change without
notice, and it may not be specific to the hardware on which you are using the software. Please be advised
that prerelease documentation in not warranted in any manner, for any purpose, and we will not be
responsible for any loss, costs, or damages incurred due to the use of this documentation.
Contents

Preface ................................................................................................................................................................. xi
Audience....................................................................................................................................................... xi
Documentation Accessibility ..................................................................................................................... xi
Structure ...................................................................................................................................................... xii
Related Documentation ............................................................................................................................ xiii
Conventions ............................................................................................................................................... xiii

1 Overview of Development
Overview of Oracle Express Server Application Development...................................................... 1-1
Oracle Database Express Edition ..................................................................................................... 1-2
SQL ....................................................................................................................................................... 1-2
PL/SQL................................................................................................................................................ 1-2
Datatypes............................................................................................................................................. 1-3
Database Objects ................................................................................................................................ 1-3
Basic Application Development Concepts ..................................................................................... 1-3
Development Tools ............................................................................................................................ 1-4
Logging in to the Database Home Page .................................................................................. 1-4
Other Development Environments....................................................................................................... 1-5
Oracle Call Interface (OCI) and Oracle C++ Call Interface (OCCI) ............................................ 1-5
Open Database Connectivity (ODBC)............................................................................................. 1-6
Oracle Data Provider for .NET (ODP.NET) ................................................................................... 1-6
Oracle Database Extensions for .NET ............................................................................................. 1-7
Oracle Developer Tools for Visual Studio .NET............................................................................ 1-7
Oracle HTML DB Developer ............................................................................................................ 1-8
Oracle JDBC ........................................................................................................................................ 1-8
Oracle Provider for OLE DB............................................................................................................. 1-8
PHP....................................................................................................................................................... 1-8

2 Using Datatypes
Overview of Datatypes............................................................................................................................ 2-1
Viewing Datatypes With Object Browser....................................................................................... 2-1
Viewing Datatypes With SQL Commands..................................................................................... 2-2
Storing Character Data ............................................................................................................................ 2-3
What are the Character Datatypes? ................................................................................................. 2-3
Choosing Between the Character Datatypes.................................................................................. 2-4

Beta Draft iii


Storing Numeric Data.............................................................................................................................. 2-4
What Are the Numeric Datatypes? ................................................................................................. 2-4
Using NUMBER Datatypes .............................................................................................................. 2-5
Using Floating-Point Number Formats .......................................................................................... 2-6
BINARY_FLOAT......................................................................................................................... 2-6
BINARY_DOUBLE ..................................................................................................................... 2-7
Storing Datetime Data............................................................................................................................. 2-7
Using DATE and TIMESTAMP Datatypes .................................................................................... 2-7
Using the DATE Datatype ......................................................................................................... 2-7
Using the TIMESTAMP Datatype ............................................................................................ 2-7
Using the TIMESTAMP WITH TIME ZONE Datatype......................................................... 2-7
Using the TIMESTAMP WITH LOCAL TIME ZONE Datatype.......................................... 2-8
Representing the Difference Between Datetime Values........................................................ 2-8
Manipulating the DATE and TIME Formats ................................................................................. 2-8

3 Managing Database Objects


Overview of Managing Objects ............................................................................................................ 3-1
Database Objects for Your Application........................................................................................... 3-2
Using Object Browser to Manage Database Objects in Your Schema ........................................ 3-2
Viewing Object Reports..................................................................................................................... 3-3
Managing Tables ...................................................................................................................................... 3-4
Column Datatypes ............................................................................................................................. 3-5
Column Default Values ..................................................................................................................... 3-6
Ensuring Data Integrity With Constraints ..................................................................................... 3-6
Column Constraints........................................................................................................................... 3-6
Table-Level Constraints .................................................................................................................... 3-7
Primary Key ................................................................................................................................. 3-7
Unique Key .................................................................................................................................. 3-8
Check Constraint......................................................................................................................... 3-8
Foreign Key.................................................................................................................................. 3-9
Creating a Table.................................................................................................................................. 3-9
Displaying a Table .......................................................................................................................... 3-10
Adding a Table Column................................................................................................................. 3-11
Dropping a Table Column ............................................................................................................. 3-12
Adding a New Table Constraint ................................................................................................... 3-12
Add a Foreign Key Constraint ...................................................................................................... 3-13
Viewing Existing Constraints........................................................................................................ 3-14
Modifying an Existing Constraint ................................................................................................ 3-14
Dropping a Constraint.................................................................................................................... 3-15
Adding Data to a Table .................................................................................................................. 3-15
Viewing Table Data......................................................................................................................... 3-17
Modifying Data in a Table ............................................................................................................. 3-18
Removing a Row in a Table ........................................................................................................... 3-18
Dropping a Table............................................................................................................................. 3-19
Managing Indexes ................................................................................................................................. 3-19
Creating Indexes for Use with Constraints ................................................................................. 3-20
Index Types...................................................................................................................................... 3-20

iv Beta Draft
Normal....................................................................................................................................... 3-20
Ascending and Descending.................................................................................................... 3-20
Column and Function-based .................................................................................................. 3-20
Single Column and Concatenated ........................................................................................ 3-20
Guidelines for Creating Indexes ................................................................................................... 3-21
Index the Correct Tables and Columns ................................................................................ 3-21
Limit the Number of Indexes for Each Table....................................................................... 3-22
Choose the Order of Columns in Composite Indexes ........................................................ 3-22
Drop Indexes That Are No Longer Required ..................................................................... 3-22
Creating an Index ............................................................................................................................ 3-23
Displaying an Index........................................................................................................................ 3-23
Dropping an Index.......................................................................................................................... 3-24
Managing Views.................................................................................................................................... 3-24
Creating a View ............................................................................................................................... 3-25
Displaying a View........................................................................................................................... 3-26
Dropping a View ............................................................................................................................. 3-26
Managing Sequences............................................................................................................................ 3-26
Creating a Sequence........................................................................................................................ 3-27
Displaying a Sequence.................................................................................................................... 3-27
Dropping a Sequence...................................................................................................................... 3-28
Managing Synonyms............................................................................................................................ 3-28
Creating a Synonym ....................................................................................................................... 3-28
Displaying a Synonym ................................................................................................................... 3-29
Dropping a Synonym ..................................................................................................................... 3-29

4 Using SQL
Overview of SQL...................................................................................................................................... 4-1
Features of SQL .................................................................................................................................. 4-2
Types of SQL Statements .................................................................................................................. 4-2
Executing SQL Statements ..................................................................................................................... 4-2
Running SQL Statements in the SQL Commands Page ............................................................... 4-2
Running SQL Statements in the Script Editor Page ...................................................................... 4-3
Retrieving Data With Queries ............................................................................................................... 4-4
Displaying Data Using the SELECT Statement ............................................................................. 4-4
Using Character Literals in SQL Statements .................................................................................. 4-5
Quoting Character Literals ........................................................................................................ 4-5
Using a Column Alias to Change Headings When Selecting Data ............................................ 4-5
Restricting Data Using the WHERE Clause ................................................................................... 4-6
Sorting Data Using the ORDER BY Clause .................................................................................... 4-7
Displaying Data From Multiple Tables........................................................................................... 4-7
Manipulating Data With SQL Statements .......................................................................................... 4-8
Adding Data With the INSERT Statement ..................................................................................... 4-8
Updating Data With the UPDATE Statement................................................................................ 4-9
Deleting Data With the DELETE Statement................................................................................... 4-9
Transaction Control Statements.......................................................................................................... 4-10
Committing Transaction Changes ................................................................................................ 4-10
Rolling Back a Transaction............................................................................................................. 4-10

Beta Draft v
Using Pseudocolumns, Sequences, and SQL Functions................................................................ 4-11
Using Pseudocolumns With SQL.................................................................................................. 4-11
Using Sequences.............................................................................................................................. 4-11
Using Character Functions ............................................................................................................ 4-12
Using Arithmetic Operators .......................................................................................................... 4-13
Using Numeric Functions .............................................................................................................. 4-13
Using Date Functions ..................................................................................................................... 4-13
Using Aggregate Functions ........................................................................................................... 4-15
Using SQL Data Definition Language Statements......................................................................... 4-15
Creating a Table With SQL ............................................................................................................ 4-16
Creating and Modifying an Index With SQL.............................................................................. 4-17
Creating and Modifying a Constraint With SQL ....................................................................... 4-17
Altering a Table With SQL............................................................................................................. 4-17
Dropping a Table With SQL .......................................................................................................... 4-18
Creating and Dropping a Sequence.............................................................................................. 4-18
Creating and Dropping a Synonym ............................................................................................. 4-18

5 Using PL/SQL
Overview of PL/SQL................................................................................................................................ 5-1
Entering and Executing PL/SQL Code ................................................................................................. 5-2
Running PL/SQL Code in the SQL Commands Page .................................................................. 5-2
Running PL/SQL Code in Script Editor ......................................................................................... 5-3
Utilizing the Main Features of PL/SQL ............................................................................................... 5-5
Using PL/SQL Block Structure ........................................................................................................ 5-5
Using Comments................................................................................................................................ 5-6
Declaring Variables and Constants ................................................................................................. 5-7
Using Identifiers in PL/SQL ............................................................................................................ 5-8
Assigning Values to a Variable With the Assignment Operator ................................................ 5-8
Using Literals...................................................................................................................................... 5-9
Declaring and Assigning Variables With DEFAULT or NOT NULL ..................................... 5-11
Assigning Values to a Variable With SELECT INTO ................................................................ 5-11
Inputting and Outputting Data with PL/SQL............................................................................ 5-12
Using %ROWTYPE and %TYPE Attributes to Declare Datatypes .......................................... 5-12
Using the %ROWTYPE Attribute to Declare Variables ..................................................... 5-12
Using the %TYPE Attribute to Declare Variables ............................................................... 5-13
Using PL/SQL Control Structures................................................................................................ 5-14
Conditional Control With IF-THEN...................................................................................... 5-14
Conditional Control With the CASE Statement .................................................................. 5-14
Iterative Control With LOOPs ............................................................................................... 5-16
Sequential Control With GOTO............................................................................................. 5-17
Using Local PL/SQL Subprograms in PL/SQL Blocks............................................................. 5-17
Working With PL/SQL Data Structures...................................................................................... 5-19
Using Cursors ........................................................................................................................... 5-19
Using Collections ..................................................................................................................... 5-20
Using Records........................................................................................................................... 5-21
Processing Queries with PL/SQL................................................................................................. 5-21
Using Dynamic SQL in PL/SQL................................................................................................... 5-22

vi Beta Draft
Using Bind Variables ...................................................................................................................... 5-23
Handling PL/SQL Errors ...................................................................................................................... 5-23
Summary of Predefined PL/SQL Exceptions ............................................................................. 5-24
Using the Exception Handler ........................................................................................................ 5-25
Declaring PL/SQL Exceptions ...................................................................................................... 5-26
Scope Rules for PL/SQL Exceptions ............................................................................................ 5-26
Continuing After an Exception is Raised .................................................................................... 5-27

6 Using Subprograms and Packages


Overview of Packages and Subprograms............................................................................................ 6-1
Stored Subprograms .......................................................................................................................... 6-2
Packages .............................................................................................................................................. 6-2
Managing Subprograms.......................................................................................................................... 6-3
Creating Subprograms With Object Browser................................................................................. 6-4
Viewing Subprograms With Object Browser................................................................................. 6-5
Creating Subprograms in the Script Editor Page .......................................................................... 6-6
Creating Stored Procedures With SQL CREATE PROCEDURE................................................. 6-7
Creating Stored Functions With SQL CREATE FUNCTION ...................................................... 6-8
Calling Stored Subprograms ............................................................................................................ 6-8
Editing Subprograms...................................................................................................................... 6-10
Dropping a Subprogram ................................................................................................................ 6-10
Managing Packages............................................................................................................................... 6-11
Writing Packages With PL/SQL Code......................................................................................... 6-11
Guidelines for Writing Packages ........................................................................................... 6-11
Creating Packages With Object Browser ..................................................................................... 6-12
Viewing Packages With Object Browser...................................................................................... 6-13
Creating Packages in the Script Editor Page ............................................................................... 6-13
Creating Packages With SQL CREATE PACKAGE................................................................... 6-14
Editing Packages ............................................................................................................................. 6-15
Dropping Packages ......................................................................................................................... 6-16
Calling Subprograms in Packages ................................................................................................ 6-16
Accessing Variables in Packages................................................................................................... 6-17
Oracle Product-Specific Packages ...................................................................................................... 6-17

7 Using Triggers
Overview of Triggers ............................................................................................................................... 7-1
Types of Triggers ............................................................................................................................... 7-2
Naming Triggers ............................................................................................................................... 7-2
When Is the Trigger Fired? .............................................................................................................. 7-2
Controlling When a Trigger Is Fired .............................................................................................. 7-2
Firing Triggers With the BEORE and AFTER Options.......................................................... 7-3
Firing Triggers With the FOR EACH ROW Option ............................................................. 7-3
Firing Triggers Based on Conditions (WHEN Clause) ......................................................... 7-3
Accessing Column Values in Row Triggers .................................................................................. 7-4
Detecting the DML Operation That Fired a Trigger ..................................................................... 7-4
Enabled and Disabled Trigger Modes............................................................................................. 7-5

Beta Draft vii


Error Conditions and Exceptions in the Trigger Body ................................................................ 7-5
Designing Triggers................................................................................................................................... 7-5
Guidelines For Triggers..................................................................................................................... 7-5
Restrictions on Creating Triggers ................................................................................................... 7-6
Privileges Needed to Work with Triggers ..................................................................................... 7-6
Managing Triggers in the Database...................................................................................................... 7-7
Creating a Trigger With the Script Editor ...................................................................................... 7-7
Creating a Trigger With Object Browser ........................................................................................ 7-8
Viewing a Trigger With Object Browser......................................................................................... 7-9
Creating a Trigger With the AFTER and FOR EACH ROW Option ....................................... 7-10
Creating a Trigger With the BEFORE Option and WHEN Clause .......................................... 7-11
Creating a Trigger With an Exception Handler.......................................................................... 7-11
Creating a Trigger That Fires Once For Each Update................................................................ 7-12
Creating LOGON and LOGOFF Triggers ................................................................................... 7-13
Modifying Triggers ........................................................................................................................ 7-14
Enabling Triggers ........................................................................................................................... 7-14
Disabling Triggers .......................................................................................................................... 7-14
Compiling Triggers ........................................................................................................................ 7-15
Dependencies for Triggers ..................................................................................................... 7-15
Recompiling Triggers ............................................................................................................. 7-16

8 Working in a Global Environment


Overview of Globalization Support..................................................................................................... 8-1
Globalization Support Features ....................................................................................................... 8-2
Running the Examples ...................................................................................................................... 8-3
Setting up the Globalization Support Environment......................................................................... 8-3
Setting NLS Parameters..................................................................................................................... 8-4
Choosing a Locale with the NLS_LANG Environment Variable ............................................... 8-5
Language and Territory Parameters ............................................................................................... 8-5
NLS_LANGUAGE ...................................................................................................................... 8-6
NLS_TERRITORY ....................................................................................................................... 8-7
Date and Time Parameters................................................................................................................ 8-8
Date Formats................................................................................................................................ 8-8
Time Formats ............................................................................................................................ 8-10
Calendar Definitions....................................................................................................................... 8-11
Calendar Formats..................................................................................................................... 8-11
NLS_CALENDAR.................................................................................................................... 8-12
Numeric and List Parameters........................................................................................................ 8-12
Numeric Formats ..................................................................................................................... 8-12
NLS_NUMERIC_CHARACTERS.......................................................................................... 8-13
Monetary Parameters ..................................................................................................................... 8-13
Currency Formats .................................................................................................................... 8-14
NLS_CURRENCY .................................................................................................................... 8-14
NLS_ISO_CURRENCY ........................................................................................................... 8-14
NLS_DUAL_CURRENCY ...................................................................................................... 8-15
Linguistic Sorting and Searching .................................................................................................. 8-15
NLS_SORT ................................................................................................................................ 8-15

viii Beta Draft


NLS_COMP .............................................................................................................................. 8-17
Case and Accent Insensitive Searching ................................................................................ 8-18
Length Semantics ............................................................................................................................ 8-18
NLS_LENGTH_SEMANTICS ................................................................................................ 8-19
SQL and PL/SQL Programming with Unicode................................................................................ 8-19
Overview of Unicode...................................................................................................................... 8-20
SQL NCHAR Datatypes................................................................................................................. 8-20
The NCHAR Datatype ............................................................................................................ 8-20
The NVARCHAR2 Datatype.................................................................................................. 8-21
Unicode String Literals................................................................................................................... 8-21
Locale-Dependent SQL Functions with Optional NLS Parameters............................................ 8-22
Default Values for NLS Parameters in SQL Functions.............................................................. 8-23
Specifying NLS Parameters in SQL Functions............................................................................ 8-23
Unacceptable NLS Parameters in SQL Functions ...................................................................... 8-24

A SQL*Plus
Overview of SQL*Plus ........................................................................................................................... A-1
Using SQL*Plus ....................................................................................................................................... A-1
Starting and Exiting SQL*Plus ........................................................................................................ A-2
Displaying Help With SQL*Plus..................................................................................................... A-2
Entering and Executing SQL Statements and Commands.......................................................... A-2
SQL*Plus DESCRIBE Command .................................................................................................... A-3
SQL*Plus SET Commands ............................................................................................................... A-3
Running Scripts From SQL*Plus..................................................................................................... A-3
Spooling From SQL*Plus ................................................................................................................. A-4
Using Variables With SQL*Plus...................................................................................................... A-4
Prompting for a Variable .......................................................................................................... A-4
Defining a Variable Value for a Query ................................................................................... A-4

Index

Beta Draft ix
x Beta Draft
Preface

This guide explains basic concepts behind development with Oracle Database Express
Edition and provides examples on how to use basic language features of SQL and
PL/SQL. This guide is intended to be a very basic introduction to development and
references are provided in the text to detailed information about subjects.
This section contains the following topics:
■ Audience on page xi
■ Documentation Accessibility on page xi
■ Structure on page xii
■ Related Documentation on page xiii
■ Conventions on page xiii

Note: Oracle Database Express Edition is a free Oracle database that


is available for download from the Oracle Database Express Edition
Web site at:
http://www.oracle.com/express
Before downloading and installing Oracle Database Express Edition,
read the release and the installation guide for Linux or Windows that
are available on the Oracle Database Express Edition Web site. Before
developing applications with Oracle Database Express Edition, read
the getting started section of the Oracle Database Express Edition 2 Day
DBA Guide.

Audience
This manual is intended for beginning developers using the Oracle Database Express
Edition product.

Documentation Accessibility
Our goal is to make Oracle products, services, and supporting documentation
accessible, with good usability, to the disabled community. To that end, our
documentation includes features that make information available to users of assistive
technology. This documentation is available in HTML format, and contains markup to
facilitate access by the disabled community. Accessibility standards will continue to
evolve over time, and Oracle is actively engaged with other market-leading
technology vendors to address technical obstacles so that our documentation can be

Beta Draft xi
accessible to all of our customers. For more information, visit the Oracle Accessibility
Program Web site at
http://www.oracle.com/accessibility/

Accessibility of Code Examples in Documentation


Screen readers may not always correctly read the code examples in this document. The
conventions for writing code require that closing braces should appear on an
otherwise empty line; however, some screen readers may not always read a line of text
that consists solely of a bracket or brace.

Accessibility of Links to External Web Sites in Documentation


This documentation may contain links to Web sites of other companies or
organizations that Oracle does not own or control. Oracle neither evaluates nor makes
any representations regarding the accessibility of these Web sites.

Structure
This guide contains the following chapters:

Chapter 1, "Overview of Development"


This chapter provides an overview of the development environments that you can use
with Oracle Database Express Edition.

Chapter 2, "Using Datatypes"


This chapter discusses the Oracle Database Express Edition datatypes.

Chapter 4, "Using SQL"


This chapter explains how to use SQL with Oracle Database Express Edition.

Chapter 3, "Managing Database Objects"


This chapter how to manage database objects that you are using in your applications.

Chapter 5, "Using PL/SQL"


This chapter discusses how to use PL/SQL with Oracle Database Express Edition.

Chapter 6, "Using Subprograms and Packages"


This chapter discusses how to develop and use packages and subprograms with
PL/SQL.

Chapter 7, "Using Triggers"


This chapter discusses how to create and use triggers.

Chapter 8, "Working in a Global Environment"


This chapter discusses how to develop in a global environment.

Appendix A, "SQL*Plus"
This appendix provides an overview of SQL*Plus.

xii Beta Draft


Related Documentation
For more information, see the following manuals in the Oracle Database 10g Release 2
documentation set:
■ Oracle Database Express Edition HTML DB User’s Guide
■ Oracle Database Express Edition HTML DB 2 Day Developer
■ Oracle Database Express Edition 2 Day DBA Guide
■ Oracle Database Express Edition 2 Day Plus PHP Developer Guide
■ Oracle Database Express Edition 2 Day Plus Java Developer Guide
■ Oracle Database Express Edition 2 Day Plus .NET Developer Guide
■ Oracle Database Express Edition ISV Embedding Guide
■ Oracle Database Application Developer's Guide - Fundamentals
■ Oracle Database Concepts
■ Oracle Database SQL Reference
■ Oracle Database PL/SQL User's Guide and Reference
■ Oracle Database PL/SQL Packages and Types Reference
■ Oracle Database Globalization Support Guide
Many of the examples in this book use the HR sample schema, which is installed by
default with Oracle Database Express Edition. Refer to Oracle Database Sample Schemas
for more information on the sample schemas.
Printed documentation is available for sale in the Oracle Store at
http://oraclestore.oracle.com/
To download free release notes, installation documentation, white papers, or other
collateral, please visit the Oracle Technology Network (OTN). You must register online
before using OTN; registration is free and can be done at
http://www.oracle.com/technology/membership/
If you already have a username and password for OTN, then you can go directly to the
documentation section of the OTN Web site at
http://www.oracle.com/technology/documentation/
For information on additional books
http://www.oracle.com/technology/books/10g_books.html

Conventions
The following text conventions are used in this document:

Convention Meaning
boldface Boldface type indicates graphical user interface elements associated
with an action, or terms defined in text or the glossary.
italic Italic type indicates book titles, emphasis, or placeholder variables for
which you supply particular values.
monospace Monospace type indicates commands within a paragraph, URLs, code
in examples, text that appears on the screen, or text that you enter.

Beta Draft xiii


xiv Beta Draft
1
Overview of Development

This chapter provides an overview of the developing applications with Oracle


Database Express Edition.
This section contains the following topics:
■ Overview of Oracle Express Server Application Development on page 1-1
■ Other Development Environments on page 1-5

See Also:
■ Oracle Database Application Developer's Guide - Fundamentals for a
complete overview of application development with Oracle.

Note: Oracle Database Express Edition is a free Oracle database that


is available for download from the Oracle Database Express
EditionWeb site at:
http://www.oracle.com/express
Before downloading and installing Oracle Database Express Edition,
read the release note and the installation guide for Linux or Windows
that are available on the Oracle Database Express Edition Web site.
Before developing applications with Oracle Database Express Edition,
read getting started section of the Oracle Database Express Edition 2 Day
DBA Guide.

Overview of Oracle Express Server Application Development


This section provides an introduction to the Oracle Database Express Edition
development environment.
This section contains the following topics:
■ Oracle Database Express Edition on page 1-2
■ SQL on page 1-2
■ PL/SQL on page 1-2
■ Datatypes on page 1-3
■ Database Objects on page 1-3
■ Basic Application Development Concepts on page 1-3

Beta Draft Overview of Development 1-1


Overview of Oracle Express Server Application Development

■ Development Tools on page 1-4

Oracle Database Express Edition


The Oracle Database Express Edition is a relational database which stores and
retrieves collections of related information. A database, also called a database server, is
the key to solving the problems of information management. In a relational database,
collections of related information are organized into structures called tables. Each table
contains rows (records) that are comprised of columns (fields). The tables are stored in
the database in structures called schemas, which are logical structures of data where
database users store their tables.
The HR sample schema that is included with Oracle Database XE is an example of a
schema with related tables. In the HR sample schema, there are tables to store
information about employees and departments. The tables contain common columns
that allow data from one table to be related to another. For an employee in the
employees table, the department name in the departments can be retrieved based on
the department Id column that is present in both tables.

See Also:
■ Oracle Database Sample Schemas for a description of the HR sample
schema
■ Oracle Database Concepts for an introduction to Oracle databases

SQL
SQL is a nonprocedural programming language that enables you to access a relational
database. Using SQL statements, you can create objects (such as tables), maintain
objects, query tables, modify tables, and perform administrative tasks. All you need to
do is describe in SQL what you want done, and the SQL language compiler
automatically generates a procedure to navigate the database and perform the desired
task. See Chapter 4, "Using SQL".

See Also: Oracle Database SQL Reference for information on SQL.

PL/SQL
PL/SQL is Oracle's procedural extension to SQL, the standard database access
language. It is an advanced programming language, which like SQL, has a built-in
treatment of the relational database domain. Applications written in any of the Oracle
programmatic interfaces can call PL/SQL stored procedures.
In PL/SQL, you can manipulate data with SQL statements and control program flow
with procedural constructs such as loops. You can also do the following:
■ Declare constants and variables
■ Define procedures and functions
■ Use collections and object types
■ Trap runtime errors
■ Create packages, subprograms, and triggers
For information on using PL/SQL, see Chapter 5, "Using PL/SQL".

1-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Overview of Oracle Express Server Application Development

See Also:
■ Oracle Database PL/SQL User's Guide and Reference
■ Oracle Database PL/SQL Packages and Types Reference
■ http://www.oracle.com/technology/tech/pl_
sql/index.html

Datatypes
A datatype associates a fixed set of properties with the values that can be used in a
column of a table or in an argument of a procedure or function. Each column value
and constant in a SQL statement has a datatype, which is associated with a specific
storage format, constraints, and a valid range of values. When you create a table, you
must specify a datatype for each of its columns. See Chapter 2, "Using Datatypes".

Database Objects
You need to create tables, indexes, and possibly other database objects in a schema
before you start developing your application. See Chapter 3, "Managing Database
Objects".

Basic Application Development Concepts


This section discusses the basic concepts in application development with Oracle
Database Express Edition.

User Interface
The interface that your application displays to end users depends on the technology
behind the application as well as the needs of the users themselves.

Client/Server Model
In a traditional client/server program, the code of your application runs on a machine
other than the database server. Database calls are transmitted from this client machine
to the database server. Data is transmitted from the client to the server for insert and
update operations and returned from the server to the client for query operations. The
data is processed on the client machine. Client/server programs are typically written
by using an application programming interface, whereas SQL statements are
embedded within the code of another language such as C, C++, Java, JDBC, .NET,
PHP, or XML.

Server-Side Coding
You can develop application logic that resides entirely inside the database by using
triggers that are executed automatically when changes occur in the database or stored
procedures that are called explicitly. Off-loading the work from your application lets
you reuse code that performs verification and cleanup and control database operations
from a variety of clients. For example, by making stored procedures callable through a
Web server, you can construct a Web-based user interface that performs the same
functions as a client/server application.

Two-Tier Versus Three-Tier Models


Client/server computing is often referred to as a two-tier model: your application
communicates directly with the database server. In the three-tier model, a separate
application server processes the requests. The application server might be a basic Web

Beta Draft Overview of Development 1-3


Overview of Oracle Express Server Application Development

server, or might perform advanced functions like caching and load-balancing.


Increasing the processing power of this middle tier lets you lessen the resources
needed by client systems.

Development Tools
There are various tools that you can use to develop with SQL and PL/SQL, and to
manage database objects. In this guide, the Oracle Database XE Graphical User
Interface is primarily featured for managing database objects, but you could also use
Oracle SQL*Plus to enter SQL statements and PL/SQL code.

Logging in to the Database Home Page


To log in to the Database Home Page:
1. Log in to the Database Home Page. The page can be accessed in your Web browser
at http://127.0.0.1:8080/htmldb when the Oracle Database Express
Edition is running on your computer. To view the database objects or run the
examples discussed in this guide, log in as user HR with your password for the HR
user account.

Note: If the HR user account is locked, you need to log in as a user


with administrator privileges and unlock the account. See "Locking
and Unlocking User Accounts" in Oracle Database Express Edition 2 Day
DBA Guide.

2. On the Database Home Page, click the icon for the specific tool that you want to
use. There are icons for Application Builder, Object Browser, SQL, Utilities, and
Administration.

Figure 1–1 XE Login Page

1-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Other Development Environments

Figure 1–2 Database Home Page

See Also:
■ Oracle Database Express Edition 2 Day DBA Guide for information
on getting started with Oracle Database Express Edition
■ Oracle Database Express Edition HTML DB User’s Guide for
information on quick start with the Oracle Database XE Graphical
User Interface

Other Development Environments


This section list other development languages that can be used with Oracle Database
Express Edition. These environments are discussed in other guides.
This section contains the following topics:
■ Oracle Call Interface (OCI) and Oracle C++ Call Interface (OCCI) on page 1-5
■ Open Database Connectivity (ODBC) on page 1-6
■ Oracle Data Provider for .NET (ODP.NET) on page 1-6
■ Oracle Database Extensions for .NET on page 1-7
■ Oracle Developer Tools for Visual Studio .NET on page 1-7
■ Oracle HTML DB Developer on page 1-8
■ Oracle JDBC on page 1-8
■ Oracle Provider for OLE DB on page 1-8
■ PHP on page 1-8

Oracle Call Interface (OCI) and Oracle C++ Call Interface (OCCI)
The Oracle Call Interface (OCI) and Oracle C++ Call Interface (OCCI) are the native C
and C++ APIs, respectively, for accessing Oracle Database Express Edition. OCI and
OCCI are the best options for building high performance, thread-safe applications that
are robust, efficient, and secure.

Beta Draft Overview of Development 1-5


Other Development Environments

OCI is the most feature-complete API for Oracle, giving developers access to all
aspects of Oracle Database XE. Developers using OCI always have room to expand
their application functionality.
For C++ developers looking for a more object oriented API, OCCI is the appropriate
simple yet powerful answer. OCCI offers easy development and rapid prototyping of
Oracle applications.
Example C and C++ programs are available in the /rdbms/demo/ subdirectory under
the Oracle Database XE home directory.

See Also:
■ Oracle Call Interface Programmer's Guide for more information on
OCI
■ Oracle C++ Call Interface Programmer's Guide for more information
on OCCI

Open Database Connectivity (ODBC)


Open Database Connectivity (ODBC) is a database access API that enables you to
connect to a database and then prepare and run SQL statements against Oracle
Database XE. In conjunction with an ODBC driver, an application can access any data
source including data stored in spreadsheets, such as an Excel spreadsheet.
■ Oracle Database XE provides an ODBC driver for both Windows and Linux (32
bit).
■ Oracle ODBC Driver conforms to ODBC 3.51 specifications. It supports all core
APIs and a set of Level 1 and Level 2 functions.
■ The Driver Manager component is supplied by Microsoft for Windows. For Unix
platforms, the Oracle Database XE driver has been tested using the latest Driver
Manager available from http://www.unixODBC.org.
ODBC demo files and the makefile are located in the /rdbms/demo/ subdirectory
under the Oracle Database XE home directory.

See Also:
■ Oracle Services for Microsoft Transaction Server Developer's Guide for
information using the Oracle ODBC driver on Windows
■ Oracle Database Administrator's Reference 10g Release 2 (10.2) for
UNIX-Based Operating Systems for information using the Oracle
ODBC driver on Linux

Oracle Data Provider for .NET (ODP.NET)


Oracle Data Provider for .NET provides data access for client applications from within
Oracle database. ODP.NET data access is fast and includes access to Oracle advanced
features, such as Real Application Clusters (RAC) and XML DB.
Oracle Data Provider for .NET (ODP.NET) is an implementation of a .NET data
provider for Oracle Database, using and inheriting from classes and interfaces
available in the Microsoft .NET Framework Class Library.
Following the .NET Framework, ODP.NET uses the ADO.NET model, which enables
native providers to expose provider-specific features and datatypes. This is similar to
Oracle Provider for OLE DB, where ADO (ActiveX Data Objects) provides an

1-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Other Development Environments

automation layer that exposes an easy programming model. ADO.NET provides a


similar programming model, but without the automation layer, for better performance.
Oracle Data Provider for .NET uses Oracle native APIs to offer fast and reliable access
to Oracle data and features from any .NET application.

See Also:
■ Oracle Database Express Edition 2 Day Plus .NET Developer Guide

Oracle Database Extensions for .NET


Oracle Database Extensions for .NET provides the following:
■ A Common Language Runtime (CLR) host for Oracle Database
■ Data access through Oracle Data Provider for .NET classes
■ Oracle Deployment Wizard for Visual Studio .NET
The Oracle Database hosts the Microsoft Common Language Runtime (CLR) in an
external process, outside of the Oracle database process, but on the same computer.
The integration of Oracle Database with the Microsoft Common Language Runtime
(CLR) enables applications to run .NET stored procedures or functions on Oracle
Database, on Microsoft Windows 2003, Windows 2000, and Windows XP.
Application developers can write stored procedures and functions using any .NET
compliant language, such as C# and VB.NET, and use these .NET stored procedures in
the database, in the same manner as other PL/SQL or Java stored procedures. .NET
stored procedures can be used from PL/SQL packages, procedures, functions, and
triggers.
Application developers build .NET procedures or functions into a .NET assembly,
typically using Microsoft Visual Studio .NET. Oracle Data Provider for .NET is used in
.NET stored procedures and functions for data access. After building .NET procedures
and functions into a .NET assembly, developers deploy them in Oracle database, using
the Oracle Deployment Wizard for .NET, a component of the Oracle Developer Tools
for Visual Studio .NET.

See Also:
■ Oracle Database Express Edition 2 Day Plus .NET Developer Guide

Oracle Developer Tools for Visual Studio .NET


Oracle Developer Tools is an add-in to Visual Studio .NET that provides graphical user
interface (GUI) access to Oracle functionality. It provides improved developer
productivity and ease of use.
Oracle Developer Tools include the Oracle Explorer to browse your Oracle schema,
designers and wizards to create and alter schema objects, and the ability to drag and
drop schema objects onto your .NET form to automatically generate code. There is also
a PL/SQL editor with integrated context sensitive online help. With the Oracle Data
Window, users can perform routine database tasks like inserting and updating Oracle
data or testing stored procedures in the Visual Studio environment. For maximum
flexibility, there is also a SQL Query Window for executing any SQL statement or SQL
script.

See Also:
■ Oracle Database Express Edition 2 Day Plus .NET Developer Guide

Beta Draft Overview of Development 1-7


Other Development Environments

Oracle HTML DB Developer


HTML DB Developer is a graphical application builder that assembles an HTML
interface (or application) on top of database objects such as tables and procedures.
Each application is a collection of pages linked together using tabs, buttons, or
hypertext links.

See Also:
■ Oracle Database Express Edition HTML DB 2 Day Developer

Oracle JDBC
JDBC (Java Database Connectivity) is an API (Applications Programming Interface)
that enables Java to send SQL statements to an object-relational database such as
Oracle Database. For more details on the JDBC API see:
http://java.sun.com/products/jdbc
Oracle Database 10g JDBC brings major capabilities, such as complete support for
JDBC 3.0 standard, complete support for JDBC RowSet (JSR-114), Advanced
Connection Caching (Non-XA and XA Connections), exposing SQL and PL/SQL data
types to Java, and faster SQL data access. For information about the new JDBC
features, see:
http://www.oracle.com/technology/tech/java/sqlj_jdbc/pdf/twp_
appdev_java_whats_new_4_java_jdbc_web_services.pdf
For more details on the Oracle JDBC Drivers, see:
http://www.oracle.com/technology/tech/java/sqlj_jdbc/index.html

See Also:
■ Oracle Database Express Edition 2 Day Plus Java Developer Guide

Oracle Provider for OLE DB


OLE DB is an open standard data access methodology which utilizes a set of
Component Object Model (COM) interfaces for accessing and manipulating different
types of data. These interfaces are available from various database providers.
Oracle Provider for OLE DB (OraOLEDB) is an OLE DB data provider that offers high
performance and efficient access to Oracle data by OLE DB consumers.
With the advent of the .NET framework, support has been provided for using the
OLEDB.NET Data Provider with OraOLEDB. With the proper connection attribute
setting, an OLEDB.NET Data Provider can utilize OraOLEDB to access Oracle
Database.

See Also:
■ Oracle Provider for OLE DB Developer's Guide

PHP
PHP is a recursive acronym for PHP Hypertext Preprocessor. It is a widely-used
open-source, interpretive, HTML-centric, server-side scripting language. PHP is
especially suited for Web development and can be embedded into HTML pages. PHP
is comparable to languages such as JSP (Java Server Pages) and Oracle's PSP (PL/SQL
Server Pages).

1-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Other Development Environments

See Also:
■ Oracle Database Express Edition 2 Day Plus PHP Developer Guide
■ PHP Development Center:
http://www.oracle.com/technology/tech/php/index.html

Beta Draft Overview of Development 1-9


Other Development Environments

1-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
2
Using Datatypes

The chapter discusses the datatypes used with Oracle Express.


This section contains the following topics:
■ Overview of Datatypes on page 2-1
■ Storing Character Data on page 2-3
■ Storing Numeric Data on page 2-4
■ Storing Datetime Data on page 2-7

See Also:
■ Oracle Database SQL Reference for complete reference information
on the SQL datatypes
■ Oracle Database Concepts to learn about Oracle built-in datatypes

Overview of Datatypes
A datatype associates a fixed set of properties with the values that can be used in a
column of a table or in an argument of a procedure or function. These properties cause
Oracle Database Express Edition to treat values of one datatype differently from values
of another datatype. For example, Oracle Database Express Edition can use the
addition operator on values of NUMBER datatype, but not with values of some other
datatypes. The datatypes supported by Oracle Database Express Edition include
characters, numbers, dates and times (known as datetime datatypes), and row
addresses (ROWIDs).
To view the datatypes contained in a database table, such as the employees table, you
can use Object Browser or the SQL*Plus DESCRIBE command entered in the SQL
Commands page or at the SQL*PLus command line. For information on the SQL*Plus
DESCRIBE command, see "SQL*Plus DESCRIBE Command" on page A-3.
This section includes the following topics:
■ Viewing Datatypes With Object Browser on page 2-1
■ Viewing Datatypes With SQL Commands on page 2-2

Viewing Datatypes With Object Browser


To view the datatypes contained in a database table, you can use Object Browser.

Beta Draft Using Datatypes 2-1


Overview of Datatypes

1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. Note that you should log in as the HR user to use the examples in this
guide.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. Select Tables in the list of object types, then click the table, such as employees,
you want to view.
The table information displays.

Figure 2–1 Viewing Columns With Datatypes in Object Browser

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using Object Browser

Viewing Datatypes With SQL Commands


To view the datatypes contained in a database object, such as the employees table,
you can use the DESCRIBE command in the SQL Commands page.
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. Note that you should log in as the HR user to use the examples in this
guide.
2. Click the SQL icon on the Database Home Page.
The SQL home page appears.
3. On the SQL home page, click the SQL Commands icon to display the SQL
Commands page.

2-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Storing Character Data

4. In the SQL Commands page, enter DESCRIBE employees and click the Run
button to execute the statement.
The datatype is listed for each column of the table.

Figure 2–2 View Columns With Datatypes Using DESCRIBE in the SQL Commands Page

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Commands

Storing Character Data


This section contains the following topics:
■ What are the Character Datatypes? on page 2-3
■ Choosing Between the Character Datatypes on page 2-4

What are the Character Datatypes?


You can use the following SQL datatypes to store alphanumeric data:
■ VARCHAR2 and NVARCHAR2 datatypes store variable-length character literals.
■ NCHAR and NVARCHAR2 datatypes store variable-length Unicode character data
only.
■ CHAR and NCHAR datatypes store fixed-length character literals.

Beta Draft Using Datatypes 2-3


Storing Numeric Data

See Also:
■ Oracle Database SQL Reference for information on datatypes
■ Oracle Database Globalization Support Guide for information on
globalization support

Choosing Between the Character Datatypes


When deciding which datatype to use for a column that will store alphanumeric data
in a table, consider the following points of distinction:
■ Space usage
To store data more efficiently, use the VARCHAR2 datatype. The CHAR datatype
blank-pads and stores trailing blanks up to a fixed column length for all column
values, whereas the VARCHAR2 datatype does not add extra blanks.
■ Comparison semantics
Use the CHAR datatype when you require ANSI compatibility in comparison
semantics (when trailing blanks are not important in string comparisons). Use the
VARCHAR2 when trailing blanks are important in string comparisons.
■ Future compatibility
The CHAR and VARCHAR2 datatypes are fully supported.

See Also: Oracle Database SQL Reference for more information on


comparison semantics for these datatypes

Storing Numeric Data


This section contains the following topics:
■ What Are the Numeric Datatypes? on page 2-4
■ Using NUMBER Datatypes on page 2-5
■ Using Floating-Point Number Formats on page 2-6

What Are the Numeric Datatypes?


The following SQL datatypes store numeric data:
■ NUMBER
■ BINARY_FLOAT
■ BINARY_DOUBLE
Use the NUMBER datatype to store integers and real numbers in a fixed-point or
floating-point format. Numbers using this datatype are guaranteed to be portable
among different Oracle Database XE platforms. For nearly all cases where you need to
store numeric data, you would use the NUMBER datatype.
Oracle Database XE provides the numeric BINARY_FLOAT and BINARY_DOUBLE
datatypes exclusively for floating-point numbers. They support all of the basic
functionality provided by the NUMBER datatype. However, while NUMBER uses
decimal precision, BINARY_FLOAT and BINARY_DOUBLE use binary precision. This
enables faster arithmetic calculations and usually reduces storage requirements.

2-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Storing Numeric Data

See Also:
■ Oracle Database Concepts for information about the internal format
for the NUMBER datatype
■ Oracle Database SQL Reference for more information about the
BINARY_FLOAT and BINARY_DOUBLE datatypes formats

Using NUMBER Datatypes


The NUMBER datatype stores zero as well as positive and negative fixed numbers with
absolute values from 1.0 x 10-130 to (but not including) 1.0 x 10126. If you specify an
arithmetic expression whose value has an absolute value greater than or equal to 1.0 x
10126, then Oracle returns an error. Each NUMBER value requires from 1 to 22 bytes.
Specify a fixed-point number using the following form:
NUMBER(p,s)
where:
■ p is the precision, or the total number of significant decimal digits, where the most
significant digit is the left-most nonzero digit, and the least significant digit is the
right-most known digit. Oracle guarantees the portability of numbers with
precision of up to 20 base-100 digits, which is equivalent to 39 or 40 decimal digits
depending on the position of the decimal point.
■ s is the scale, or the number of digits from the decimal point to the least
significant digit. The scale can range from -84 to 127.
– Positive scale is the number of significant digits to the right of the decimal
point to and including the least significant digit.
– Negative scale is the number of significant digits to the left of the decimal
point, to but not including the least significant digit. For negative scale the
least significant digit is on the left side of the decimal point, because the actual
data is rounded to the specified number of places to the left of the decimal
point. 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. When
scale is greater than precision, the precision specifies the maximum number of
significant digits to the right of the decimal point. For example, a column defined as
NUMBER(4,5) requires a zero for the first digit after the decimal point and rounds all
values past the fifth digit after the decimal point.
It is good practice to specify the scale and precision of a fixed-point number column
for extra integrity checking on input. Specifying scale and precision does not force all
values to a fixed length. If a value exceeds the precision, then Oracle returns an error. If
a value exceeds the scale, then Oracle 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 to
NUMBER(p,0).
Specify a floating-point number using the following form:
NUMBER
The absence of precision and scale designators specifies the maximum range and
precision for an Oracle number.

Beta Draft Using Datatypes 2-5


Storing Numeric Data

Table 2–1 show how Oracle stores data using different values for precision and scale.

Table 2–1 Storage of Scale and Precision


Actual Data Specified As Stored As
123.89 NUMBER 123.89
123.89 NUMBER(3) 124
123.89 NUMBER(6,2) 123.89
123.89 NUMBER(6,1) 123.9
123.89 NUMBER(3) exceeds precision
123.89 NUMBER(4,2) exceeds precision
123.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) .0000012
1.2e-4 NUMBER(2,5) 0.00012
1.2e-5 NUMBER(2,5) 0.00001

Using Floating-Point Number Formats


The BINARY_FLOAT and BINARY_DOUBLE datatypes store floating-point data in the
32-bit IEEE 754 format and the double precision 64-bit IEEE 754 format respectively.
Compared to the Oracle NUMBER datatype, arithmetic operations on floating-point
data are usually faster for BINARY_FLOAT and BINARY_DOUBLE. Also, high-precision
values require less space when stored as BINARY_FLOAT and BINARY_DOUBLE.
The floating-point number system is a common way of representing and manipulating
numeric values in computer systems. The value 4.32682E-21F is an example of a
BINARY_FLOAT datatype.
Floating-point numbers can have a decimal point anywhere from the first to the last
digit or can have no decimal point at all. An exponent may optionally be used
following the number to increase the range (for example, 1.777 e-20). A scale value is
not applicable to floating-point numbers, because the number of digits that can appear
after the decimal point is not restricted.
Binary floating-point numbers differ from NUMBER in the way the values are stored
internally by Oracle Database. Values are stored using decimal precision for NUMBER.
All literals that are within the range and precision supported by NUMBER are stored
exactly as NUMBER. Literals are stored exactly because literals are expressed using
decimal precision (the digits 0 through 9). Binary floating-point numbers are stored
using binary precision (the digits 0 and 1). Such a storage scheme cannot represent all
values using decimal precision exactly. Frequently, the error that occurs when
converting a value from decimal to binary precision is undone when the value is
converted back from binary to decimal precision. The literal 0.1 is such an example.

BINARY_FLOAT
BINARY_FLOAT is a 32-bit, single-precision floating-point number datatype. Each
BINARY_FLOAT value requires 5 bytes, including a length byte.

2-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Storing Datetime Data

BINARY_DOUBLE
BINARY_DOUBLE is a 64-bit, double-precision floating-point number datatype. Each
BINARY_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 a
number).
You can specify floating-point numbers within the limits listed in Table 2–2 on
page 2-7.

Table 2–2 Floating Point Number Limits


Value Binary-Float Binary-Double
Maximum positive finite value 3.40282E+38F 1.79769313486231E+308
Minimum positive finite value 1.17549E-38F 2.22507485850720E-308

Storing Datetime Data


This section contains the following topics:
■ Using DATE and TIMESTAMP Datatypes on page 2-7
■ Manipulating the DATE and TIME Formats on page 2-8

Using DATE and TIMESTAMP Datatypes


Oracle Database supports the following datetime datatypes:
■ DATE
■ TIMESTAMP
■ TIMESTAMP WITH TIME ZONE
■ TIMESTAMP WITH LOCAL TIME ZONE

Using the DATE Datatype


Use the DATE datatype to store point-in-time values (dates and times) in a table. An
application that specifies the time for a job might use the DATE datatype.
The DATE datatype 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.

Using the TIMESTAMP Datatype


Use the TIMESTAMP datatype to store values that are precise to fractional seconds. An
application that must decide which of two events occurred first might use
TIMESTAMP.

Using the TIMESTAMP WITH TIME ZONE Datatype


Because TIMESTAMP WITH TIME ZONE can also store time zone information, it is
particularly suited for recording date information that must be gathered or
coordinated across geographic regions.

Beta Draft Using Datatypes 2-7


Storing Datetime Data

Using the TIMESTAMP WITH LOCAL TIME ZONE Datatype


Use TIMESTAMP WITH LOCAL TIME ZONE when the time zone is not significant. For
example, you might use it in an application that schedules teleconferences, where
participants each see the start and end times for their own time zone.
The TIMESTAMP WITH LOCAL TIME ZONE type is appropriate for two-tier
applications in which you want to display dates and times that use the time zone of
the client system. It is generally inappropriate in three-tier applications because data
displayed 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 time
is used.

Representing the Difference Between Datetime Values


Use the INTERVAL DAY TO SECOND datatype to represent the precise difference
between two datetime values. For example, you might use this value to set a reminder
for a time 36 hours in the future or to record the time between the start and end of a
race. To represent long spans of time with high precision, you can use a large value for
the days portion.
Use the INTERVAL YEAR TO MONTH datatype to represent the difference between
two 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 the
future, or check whether 6 months have elapsed since a particular date.
Oracle Database stores dates in its own internal format which is fixed-length fields of
seven bytes each, corresponding to century, year, month, day, hour, minute, and
second.

Manipulating the DATE and TIME Formats


For input and output of dates, the standard Oracle Database default date format is
DD-MON-RR. The RR datetime format element enables you store 20th century dates in
the 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 DATE
column is 12:00:00 A.M. (midnight) if no time portion is entered or if the DATE is
truncated. In a time-only entry, the date portion defaults to the first day of the current
month.
You can change the current default date or time format for a specific date or timestamp
with 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')

Oracle Database Express Edition provides various functions for calculating and
converting datetime data. For examples in SQL statements, see "Using Date Functions"
on page 4-13.
Be careful when using a date format such as DD-MON-YY. The YY indicates the year in
the current century. For example, 31-DEC-92 is December 31, 2092, not 1992 as
you might expect. If you want to indicate years in any century other than the current
one, use a format mask such as the default RR.
You can use the following techniques to change the default date format on a more
global level:

2-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Storing Datetime Data

■ 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 Chapter 8, "Working in a Global
Environment".

See Also:
■ Oracle Database SQL Reference for more information about date and
time formats
■ Oracle Database Concepts for information about Julian dates. Oracle
Database Julian dates might not be compatible with Julian dates
generated by other date algorithms.

Beta Draft Using Datatypes 2-9


Storing Datetime Data

2-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
3
Managing Database Objects

This chapter discusses creating and managing database objects in your schema, plus
design considerations and indexing guidelines when developing applications with the
Oracle Database Express Edition.
This section contains the following topics:
■ Overview of Managing Objects on page 3-1
■ Managing Tables on page 3-4
■ Managing Indexes on page 3-19
■ Managing Views on page 3-24
■ Managing Sequences on page 3-26
■ Managing Synonyms on page 3-28

See Also:
■ Oracle Database SQL Reference for information about schema
objects, object names, and data types.

Overview of Managing Objects


You need to create tables, indexes, and possibly other database objects in a schema
before you start developing your application. A schema is a collection of database
objects. 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. Objects
can define areas of the database to hold data, such as tables or indexes, or can consist
just of a definition, such as a views or synonyms.
This chapter discusses tables, indexes, views, sequences, and synonyms. Other
database (schema) objects include functions, packages, procedures, and triggers.
Functions, packages, and procedures are discussed in Chapter 6, "Using Subprograms
and Packages". Triggers are discussed in Chapter 7, "Using Triggers".
You can create, view, and manipulate database objects in your schema with Object
Browser or SQL. With the Object Browser, the underlying SQL is generated for you. In
this chapter, the examples use the Object Browser.
This section contains the following topics:
■ Database Objects for Your Application
■ Using Object Browser to Manage Database Objects in Your Schema
■ Viewing Object Reports

Beta Draft Managing Database Objects 3-1


Overview of Managing Objects

See Also:
■ Oracle Database Express Edition HTML DB User’s Guide for a
detailed description of the use of Object Browser to manage
database objects.
■ Oracle Database Express Edition 2 Day DBA Guide for information
on getting started with Oracle Database Express Edition

Database Objects for Your Application


Some object types have many more management options than others, but most have a
number of similarities. Every object in the database belongs to just one schema and has
a unique name within that schema. Therefore, when you create an object, you must
ensure it is in the schema where you intend to store it. Generally, you place all of the
objects 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 be
unique within its schema. For example, object names cannot be longer than 30 bytes
and must begin with a letter. If you attempt to create an object with a name that
violates any of these rules, then Oracle raises an error.
The following sections describe how to view, create, and manage the various types of
objects in your database schemas.

Using Object Browser to Manage Database Objects in Your Schema


You can use Object Browser to create, modify, or view all your database objects. For
example, with Object Browser you can create a table and then modify it by adding and
deleting columns or adding constraints.
To access Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. On the Object Browser home page, you can view and create database objects. For
example, you can click on the employees table in Tables object list to display
information on that table.

3-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Overview of Managing Objects

Figure 3–1 Object Browser

Viewing Object Reports


You can run reports on database objects with the Reports feature of the Utilities tool.
For example, you might want to run a report on all database objects that are currently
invalid or a report on all tables in the database.
To run a report on all columns in all of the tables in the database:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Utilities icon on the Database Home Page.
The Utilities home page appears.
3. On the Utilities page, click Object Reports.
4. In the Object Reports page, click the Tables icon.
5. In the Tables page, click the Columns icon.
6. Enter employees in the Table Filter field and click the Go button.

Beta Draft Managing Database Objects 3-3


Managing Tables

Figure 3–2 Object Reports

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using Object Reports

Managing Tables
Tables are the basic unit of data storage in an Oracle database. They hold all
user-accessible data. A table is two-dimensional object comprised of columns and
rows. For example the employees table includes (vertical) columns called first_
name, last_name, and employee_id. Each (horizontal) row in the table contains a
value for employee name and Id number. The most common type of table in an Oracle
database is a relational table.
This section contains the following topics:
■ Column Datatypes on page 3-5
■ Column Default Values on page 3-6
■ Ensuring Data Integrity With Constraints on page 3-6
■ Column Constraints on page 3-6
■ Table-Level Constraints on page 3-7
■ Creating a Table on page 3-9
■ Displaying a Table on page 3-10
■ Adding a Table Column on page 3-11
■ Dropping a Table Column on page 3-12
■ Adding a New Table Constraint on page 3-12
■ Add a Foreign Key Constraint on page 3-13

3-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables

■ Viewing Existing Constraints on page 3-14


■ Modifying an Existing Constraint on page 3-14
■ Dropping a Constraint on page 3-15
■ Adding Data to a Table on page 3-17
■ Viewing Table Data on page 3-17
■ Modifying Data in a Table on page 3-18
■ Removing a Row in a Table on page 3-18
■ Dropping a Table on page 3-19

See Also:
■ Oracle Database Administrator's Guide for information on
managing tables.
■ Oracle Database Concepts for conceptual information on tables
types.
■ Oracle Database SQL Reference for the syntax required to create and
alter tables.
■ Oracle Database Express Edition HTML DB User’s Guide for
information on managing tables

Column Datatypes
Datatypes are required elements that define the nature of the data to be stored in the
columns of a table. Datatypes might include a value to indicate the longest value that
can be placed in the column. When you create a table, you must specify a data type for
each of its columns. For a discussion of datatypes, see Chapter 2, "Using Datatypes".
These datatypes define the domain of values that each column can contain or each
argument can have. For example, DATE columns cannot accept the value February
29 (except for a leap year) or the values 2 or SHOE. Each value subsequently placed in
a column assumes the column datatype. For example, if you insert 17-JAN-2004 into
a date column, then Oracle treats the 17-JAN-2004 character string as a date value
after verifying that it translates to a valid date.

See Also: Oracle Database SQL Reference for a complete list of


Oracle’s built-in datatypes.

In 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 maximum
number of digits in the number, and the scale option to define how many of the digits
are to the right of the decimal point. For example, a field to hold monetary values
might be defined as NUMBER(12,2), providing ten digits for the primary unit of
currency (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 the
size to the maximum number of bytes (or, optionally, characters) to be stored in the
column. A column to hold postal codes for different countries, for example, might be
restricted to 12 bytes by defining it as VARCHAR2(12).

Beta Draft Managing Database Objects 3-5


Managing Tables

DATE columns are automatically formatted by Oracle to include a date and time
component. 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, Oracle Database Express Edition enables you great flexibility in how you
can display your dates and times.

Column Default Values


Default values are values that are automatically stored into the column whenever a
new row is inserted without a value being provided for the column. When you define
a column with a default value, any new rows inserted into the table store the default
value unless the row contains an alternate value for the column. Assign default values
to columns that contain a typical value. For example, in the departments table, if
most departments are located at one site, then the default value for the location_id
column can be set to this value, such as 1700.
Default values can help avoid errors where there is a number, such as zero, that
applies to a column that has no entry. For example, a default value of zero can simplify
testing, by changing a test like this:
IF salary >= 0 AND salary < 50000
to the simpler form:
IF salary < 50000
Depending upon your business rules, you might use default values to represent zero
or 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 including
SYSDATE, which is a SQL function that returns the current date.

Ensuring Data Integrity With Constraints


You 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 must
always be false.
When an integrity constraint applies to a table, all data in the table must conform to
the corresponding rule. When you issue a SQL statement that inserts or modifies data
in the table, Oracle Database XE ensures that the new data satisfies the integrity
constraint, without the need to do any checking within your program.
You can enforce rules by defining integrity constraints more reliably than by adding
logic to your application. Oracle Database XE can check that all the data in a table
obeys an integrity constraint faster than an application can.
Some constraints can be defined at the column level or at the table level. Column level
constraints are syntactically defined where the column to which the constraint applies
is defined. Table level constraints are syntactically defined at the end of the table
definition.

Column Constraints
Column constraints are optional elements that determine what values are valid in the
column. When creating a table with Object Browser, the only constraint defined at the
column level on the Create Table page is the NOT NULL constraint, which requires that
a value is included in this column for every row in the table.

3-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables

The NOT NULL constraint on a column requires that the column must contain a value
whenever a row is inserted or updated. Unlike other constraints described in
"Table-Level Constraints" on page 3-7, which may be defined as part of the column
definition or part of the table definition, the NOT NULL constraint must be defined as
part 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 column
that 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 unknown
or may not exist when rows are added or changed, for example, the second, optional
line in a mailing address.
A primary key constraint automatically adds a NOT NULL constraint to the column or
columns included in the primary key, in addition to enforcing uniqueness among the
values.

Table-Level Constraints
In an Oracle Database XE, you can apply rules to preserve the integrity of your data.
For example, in a table containing employee data, the employee email column must be
unique. Similarly, in this table you cannot have two employees with the same
employee Id.
Oracle Database XE enables you to apply data integrity rules as constraints on
columns at the table level. Any attempt to insert, update, or remove a row that violates
a constraint results in an error and the statement is rolled back. Likewise, any attempt
to apply a new constraint to a populated table also results in an error if any existing
row violates the new constraint.
The types of constraints you can apply at the table level are as follows:
■ Primary Key on page 3-7
■ Unique Key on page 3-8
■ Check Constraint on page 3-8
■ Foreign Key on page 3-9
Constraints can be created and, in most cases, modified with a number of different
status values. The options include enabled or disabled, which determine if the
constraint is checked when rows are added, modified, or removed; and deferred or
immediate, which cause constraint validation to occur at the end of a transaction or at
the end of a statement, respectively.

See Also: Oracle Database Concepts for more information on


constraints.

Primary Key
A primary key requires that a column (or combination of columns) be the unique
identifier of the row and ensures that no duplicate rows exist. A primary key column
cannot 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 unique
numeric values for your primary key values.
■ Choose a column whose data values are unique, because the purpose of a primary
key is to uniquely identify each row of the table.

Beta Draft Managing Database Objects 3-7


Managing Tables

■ Choose a column whose data values are never changed. A primary key value is
only used to identify a row in the table, and its data should never be used for any
other purpose. Therefore, primary key values should rarely or never be changed.
■ Choose a column that does not contain any nulls. A PRIMARY KEY constraint, by
definition, does not allow any row to contain a null in any column that is part of
the 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 key
constraint applies to more than one column. Although composite primary keys are
allowed, they do not satisfy all of the other recommendations. For example,
composite primary key values are long and cannot be assigned by sequence
numbers.

Unique Key
A unique key requires that every value in a column be unique. That is, no two rows
can have duplicate values in a specified column or combination of columns.
Choose columns for unique keys carefully. The purpose of these constraints is different
from that of primary keys. Unique key constraints are appropriate for any column
where duplicate values are not allowed. Primary keys identify each row of the table
uniquely, and typically contain values that have no significance other than being
unique. In the employees table, the email column has a unique key constraint
because it is important that the emails for each employee are unique. Note that the
email column has a NOT NULL constraint.
Some examples of good unique keys include:
■ An employee social security number where the primary key might be the
employee number
■ A truck license plate number where the primary key might be the truck number
■ A customer phone number, consisting of the two columns area_code and
local_phone where the primary key might be the customer number
■ A department name and location where the primary key might be the department
number

Check Constraint
A check constraint requires that a column (or combination of columns) satisfy a
condition for every row in the table. A check constraint must be a boolean expression
that is evaluated using the column value about to be inserted or updated to the row.
Use CHECK constraints when you need to enforce integrity rules based on logical
expressions, such as comparisons. Never use CHECK constraints when any of the other
types 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 the
commission from being larger than the salary.

3-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables

Foreign Key
Whenever two tables contain one or more common columns, you can enforce the
relationship between the tables through a referential integrity constraint with a foreign
key. A foreign key requires that all column values in the child table exist in the parent
table. The table that includes the foreign key is called the dependent or child table. The
table that is referenced is called the parent table.
An example of a foreign key constraint is when the department column of the
employees table (child) must contain a department Id that exists in the parent
departments table.
Foreign keys can be comprised of multiple columns. Such a composite foreign key
must reference a composite primary or unique key of the exact same structure, with
the same number of columns and the same datatypes. Because composite primary and
unique keys are limited to 32 columns, a composite foreign key is also limited to 32
columns. You must use the same datatype for corresponding columns in the parent
and child tables. The column names do not need to match.

Creating a Table
You can use Object Browser to create a table. The procedure in this section creates a
table that is similar to a portion of the employees sample table.
To create a table:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Table in the object list under Create.
4. In the Table Name field, enter the name of the table (my_employees).
5. Enter the following column names and datatypes and enable the NOT NULL
constraint where applicable. When you have entered the column information, click
Next. Note that the Preserve Case has been left unchecked; this provides that
names are stored in the default manner (uppercase) and avoids any extra
overhead.
employee_id NUMBER(6,0) NOT NULL
first_name VARCHAR2(20)
last_name VARCHAR2(25) NOT NULL
email VARCHAR2(25) NOT NULL
phone_number VARCHAR2(20)
hire_date DATE NOT NULL
job_id VARCHAR2(10)
salary NUMBER(8,2)

6. In the Primary Key page, select the Not Generated option. Accept the default
primary key name (MY_EMPLOYEES_PK) and select the employee_id column for
the Primary Key. Do not select a composite primary key. When you have
completed the page, click the Next button. The primary key uniquely identifies
each record (row) that is inserted in the table.
7. In the Foreign Key page, do not enter any information as there is no foreign key
for this table. Click the Next button.

Beta Draft Managing Database Objects 3-9


Managing Tables

8. On the Constraints page, select the Unique option to add a unique constraint.
Move the email table column to Key Columns list. Accept the default name for
this constraint. Click the Add button to add this constraint which ensures that the
email column value will be unique for all the rows.
9. On the Constraints page, select the Check option to add a check constraint. In the
entry field, enter salary >= 0. Accept the default name for this constraint. Click
the Add button to add this constraint which ensures that the salary column
value will be greater than or equal to zero for all the rows.
10. After you have reviewed the information in the Constraints page, click the Finish
button.
11. On the Create Table page, you can click the SQL button to view the SQL
statements that produce the table. This option shows the statement even if it is
incomplete, so you need to complete your input to see the complete SQL statement
when using this option.
12. Click the Create button to create the table

Figure 3–3 Creating a Table With Object Browser

Displaying a Table
You can use Object Browser to view information about an existing table, such as the
my_employees table that you previously created.
To display information for an existing table:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.

3-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables

3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. After viewing the Object Details for the table, click the Constraints tab to display
the constraints added to the table.
5. Click the employees and departments tables in the Object list to display
information about those tables. View the Object Details and Constraints pages.

Figure 3–4 Viewing a Table in Object Browser

Adding a Table Column


You can use Object Browser to add columns to a table.
To add a column:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click Add Column.
5. Enter the data to add column named manager_id. The datatype is NUMBER with
a precision of 6 and scale 0. The column can be NULL. Click the Next button.
6. Click the Finish button to complete the action.
7. Click Add Column.
8. Enter the data to add column named department_id. The datatype is NUMBER
with a precision of 4 and scale 0. The column can be NULL. Click the Next button.
9. Click the Finish button to complete the action.

Beta Draft Managing Database Objects 3-11


Managing Tables

Figure 3–5 Adding a Table Column With Object Browser

Dropping a Table Column


You can use Object Browser to delete columns in a table. Before you do delete a
column, make sure the data in that column is not going to be needed later.
To delete a column:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click Drop Column.
5. Select the manager_id column click the Next button.
6. Click the Finish button to complete the action.

Adding a New Table Constraint


You can use Object Browser to add a constraint to a table after it has been created. In
the my_employees table, you might want to enforce the rules so that each email
address is unique.
To add a constraint:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.

3-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables

4. Click the Constraints tab.


5. Click Create button.
6. In the Add Constraint page, select Check for the Constraint Type and first_
name for the Constraint on Column. Enter IS NOT NULL in the entry field for the
check constraint condition. Accept the default name (MY_EMPLOYEE_CON) for this
constraint. Click the Next button.
7. Click the Finish button to complete the action.

Figure 3–6 Adding a Constraint With Object Browser

Add a Foreign Key Constraint


You can use Object Browser to add a foreign key constraint on a column in one table to
a column in a reference table. This ensures that a value inserted in a column matches a
valid value in the reference table.
To add a foreign key constraint:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click the Constraints tab.
5. Click Create button.
6. In the Add Constraint page, select Foreign Key for the Constraint Type. Use
following to complete page:
Constraint Name: MY_FOREIGN_KEY
Foreign Key Column: DEPARTMENT_ID
Reference Table Name: DEPARTMENTS
Reference Table Column List: DEPARTMENT_ID

7. Click the Next button.

Beta Draft Managing Database Objects 3-13


Managing Tables

8. Click the Finish button to complete the action.

Viewing Existing Constraints


You can use Object Browser to view existing constraints on a table.
To view constraints:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click the Constraints tab.

Figure 3–7 Viewing Constraints With Object Browser

Modifying an Existing Constraint


You can use Object Browser to modify a constraint on a table. When modifying an
existing constraint, you can enable or disable the constraint.
To disable a constraint:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click the Constraints tab.

3-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables

5. Click the Disable button.


6. In the Disable Constraint page, select the constraint that you created on the
first_name column (MY_EMPLOYEE_CON). Click the Next button.
7. Click the Finish button to complete the action.

Figure 3–8 Disabling Constraints With Object Browser

Dropping a Constraint
You can use Object Browser to drop constraints from a table. Although you do not
have to disable a constraint before dropping it, you can determine whether the
constraint can be dropped by attempting to disable it first. If a constraint in a parent
table enforces a foreign key constraint in a child table, and if the child table contains
dependent rows, then the constraint cannot always be disabled or dropped.
Continuing the current example, you drop the unique constraint that you created
earlier in the section, "Adding a New Table Constraint" on page 3-12.
To drop a constraint:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click the Constraints tab.
5. Click the Drop button.
6. In the Drop Constraint page, select the constraint that you created on the first_
name column (MY_EMPLOYEE_CON). Click the Next button.
7. Click the Finish button to complete the action.

Adding Data to a Table


You can add a row of data to a table with Object Browser. This is the process of
inserting a row in the table.
To add data to a table:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.

Beta Draft Managing Database Objects 3-15


Managing Tables

2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click Data.
5. Click the Insert Row button.
6. In the Create Row page, add the following values:
employee_id: 100
first_name: Roberta
last_name: Delare
email: rdelare@company.com
phone_number: 555-111-4444
hire_date: 01-SEP-05
job_id: AC_MGR
salary: 7000
department_id: 20

Note that when you add the data, the values must conform to any constraints on
the table. For example, the email value must be 25 characters or less and the
department_id value must match a value in the department_id column of the
departments table.
7. Click the Create and Create Another button to insert the row of data and create
another row in the table.
8. In the Create Row page, add the following values:
employee_id: 101
first_name: Ricardo
last_name: Santiago
email: rsantiago@company.com
phone_number: 555-111-7777
hire_date: 08-SEP-05
job_id: AC_MGR
salary: 7000
department_id: 20

9. Click the Create button to insert the row of data.

3-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables

Figure 3–9 Adding Data to a Table

Viewing Table Data


Besides viewing table names and table definitions, you can view the data stored in the
table as well as the SQL statement used to display the data. You can also change the
SQL statement to alter the result set.
To view table data:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click Data.

Beta Draft Managing Database Objects 3-17


Managing Tables

Figure 3–10 Object Browser Data Page

For detailed information on the Object Browser page, see Oracle Database Express
Edition HTML DB User’s Guide.
You can also write your own SQL query using a SELECT statement to see the contents
of a table. See "Executing SQL Statements" on page 4-2.

Modifying Data in a Table


To modify data in a table:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click Data.
5. Click Edit next to employee_id equal to 101.
6. Change the value of phone_number to 555-111-8888.
7. Click the Apply Changes button.

Removing a Row in a Table


To remove a row in a table:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click Data.
5. Click Edit next to employee_id equal to 101.
6. Click the Delete button to remove this row from the table.
7. Click OK to confirm the delete action.

3-18 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Indexes

Dropping a Table
If you no longer need a table or its contents, then you can drop the table using Object
Browser. Be certain that you really do not need the data in the table before you drop it.
It may be difficult and time-consuming to retrieve the records, if they can be retrieved,
after you execute the drop statement.
To test this procedure, follow the procedure in "Creating a Table" on page 3-9 to create
a table.
To drop a table:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Tables in the Object list, then click the my_employees table that you
previously created.
4. Click Drop.
5. Click the Finish button to complete the action.

Managing Indexes
Indexes are optional structures associated with tables. You can create them to improve
query performance. Just as the index in this book helps you to quickly locate specific
information, an Oracle Database XE 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, it
is automatically maintained and used by Oracle Database XE. Changes to a table's data
or structure, such as adding new rows, updating rows, or deleting rows, are
automatically incorporated into all relevant indexes with complete transparency to the
user.
Some indexes are created implicitly through constraints that are placed on a table. For
example, a column with the constraint that its values be unique causes Oracle
Database XE to create a unique key index.
Oracle Database XE automatically creates the indexes necessary to support data
integrity defined with constraints when you add or enable those constraints. For
performance purposes, you might want to add an index to the columns you define in a
child table when adding a foreign key constraint. Before you add additional indexes,
you should examine the performance of your database. You can then compare
performance after the new indexes are added.
After index creation, Oracle Database XE automatically synchronizes the index with
any subsequent inserts, updates, or deletes to the base table.
Indexes are generally of value to queries and to SQL statements that need to operate
on a single, existing row or a small number of existing rows. Too many indexes can
cause 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 and
the optimizer picks just one of them. Unless other statements can take advantage of
the unused indexes, they are not providing any benefit. Therefore, you might find
yourself deleting indexes if you create too many.
This section contains the following topics:
■ Creating Indexes for Use with Constraints on page 3-20

Beta Draft Managing Database Objects 3-19


Managing Indexes

■ Index Types on page 3-20


■ Guidelines for Creating Indexes on page 3-21
■ Creating an Index on page 3-23
■ Displaying an Index on page 3-23
■ Dropping an Index on page 3-24

See Also: Oracle Database Express Edition HTML DB User’s Guide for
information on managing indexes

Creating Indexes for Use with Constraints


All enabled unique and primary keys require corresponding indexes. 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 can
even 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 you
automatically.

Index Types
Indexes can be categorized in a number of ways. The primary options are:

Normal
A standard, B-tree index contains an entry for each value in the index key along with
an address to the row where the value is stored. A B-tree index is the default and most
common type of index in an Oracle database.

Ascending and Descending


The default search through an index is from lowest to highest value, where character
data is sorted by ASCII values, numeric data from smallest to largest number, and date
from the earliest to the latest value. This default behavior is performed in indexes
created as ascending indexes. You can cause index searches to reverse the search order
by creating the related index with the descending option.

Column and Function-based


Typically, an index entry is based on the value or values found in the table's column or
columns. This is a column index. Alternatively, you can create a function-based index
in which the indexed value is derived from the table data. For example, to find
character data that can be in mixed case, you could use a function-based index to look
for the values as if they were all in uppercase characters.

Single Column and Concatenated


You can create an index on just one column, which is called a single column index, or
on multiple columns, which is called a concatenated index. Concatenated indexes are
useful when all of the columns are likely to be included in the WHERE clause of
frequently executed SQL statements.

3-20 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Indexes

For concatenated indexes, you should define the columns used in the index carefully
so that the column with the fewest duplicate values is named first, the column with
next fewest duplicate values is second, and so on. Columns with many duplicate
values or many rows with NULL values should not be included or should be the
last-named columns in the index definition.

Guidelines for Creating Indexes


You can create indexes on columns to speed up queries. Indexes provide faster access
to 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 of
these situations, creating an index on the column does not increase performance and
the index takes up resources unnecessarily.
Although the database creates an index for you on a column with an integrity
constraint, explicitly creating an index on such a column is recommended.

Index the Correct Tables and Columns


Use 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 rows
in a large table. This threshold percentage varies greatly, however, according to the
relative speed of a table scan and how clustered the row data is about the index
key. The faster the table scan, the lower the percentage; the more clustered the row
data, 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 to
create an index on a foreign key. See "Foreign Key" on page 3-9 for more
information.
■ Small tables do not require indexes; if a query is taking too long, then the table
might have grown from small to large.
Some columns are strong candidates for indexing. Columns with one or more of the
following 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 to
WHERE COL_X IS NOT NULL
This is because the first uses an index on COL_X (assuming that COL_X is a
numeric column).
Columns with the following characteristics are less suitable for indexing:

Beta Draft Managing Database Objects 3-21


Managing Indexes

■ 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 some
overhead) of the available space in the data block. Consult with the database
administrator for assistance in determining the space required by an index.

Limit the Number of Indexes for Each Table


The more indexes, the more overhead is incurred as the table is altered. When rows are
inserted or deleted, all indexes on the table must be updated. When a column is
updated, all indexes on the column must be updated.
You must weigh the performance benefit of indexes for queries against the
performance overhead of updates. For example, if a table is primarily read-only, you
might use more indexes; but, if a table is heavily updated, you might use fewer
indexes.

Choose the Order of Columns in Composite Indexes


Although you can specify columns in any order in the CREATE INDEX command, the
order of columns in the CREATE INDEX statement can affect query performance. In
general, 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 be
used 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_cost
1010 10-440 0.27
1010 10-457 5.10
1012 08-300 1.19
1012 10-440 0.25
1012 10-441 0.39
1012 10-457 4.96
1220 08-300 1.33
1292 10-457 5.29

Assume that there are five vendors, and each vendor has about 1000 parts. Suppose
that the vendor_parts table is commonly queried by SQL statements such as the
following:
SELECT * FROM vendor_parts
WHERE part_no = 457 AND vendor_id = 1012;

To increase the performance of such queries, you might create a composite index
putting 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 in
this example, queries with WHERE clauses using only the part_no column also note a
performance gain. Because there are only five distinct values, placing a separate index
on vendor_id would serve no purpose.

Drop Indexes That Are No Longer Required


You might drop an index if:
■ It does not speed up queries. The table might be very small, or there might be
many rows in the table but very few index entries.

3-22 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Indexes

■ 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 the
constraint 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 the
DROP ANY INDEX system privilege.

Creating an Index
You can create an index with Object Browser. To create an index, you specify one or
more columns to be indexed and the type of index you want to create. In the following
example, an index is created on the last_name column of the employees table.
Because the last_name column is frequently used when retrieving data, an index on
that column would increase the speed of those queries.
To create an index:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Index in the pull-down menu under Create in the Detail pane.
4. In the Table Name field, enter employees, then click the Next button. Do not
change any of the default values on the page.
5. In the Index Name field, enter last_name_index, then click the Next button. Do
not change any of the default values on the page.
6. Select last_name in the Index Column 1 pull down list, then click the Next
button. Do not change any of the default values on the page.
7. Click the SQL button to view the SQL statement that creates the index.
8. Click Finish button.

Displaying an Index
You can use Object Browser to display information about an existing index.
To display information for an index:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Indexes in the object list, then click the last_name_index index that you
previously created.
4. After viewing the Object Details for the index, click the SQL tab to display the
SQL statement used to create the index.
5. Click other indexes in the Object list to display information about those indexes.

Beta Draft Managing Database Objects 3-23


Managing Views

Figure 3–11 Viewing an Index in Object Browser

Dropping an Index
If you no longer need an index, you can drop it with Object Browser. See "Drop
Indexes That Are No Longer Required" on page 3-22.
To test this procedure, follow the procedure in "Creating an Index" on page 3-23 to
create an index.
To drop an index:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Indexes in the Object list, then click the last_name_index that you
previously created.
4. Click the Drop button to drop the selected index.
5. Click the Finish button to complete the action.

Note: You cannot drop an index that is currently used to enforce a


constraint. You must disable or drop the constraint and then, if the
index is not dropped as a result of that action, drop the index.

Managing Views
Views are customized presentations of data in one or more tables or other views. You
can think of them as stored queries. Views do not actually contain data, but instead
derive their data from the tables upon which they are based. These tables are referred
to as the base tables of the view.

3-24 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Views

Like tables, views can be queried, updated, inserted into, and deleted from, with some
restrictions. All operations performed on a view actually affect the base tables of the
view. Views provide an additional level of security by restricting access to a
predetermined set of rows and columns of a table. They also hide data complexity and
store complex queries.
This section contains the following topics:
■ Creating a View on page 3-25
■ Displaying a View on page 3-26
■ Dropping a View on page 3-26

See Also: Oracle Database Express Edition HTML DB User’s Guide for
information on managing view

Creating a View
The following example creates a view derived from the departments and
employees tables to display department information along with the corresponding
manager’s name. This view combines the department_id, department_name, and
manager_id columns from the departments table with the employee_id, first_
name, and last_name columns of the employees table. The tables are joined from
the manager_id of the departments table to the employee_id of the employees
table. This ensures that the corresponding first and last name of a manager is
displayed in the view.
To create a view in Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Views in the pull-down menu under Create in the Detail pane.
4. In the View Name field, enter the name of the view (my_view).
5. Click Query Builder to build the query for the view.
6. Click the departments table and select the department_id, department_
name, and manager_id columns.
7. Click the employees table and select the employee_id, first_name, and
last_name columns.
8. Click the blank box to the right of manager_id in the departments table to
choose this column for a join with the employees table.
9. Click the blank box to the right of the employee_id in the employees table to
choose this as the corresponding column for the join with manager_id of the
departments table. Note the line that is added to the diagram connecting the
two tables.
10. Click the Run button to see the results when querying this view.

11. Click the Return button to return to Object Browser.

12. Click the Next button.

13. Click the SQL button to view the SQL statement that creates the view.

14. Click the Create button to create the view.

Beta Draft Managing Database Objects 3-25


Managing Sequences

Displaying a View
You can use Object Browser to display information about an existing view.
To display information about a view:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Views in the Object list, then click the my_view that you previously created
to display Object Details for the view.
4. Click the SQL button to view the SQL statement that created the view.
5. Click the emp_details_view view in the Object list to display the Object Details
of that view.
6. Click the SQL button to view the SQL statement that created emp_details_
view.

Dropping a View
If you no longer need a view, then you can drop it using Object Browser.
To test this procedure, follow the procedure in "Creating a View" on page 3-25 to create
a view.
To drop a view:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Views in the object list, then click the my_view view that you previously
created.
4. Click the Drop button.
5. Click the Finish button to complete the action.

Managing Sequences
A sequence is a database object similar to a pseudocolumn that generates unique
sequential values. These values are often used for primary and unique keys. Using a
sequence generator to provide the value for a primary key in a table is an easy way to
guarantee that the key value is unique.
You can refer to sequence values in SQL statements with these pseudocolumns:
■ CURRVAL: Returns the current value of a sequence
■ NEXTVAL: Increments the sequence and returns the next value
You must qualify CURRVAL and NEXTVAL with the name of the sequence, such as
employees_seq.CURRVAL or employees_seq.NEXTVAL.
When you create a sequence, you can define its initial value and the increment
between its values. The first reference to NEXTVAL returns the initial value of the
sequence. Subsequent references to NEXTVAL increment the sequence value by the
defined increment and return the new value. Any reference to CURRVAL always

3-26 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Sequences

returns the current value of the sequence, which is the value returned by the last
reference to NEXTVAL.
Before you use CURRVAL for a sequence in your session, you must first initialize the
sequence with NEXTVAL.
This section contains the following topics:
■ Creating a Sequence
■ Displaying a Sequence
■ Dropping a Sequence
For examples of managing sequences using SQL statements, see "Creating and
Dropping a Sequence" on page 4-18.

See Also: Oracle Database Express Edition HTML DB User’s Guide for
information on managing sequences

Creating a Sequence
To create a sequence in Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Sequence in the pull-down menu under Create in the Detail pane.
4. In the Sequence Name field, enter the name of the new sequence (my_sequence).
5. In the Start With field, enter 1000. This starts the sequence with a value of 1000.
6. For the other fields on the page, use the default values. Click the Next button.
7. Click the SQL button to view the SQL statement that creates this sequence.
8. Click the Finish button to create the sequence.
After creating and initializing a sequence, you can access and use the current value of
the sequence. For an example of the use of a sequence in a SQL statement to insert data
in a table, see Example 4–13 on page 4-12.

Displaying a Sequence
To display information for an existing sequence in Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Sequences in the Object list, then click the my_sequence sequence that you
previously created.
4. After viewing the Object Details for the sequence, click the SQL tab to display the
SQL statement used to create the sequence.
5. Click other sequences in the Object list to display information about those
sequences.

Beta Draft Managing Database Objects 3-27


Managing Synonyms

Dropping a Sequence
To test this procedure, follow the procedure in "Creating a Sequence" on page 3-27 to
create a sequence.
To drop an existing sequence in Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Sequences in the object list, then click the my_sequence that you
previously created.
4. Click the Drop button to drop the selected sequence.
5. Click the Finish button to complete the action.

Managing Synonyms
A synonym is an alias for any schema object such as a table or view. Synonyms
provide an easy way to provide an alternative name for a database object and can be
used to simplify SQL statements for database users. For example, you can create a
synonym 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 the
employees table, you can use the employees synonym to refer to the personnel
table 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 database
other than its definition.
You can create both public and private synonyms. A public synonym is owned by the
special user group named PUBLIC and every user in a database can access it. A private
synonym is in the schema of a specific user who has control over its availability to
others.
This section contains the following topics:
■ Creating a Synonym on page 3-28
■ Displaying a Synonym on page 3-29
■ Dropping a Synonym on page 3-29
For examples of managing synonyms using SQL statements, see "Creating and
Dropping a Synonym" on page 4-18.

See Also: Oracle Database Express Edition HTML DB User’s Guide for
information on managing synonyms

Creating a Synonym
To create a synonym in Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Synonym in the pull-down menu under Create in the Detail pane.

3-28 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Synonyms

4. In the Synonym Name field, enter the name of the synonym (emps).
5. In the Object field, enter employees.
6. For the other fields on the page, use the default values. Click the Next button.
7. Click the SQL button to see the SQL statement that creates this sequence.
8. Click the Finish button to create the synonym.

Displaying a Synonym
To display an existing synonym in Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Synonyms in the Object list, then click the emps synonym to display Object
Details for that synonym.

Dropping a Synonym
To test this procedure, follow the procedure in "Creating a Synonym" on page 3-28 to
create a synonym.
To drop an existing synonym in Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page to display the Object
Browser home page.
3. Select Synonyms in the object list, then click the emps synonym that you
previously created.
4. Click the Drop button to drop the selected synonym.
5. Click the Finish button to confirm.

Beta Draft Managing Database Objects 3-29


Managing Synonyms

3-30 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
4
Using SQL

This chapter discusses how to use SQL with Oracle Database Express Edition.
This section includes the following topics:
■ Overview of SQL on page 4-1
■ Executing SQL Statements on page 4-2
■ Retrieving Data With Queries on page 4-4
■ Manipulating Data With SQL Statements on page 4-8
■ Transaction Control Statements on page 4-10
■ Using Pseudocolumns, Sequences, and SQL Functions on page 4-11
■ Using SQL Data Definition Language Statements on page 4-15

See Also:
■ Oracle Database SQL Reference for detailed information about SQL
statements and other parts of SQL, such as operators, functions,
and format models.
■ Oracle Database Concepts for conceptual information on SQL.
■ SQL*Plus User's Guide and Reference for information about
SQL*Plus, Oracle's version of SQL.
■ Oracle Database Sample Schemas for information on the HR sample
schema that is used for examples in this chapter.

Overview of SQL
Structured Query Language (SQL) is a database access, nonprocedural language.
Users issue SQL statements or commands to perform various tasks, such as retrieving
data, and the SQL language compiler automatically handles how to navigate the
database and perform the desired task. All database operations are performed using
SQL.
This section includes the following topics:
■ Features of SQL on page 4-2
■ Types of SQL Statements on page 4-2

Beta Draft Using SQL 4-1


Executing SQL Statements

Features of SQL
Using the various Oracle tools, such as the SQL Commands page or SQL*Plus, you can
enter and execute SQL, PL/SQL, SQL*Plus and operating system commands. With
SQL commands and statements you can perform the following:
■ Format, perform calculations on, store, and print from query results
■ Examine table and object definitions
■ Develop and run batch scripts
■ Perform database administration

Types of SQL Statements


All operations performed on the information in an Oracle database are run using SQL
statements. A statement consists partially of SQL reserved words, which have special
meaning in SQL and cannot be used for any other purpose. For example, SELECT and
UPDATE are reserved words and cannot be used as table names.
A SQL statement is an instruction. The statement must be the equivalent of a complete
SQL sentence, as in:
SELECT last_name, department_id FROM employees;
Oracle SQL statements are divided into several categories:
■ Data Manipulation Language (DML) Statements
These statements query, insert, update, delete data in tables.
■ Transaction Control Statements
These statements commit or rollback the processing of transactions.
■ Data Definition Language (DDL) Statements
These create, alter, and drop database objects.

Executing SQL Statements


You can run SQL statements and commands from the SQL Commands page, SQL
Scripts page, or SQL*Plus command line. For information on executing SQL
statements with the SQL*Plus command line, see Appendix A, "SQL*Plus".
To run the examples in this guide, you should log in as user HR with your password
for the HR account.
■ Running SQL Statements in the SQL Commands Page on page 4-2
■ Running SQL Statements in the Script Editor Page on page 4-3

Running SQL Statements in the SQL Commands Page


To enter and run SQL statements in the SQL Commands page:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.
3. Click the SQL Commands icon to display the SQL Commands page.

4-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Executing SQL Statements

4. In the SQL Commands page, enter the SQL statement(s) and click the Run button
to execute the statement.
5. If you want to save the SQL statement(s) for future use, click the Save button.
6. In the Name field, enter a name for the saved SQL. You can also enter an optional
description. Click the Save button to save the SQL.
7. To access saved SQL, click the Saved SQL tab and select the name of the saved
SQL that you want to access.

Figure 4–1 SQL Commands Page

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Commands

Running SQL Statements in the Script Editor Page


You can also enter SQL statements in the Script Editor page and create a SQL script
that can be run from SQL*Plus. For information on running SQL scripts from
SQL*Plus, see "Running Scripts From SQL*Plus" on page A-3.
To access and run SQL statements in the SQL Script Editor page:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.
3. Click the SQL Scripts icon to display the Script Editor page.
4. Click the Create button to create a SQL script.
5. In the Script Name field, enter a name (my_sql_script) for the script.
6. In the Script Editor entry area, enter the SQL statement(s) and click the Run
button to execute the statement(s).
7. Click the Run button in the Script Editor page to execute the statement(s) in the
script.

Beta Draft Using SQL 4-3


Retrieving Data With Queries

8. Click the Run button in the Run Script page to confirm that you want to run the
script.
9. Click the script (my_sql_script) in the Manage Scripts page. to display the
results of the script.
10. Select the Detail view and enable all the Show options in the Results page to
display details on the script results.
11. After you completed all the SQL statement in the script, you can click the Save
button to save the script file for future use. Note that the .sql extension is
appended to the SQL script name.

Figure 4–2 SQL Script Editor Page

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Scripts

Retrieving Data With Queries


You can retrieve data from rows stored one or more database tables or views with a
query using the SQL SELECT statement. The SELECT statement retrieves the all of or
part of the column data from rows depending on the conditions that you specify in
WHERE clauses. The group of columns that are selected from a table is referred to as the
SELECT list.
■ Displaying Data Using the SELECT Statement on page 4-4
■ Using Character Literals in SQL Statements on page 4-5
■ Using a Column Alias to Change Headings When Selecting Data on page 4-5
■ Restricting Data Using the WHERE Clause on page 4-6
■ Sorting Data Using the ORDER BY Clause on page 4-7
■ Displaying Data From Multiple Tables on page 4-7
You can also build SQL queries with Query Builder. See "Viewing Table Data" on
page 3-17.

Displaying Data Using the SELECT Statement


Example 4–1 shows how to use SELECT to query and retrieve all data from the
employees table and how to retrieve only specific columns from the employees table.
Note the use of comments to document the SQL statements. The comments (or
remarks) in this example begin with --, but you could also use rem or REM.

4-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Retrieving Data With Queries

Example 4–1 Using SELECT to Retrieve Data


-- the following uses the wildcard * to retrieve all the columns of data in the
-- rows of the employees table
SELECT * FROM employees;

-- the following retrieves the data in columns employee_id, last_name, first_name


SELECT employee_id, last_name, first_name FROM employees;

See Also:
■ Oracle Database SQL Reference for detailed information on the SQL
SELECT statement.

Using Character Literals in SQL Statements


Many SQL statements, functions, expressions, and conditions require you to specify
character 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 n
specifies the literal using the national character set. For example, N'résumé' is a
National character literal.
For information on unicode literals, see "Unicode String Literals" on page 8-21.

Quoting Character Literals


By default you must quote character literals in single-quotes, as in 'Hello'. This
technique can sometimes be inconvenient if the text itself contains single quotes. In
such cases, you can also use the Q-quote mechanism, which enables you to specify q
or Q followed by a single quote and then another character to be used as the quote
delimiter. For example, the literal q'#it's the "final" deadline#' uses the
pound 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, and
return. If the opening quote delimiter is a [, {, <, or ( character, then the closing quote
delimiter must be the corresponding ], }, >, or ) character. In all other cases, the
opening and closing delimiter must be the identical character.
The following character literals use the alternative quoting mechanism:
q'(name LIKE '%DBMS_%%')'
q'<'Data,' he said, 'Make it so.'>'
q'"name like '['"'
nq'ïŸ1234ï'

See Also:
■ Oracle Database Globalization Support Guide to learn about national
character sets
■ Oracle Database SQL Reference to learn about character literals

Using a Column Alias to Change Headings When Selecting Data


When displaying the result of a query, SQL normally uses the name of the selected
column as the column heading. You can change a column heading by using a column
alias to make the heading more descriptive and easier to understand.

Beta Draft Using SQL 4-5


Retrieving Data With Queries

You can specify the alias after the column name in the SELECT list using a space as a
separator. If the alias contains spaces or special characters (such as # or $), or if it is
case-sensitive, enclose the alias in double quotation marks (" ").
Example 4–2 shows the use of a column alias to provide more description for each
heading of the columns selected in a query.

Example 4–2 Using 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 columns
SELECT employee_id "Employee Id number", last_name "Employee last name",
first_name "Employee first name" FROM employees;

Restricting Data Using the WHERE Clause


The WHERE clause uses a comparison operator to identify specific rows in a table.
Comparison operators include those listed in Table 4–1.

Table 4–1 Comparison Operators


Operator Definition
=, !=, <> test for equal, not equal, not equal
>, >=, <, <= test greater than, greater than or equal to, less than, less than or
equal to
BETWEEN ... AND ... check for range between and including two values
LIKE search for a match in string, using the wildcard symbols % (zero
or multiple characters) or _ (one character)
IN ( ) test for a match in a specified list of values
IS NULL, IS NOT NULL check whether is null (no value), is not null

Example 4–3 shows how to use SELECT with a WHERE clause and several comparison
operators to retrieve specific data from the employees table.

Example 4–3 Using SELECT With a WHERE Clause


-- the following retrieves data where the manager_id equals 122
SELECT * FROM employees WHERE manager_id = 122;

-- this retrieves data where the manager_id equals 122 and job_id is ST_CLERK
SELECT * FROM employees WHERE manager_id = 122 AND job_id = 'ST_CLERK';

-- this retrieves employees with managers with Ids between 122 and 125 inclusive
SELECT * 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 name
SELECT employee_id, last_name FROM employees WHERE last_name LIKE '%mar%';

-- this retrieves employees where the last name starts with Mar
SELECT employee_id, last_name FROM employees WHERE last_name LIKE 'Mar%';

-- this retrieves employees where the commission percentage is not null


SELECT employee_id, last_name FROM employees WHERE commission_pct IS NOT NULL;

-- the following retrieves data where the employee_id equals 125, 130, or 135

4-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Retrieving Data With Queries

SELECT employee_id, last_name, first_name FROM employees


WHERE employee_id IN (125, 130, 135);

See Also:
■ Oracle Database SQL Reference for detailed information on using
the WHERE clause.

Sorting Data Using the ORDER BY Clause


Example 4–4 shows how to use SELECT with the ORDER BY clause to retrieve and
display rows from the employees table ordered (sorted) by a specified column. You
can sort by a column that is not in the selected list of columns.
You can specify the sort order ASC for ascending or DESC for descending. The default
sort 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 before
01-JUN-95.
Null (empty) values are displayed last for ascending sequences and first for
descending sequences.

Example 4–4 Using 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 first
SELECT * 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 first
SELECT employee_id, last_name, first_name, manager_id FROM employees
ORDER BY manager_id DESC;

See Example 4–19 on page 4-15 for the use of ORDER BY with the GROUP BY clause.

See Also:
■ Oracle Database SQL Reference for detailed information on using
ORDER BY with SELECT.

Displaying Data From Multiple Tables


Example 4–5 shows how to use SELECT to display data from the multiple tables. This
process is referred to as joining the tables. In a join, multiple tables share a similar
column.
Note the use of the table aliases (d, e, and l) to explicitly identify the columns by table
in the SQL statement. The alias is defined in the FROM clause of the SQL statement.
You can also use the complete table name to explicitly identify a column, such as
employees.employee_id. A table alias is used to simply and reduce the size of the
SQL code.

Example 4–5 Using SELECT to Display Data From Multiple Tables


-- the following SELECT statements retrieve data from two tables
-- that have a corresponding column (department_id)

Beta Draft Using SQL 4-7


Manipulating Data With SQL Statements

-- note that the employees table has been aliased to e and departments to d
SELECT e.employee_id, e.last_name, e.first_name, e.department_id,
d.department_name FROM employees e, departments d
WHERE 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_id
SELECT e.employee_id, e.department_id, d.department_name, d.location_id,
l.country_id FROM employees e, departments d, locations l
WHERE e.department_id = d.department_id AND d.location_id = l.location_id;

The joins in Example 4–5 use the Oracle-proprietary syntax. Example 4–6 is an
example of the same join using ANSI syntax. There is no performance difference
between the ANSI and Oracle syntax.

Example 4–6 Selecting Data From Multiple Table With 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 ON
SELECT e.employee_id, e.last_name, e.first_name, e.department_id,
d.department_name FROM employees e JOIN departments d
ON e.department_id = d.department_id;

See Also:
■ "Joins" in Oracle Database SQL Reference for information on using
SELECT with multiple tables.

Manipulating Data With SQL Statements


Data manipulation language (DML) statements query or manipulate data in existing
schema 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 SQL statements.
■ Adding Data With the INSERT Statement on page 4-8
■ Updating Data With the UPDATE Statement on page 4-9
■ Deleting Data With the DELETE Statement on page 4-9

Adding Data With the INSERT Statement


Example 4–7 shows how to use INSERT to add a row to the employees table. The
data inserted must be valid for the datatype and size of each column of the table. In
the second INSERT statement, values are inserted only into the specified columns of
the table and the remaining columns are set to NULL. If the those remaining columns
had been specified as NOT NULL for the table, an error would have been raised. See
"Managing Tables" on page 3-4 and "Column Constraints" on page 3-6.

Example 4–7 Using the INSERT Statement


-- the following inserts data for all the columns in a row

4-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Manipulating Data With SQL Statements

INSERT 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


INSERT 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 300
SELECT employee_id, last_name FROM employees WHERE employee_id >= 300;

See Also:
■ Oracle Database SQL Reference for information on the INSERT
statement.

Updating Data With the UPDATE Statement


Example 4–8 shows how to use UPDATE to update data in the employees table. Note
the use of the use of multiplication operator * to calculate a new salary. For
information on arithmetic operators, See "Using Arithmetic Operators" on page 4-13.

Example 4–8 Using the UPDATE Statement


SELECT 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 salary


SELECT salary FROM employees WHERE employee_id = 301;

See Also:
■ Oracle Database SQL Reference for information on the UPDATE
statement.

Deleting Data With the DELETE Statement


Example 4–9 shows how to use DELETE to delete rows in the employees table. Note
the use of the WHERE clause. Without that clause, all the rows would be deleted.

Example 4–9 Using the DELETE Statement


DELETE FROM employees WHERE employee_id = 300 OR employee_id = 301;

-- the following should not find any records


SELECT * FROM employees WHERE employee_id >= 300;

See Also:
■ Oracle Database SQL Reference for information on the DELETE
statement.

Beta Draft Using SQL 4-9


Transaction Control Statements

Transaction Control Statements


Transaction control statements manage the changes made by DML statements and
group 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 a
savepoint (ROLLBACK)
This section includes the following topics:
■ Committing Transaction Changes on page 4-10
■ Rolling Back a Transaction on page 4-10

Committing Transaction Changes


Example 4–10 shows how to use COMMIT to commit (save) changes to the database.
When a COMMIT has been executed, all the recent changes are saved.

Example 4–10 Using the COMMIT Statement


-- add a row and then update the data
INSERT 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 database


COMMIT;

See Also:
■ Oracle Database SQL Reference for information on the COMMIT
statement.

Rolling Back a Transaction


Example 4–11 shows how to use ROLLBACK to rollback changes made to the database
before a COMMIT has been executed.

Example 4–11 Using the ROLLBACK Statement


-- delete a row (record)
DELETE FROM employees WHERE last_name = 'Doe';

-- rollback the delete statement because the previous DELETE was incorrect
ROLLBACK;

-- the following is valid


SELECT * FROM employees WHERE last_name = 'Doe';

See Also:
■ Oracle Database SQL Reference for information on the ROLLBACK
statement.

4-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using Pseudocolumns, Sequences, and SQL Functions

Using Pseudocolumns, Sequences, and SQL Functions


With SQL built-in functions you can manipulate character, numeric, and date data in
SQL statements. You can also perform operations on a collection of data with the
aggregate functions.
Pseudocolumns are built-in values that provide specific information with a query and
are similar to functions without arguments. However, functions without arguments
typically return the same value for every row in the result set, whereas
pseudocolumns typically return a different value for each row.
This section includes the following:
■ Using Pseudocolumns With SQL on page 4-11
■ Using Sequences on page 4-11
■ Using Character Functions on page 4-12
■ Using Arithmetic Operators on page 4-13
■ Using Numeric Functions on page 4-13
■ Using Date Functions on page 4-13
■ Using Aggregate Functions on page 4-15

See Also:
■ Oracle Database SQL Reference for detailed information on SQL
functions.

Using Pseudocolumns With SQL


Example 4–12 show the use of the ROWNUM, SYSDATE, and USER pseudocolumns. The
ROWNUM pseudocolumn returns a number indicating the order in which Oracle selects
the row in a query. SYSDATE returns the current date and time set for the operating
system on which the database resides. USER returns the name of the user name that is
currently logged in. Note the use of the dummy table DUAL, which is automatically
created by Oracle Database XE for use in SQL statements.

Example 4–12 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 statement
SELECT SYSDATE "NOW" FROM DUAL;

-- display the name of the current user, the user name should be HR
SELECT USER FROM DUAL;

-- using ROWNUM < 10 limits the number of rows returned to less than 10
SELECT employee_id, hire_date, SYSDATE FROM employees WHERE ROWNUM < 10;

See Example 4–17 on page 4-14 for another example of the use of SYSDATE.

Using Sequences
A sequence is a database object similar to a pseudocolumn that generates unique
sequential values, often used for primary and unique keys. You can refer to sequence
values in SQL statements with the CURRVAL and NEXTVAL pseudocolumns. See
"Creating a Sequence" on page 3-27.

Beta Draft Using SQL 4-11


Using Pseudocolumns, Sequences, and SQL Functions

To generate a sequence number, you call the sequence using the CURRVAL or NEXTVAL
keywords. You must qualify CURRVAL and NEXTVAL with the name of the sequence,
such as employees_seq.CURRVAL or employees_seq.NEXTVAL. Before you use
CURRVAL for a sequence in your session, you must first initialize the sequence with
NEXTVAL.
Example 4–13 shows an example of the use of the employees_seq sequence with the
employee_id of the employees table. The employees_seq sequence is part of the
HR schema and had been created for use with the employees table. When a sequence
is intended to be used with a specific table, it is a good practice to include the name of
the table in the sequence name.

Example 4–13 Using Sequences


-- first initialize the employees_seq sequence with NEXTVAL
SELECT employees_seq.NEXTVAL FROM DUAL;

-- after initializing the sequence, use CURRVAL as the next value in the sequence
INSERT 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 statement
SELECT employee_id, last_name FROM employees WHERE last_name = 'Vernal';

Using Character Functions


Oracle provides a set of character functions that you can use in your SQL statements to
customize the character values.
Example 4–14 shows how to use character functions on character data.

Example 4–14 Using Character Functions


-- you can use the UPPER function to display uppercase data, LOWER for lowercase
SELECT employee_id, UPPER(last_name), LOWER(first_name) FROM employees;

-- you can use CONCAT function to concatenate character data


SELECT 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 end
SELECT 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
SELECT TO_CHAR(SYSDATE, 'fmMonth DD YYYY') "Today" FROM DUAL;

-- the following displays 21-SEP-2005 AD


SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY AD') "Today" FROM DUAL;

4-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using Pseudocolumns, Sequences, and SQL Functions

Using Arithmetic Operators


You can use arithmetic operators to create expressions for calculations on data in
tables. The arithmetic operators include:
■ + for addition
■ - for subtraction
■ * for multiplication
■ / for divide
In an arithmetic expression, multiplication and division are evaluated first, then
addition and subtraction. When operators have equal precedence, the expression is
evaluated left to right. It is best to include parentheses to explicitly determine the order
of operators and provide clarity in the expression.
Example 4–15 shows the use of arithmetic operators in expressions with the data in the
employees table. Note the use of a column alias to provide a more useful heading for
the displayed output.

Example 4–15 Using Arithmetic Operators


-- in the following query the commission is displayed as a percentate instead
-- of the decimal that is stored in the database
SELECT 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 145
SELECT employee_id, ((salary + 100) * 12) "Proposed new annual salary"
FROM employees WHERE manager_id = 145;

Using Numeric Functions


Example 4–16 shows how to use numeric functions on numeric data in the
employees table.

Example 4–16 Using Numeric Functions


-- you can use the ROUND function to round off numeric data, in this case to
-- two decimal places
SELECT employee_id, ROUND(salary/30, 2) "Salary per day" FROM employees;

Using Date Functions


Oracle Database Express Edition provides various functions for calculating and
converting datetime data.

See Also: Oracle Database SQL Reference for details about each
function

Performing Date Arithmetic


Oracle Database provides a number of features to help with date arithmetic, so that
you 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 the
following:

Beta Draft Using SQL 4-13


Using Pseudocolumns, Sequences, and SQL Functions

■ ADD_MONTHS function, which returns the date plus the specified number of
months.
■ MONTHS_BETWEEN function, which returns the number of months between two
dates.
■ SYSDATE function, which returns the current date and time set for the operating
system on which the database resides.
■ SYSTIMESTAMP function, which returns the system date, including fractional
seconds and time zone, of the system on which the database resides.
■ TRUNC function, which when applied to a DATE value, trims off the time portion
so that it represents the very beginning of the day (the stroke of midnight). By
truncating two DATE values and comparing them, you can determine whether
they refer to the same day. You can also use TRUNC along with a GROUP BY clause
to produce daily totals.
■ Arithmetic operators such as + and -. For example, SYSDATE-7 refers to 7 days
before the current system date.
■ INTERVAL datatypes, which enable you to represent constants when performing
date arithmetic rather than performing your own calculations. For example, you
can add or subtract INTERVAL constants from DATE values or subtract two DATE
values and compare the result to an INTERVAL.
■ Comparison operators such as >, <, =, and BETWEEN.

Converting Between Datetime Types


Oracle Database provides several useful functions that enable you to convert to a from
datetime datatypes. Some useful functions include:
■ EXTRACT, which extracts and returns the value of a specified datetime field from a
datetime or interval value expression
■ NUMTODSINTERVAL, which converts a NUMBER or expression that can be implicitly
converted to a NUMBER value to an INTERVAL DAY TO SECOND literal
■ NUMTOYMINTERVAL, which converts a NUMBER or expression that can be implicitly
converted to a NUMBER value to an INTERVAL YEAR TO MONTH literal
■ TO_DATE, which converts character data to a DATE datatype
■ TO_CHAR, which converts DATE data to character data
■ TO_DSINTERVAL, which converts a character string to an INTERVAL DAY TO
SECOND value
■ TO_TIMESTAMP, which converts character data to a value of TIMESTAMP datatype
■ TO_TIMESTAMP_TZ, which converts character data to a value of TIMESTAMP
WITH TIME ZONE datatype
■ TO_YMINTERVAL, which converts a character string to an INTERVAL YEAR TO
MONTH type
Example 4–17 shows how to use date functions on date data.

Example 4–17 Using 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 column
SELECT employee_id, TRUNC(MONTHS_BETWEEN(SYSDATE, HIRE_DATE)) "Months Employed"

4-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL Data Definition Language Statements

FROM employees;

-- the following displays the year hired for each employee id


SELECT employee_id, EXTRACT(YEAR FROM hire_date) "Year Hired" FROM employees;

Example 4–18 shows how to use date functions with format masks.

Example 4–18 Using 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 mask
SELECT 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 mask
SELECT 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 mask
SELECT 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 mask
SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Now" FROM DUAL;

Using Aggregate Functions


Group functions operate on sets of rows to give one result per group. These sets may
comprise the entire table or the table split into groups.
Example 4–17 shows how to use aggregate functions on collections of data in the
database. Aggregate functions include COUNT, MAX, MIN, and SUM. The GROUP BY
clause is used to select groups of rows by a specified expression and returns one row
of summary information for each group.

Example 4–19 Using Aggregate Functions


-- you can use COUNT to count the employees with manager 122
-- note the use of a column alias Employee Count
SELECT COUNT(*) "Employee Count" FROM employees WHERE manager_id = 122;

-- count the employees grouped by manager, also sort the groups


SELECT COUNT(*) "Employee Count", manager_id FROM employees
GROUP BY manager_id ORDER BY manager_id;

-- you can use MIN to find the minimum salary for employees with manager 122
SELECT 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 order
SELECT MIN(salary), MAX(salary), job_id FROM employees
GROUP BY job_id ORDER BY job_id;

Using SQL Data Definition Language Statements


Data definition language (DDL) statements include CREATE, ALTER, and DROP for
defining database objects. When managing database objects, the Object Browser

Beta Draft Using SQL 4-15


Using SQL Data Definition Language Statements

provides a simple and easy-to-use interface that can be utilized instead of SQL DDL
statements. See "Using Object Browser to Manage Database Objects in Your Schema"
on page 3-2.
In this guide, some basic SQL DDL statements are used in the code examples and a
brief description of some DDL statements are discussed here.
This section includes the following topics:
■ Creating a Table With SQL on page 4-16
■ Creating and Modifying an Index With SQL on page 4-17
■ Creating and Modifying a Constraint With SQL on page 4-17
■ Altering a Table With SQL on page 4-17
■ Dropping a Table With SQL on page 4-18
■ Creating and Dropping a Sequence on page 4-18
■ Creating and Dropping a Synonym on page 4-18

Creating a Table With SQL


To create a database object, such as a table, use the SQL CREATE statement as shown in
Example 4–20. When you create a table, you need to provide datatypes for each
column.

Example 4–20 Creating a Simple Table


-- create a simple table for keeping track of birthdays
CREATE TABLE my_birthdays
( first_name VARCHAR2(20),
last_name VARCHAR2(25),
bday_date DATE
);

Optionally, you can provide constraints as shown inExample 4–21. The use of
constrains are discussed in "Ensuring Data Integrity With Constraints" on page 3-6.

Example 4–21 Creating a Table With Constraints


-- create a table similar to the employees table in the HR schema
CREATE TABLE my_employees
( employee_id NUMBER(6),
first_name VARCHAR2(20),
last_name VARCHAR2(25) CONSTRAINT my_emp_last_name_nn NOT NULL,
email VARCHAR2(25) CONSTRAINT my_emp_email_nn NOT NULL,
phone_number VARCHAR2(20),
hire_date DATE DEFAULT SYSDATE CONSTRAINT my_emp_hire_date_nn NOT NULL,
job_id VARCHAR2(10) CONSTRAINT my_emp_job_nn NOT NULL,
salary NUMBER(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)
);

4-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL Data Definition Language Statements

Creating and Modifying an Index With SQL


To create, modify, or drop an index, use the SQL CREATE, ALTER, or DROP INDEX
statement as shown in Example 4–22.

Example 4–22 Creating, Modifying, and Dropping an Index


-- create a new index on the employees table using the email column
CREATE INDEX email_ix
ON employees (email);

-- disable the index


ALTER INDEX email_ix
RENAME TO my_email_ix;

-- drop the index


DROP INDEX my_email_ix;

-- create an index on a single column to make queries faster on that column


CREATE 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 columns
CREATE 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;

Creating and Modifying a Constraint With SQL


To add or a modify a constraint on a table, use the SQL ALTER statement as shown in
Example 4–23.

Example 4–23 Creating and Altering a Constraint


-- add a constraint a new constraint
ALTER TABLE my_employees
ADD CONSTRAINT ...

-- remove the constraint on email in the my_employees table


ALTER TABLE my_employees
DROP UNIQUE (email);

Altering a Table With SQL


To alter a database object use the SQL ALTER statement as shown in Example 4–24.

Example 4–24 Altering a Table


-- add a new column to my_birthdays
ALTER TABLE my_birthdays
ADD (age NUMBER(3));

-- rename the my_employees table

Beta Draft Using SQL 4-17


Using SQL Data Definition Language Statements

ALTER TABLE my_employees RENAME to temp_employees;

Dropping a Table With SQL


To drop (remove) a table from the database use the SQL DROP statement as shown
inExample 4–25. Be very careful when using the DROP statement to remove database
objects.

Example 4–25 Dropping a Table


-- drop tables from the database
-- use caution when use the DROP statement!
DROP TABLE my_birthdays;
DROP TABLE temp_employees;

Creating and Dropping a Sequence


Example 4–26 creates a sequence that can be used with the employees table. The
sequence could also be used with other tables.

Example 4–26 Creating a Sequence


-- create a new sequence to use with the employees table
CREATE SEQUENCE new_employees_seq START WITH 1000 INCREMENT BY 1;

-- to use the sequence, first initialize the sequence with NEXTVAL


SELECT new_employees_seq.NEXTVAL FROM DUAL;

-- after initializing the sequence, use CURRVAL as the next value in the sequence
INSERT 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 statement
SELECT employee_id, last_name FROM employees WHERE last_name = 'Valdivia';

Example 4–27 drops the sequence that you previously created.

Example 4–27 Dropping a Sequence


-- drop the sequence
DROP SEQUENCE new_employees_seq;

Creating and Dropping a Synonym


Example 4–28 creates a synonym that is alias for the employees table.

Example 4–28 Creating a Synonym


-- create a synonym for the employees table
CREATE SYNONYM emps for HR.employees;

-- query the employees table using the emps synonym


SELECT employee_id, last_name FROM emps WHERE employee_id < 105;

4-18 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL Data Definition Language Statements

Example 4–29 drops a synonym.

Example 4–29 Dropping a Synonym


-- drop the synonym
DROP SYNONYM emps;

Beta Draft Using SQL 4-19


Using SQL Data Definition Language Statements

4-20 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
5
Using PL/SQL

The chapter discusses the development with PL/SQL.


This section includes the following topics:
■ Overview of PL/SQL on page 5-1
■ Entering and Executing PL/SQL Code on page 5-2
■ Utilizing the Main Features of PL/SQL on page 5-5
■ Handling PL/SQL Errors on page 5-23

See Also:
■ Oracle Database PL/SQL User's Guide and Reference for detailed
information about PL/SQL.
■ Oracle Database PL/SQL Packages and Types Reference for
information on packages supplied by Oracle.
■ Oracle Database Application Developer's Guide - Fundamentals for
information on dynamic SQL.
■ Oracle Database Application Developer's Guide - Fundamentals for
information on using PL/SQL to develop Web applications.

Overview of PL/SQL
PL/SQL is Oracle's procedural language extension to SQL. It provides a server-side,
stored procedural language that is easy-to-use, seamless with SQL, robust, portable,
and secure.
The PL/SQL compiler and interpreter are embedded in Oracle Database XE, providing
developers with a consistent and leveraged development model on both the client and
the server side. In addition, PL/SQL stored subprograms can be called from Oracle
clients.
PL/SQL enables you to mix SQL statements with procedural constructs. With
PL/SQL, you can create and run PL/SQL program units such as procedures,
functions, and packages. PL/SQL program units generally are categorized as
anonymous blocks, stored subprograms, and packages.
The basic units (procedures, functions, and anonymous blocks) that make up a
PL/SQL program can be nested inside one another.

Beta Draft Using PL/SQL 5-1


Entering and Executing PL/SQL Code

You can place declarations close to where they are used, such as inside a large
subprogram. The declarations are local to the block and cease to exist when the block
completes, helping to avoid cluttered namespaces for variables and procedures.
You can nest blocks in the executable and exception-handling parts of a PL/SQL block
or subprogram, but not in the declarative part. You can define local subprograms in
the declarative part of any block. You can call local subprograms only from the block
in which they are defined.
■ Anonymous block
An anonymous block is a PL/SQL block that appears in your application and is
not named or stored in the database. In many applications, PL/SQL blocks can
appear wherever SQL statements can appear. A PL/SQL block groups related
declarations and statements.
■ Stored or standalone subprogram
A stored or standalone subprogram is a PL/SQL block that Oracle stores in the
database and can be called by name from an application. Subprograms can be
procedures or functions; the difference is that functions return a value when
executed. When you create a stored subprogram, Oracle parses the subprogram
and stores its parsed representation in the database. See Chapter 6, "Using
Subprograms and Packages".
■ Package
A package is a group of subprograms and variable definitions that Oracle stores in
the database. Subprograms and variables in packages can be called from other
packages or subprograms. See Chapter 6, "Using Subprograms and Packages".

Entering and Executing PL/SQL Code


PL/SQL code can be entered and executed from the Script Editor page, the SQL
Commands page, or the SQL*Plus command line.
If you enter PL/SQL code in the SQL Commands page, you save, run, and edit the
code as a SQL Commands module. If you enter PL/SQL code in the Script Editor
page, you save, run, and edit the code as a SQL script text file. If you use SQL*Plus,
simply type in each line of code at the SQL prompt. For information on using
SQL*Plus, see Appendix A, "SQL*Plus".
You can create a text file of the PL/SQL code and run that as a SQL script from the
SQL*Plus command line. The script can be created using a text editor or the Script
Editor page. Using a script makes correcting mistakes much easier because you only
need to make the necessary updates to correct the problem rather than retyping all the
PL/SQL code. For information on running SQL scripts from SQL*Plus, see "Running
Scripts From SQL*Plus" on page A-3.
■ Running PL/SQL Code in the SQL Commands Page on page 5-2
■ Running PL/SQL Code in Script Editor on page 5-3

Running PL/SQL Code in the SQL Commands Page


To enter and runPL/SQL code in the SQL Commands page:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.

5-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Entering and Executing PL/SQL Code

3. Click the SQL Commands icon to display the SQL Commands page.
4. In the SQL Commands page, enter the PL/SQL code and click the Run button to
execute the code.
5. If you want to save the PL/SQL code for future use, click the Save button.
6. In the Name field, enter a name for the saved PL/SQL code. You can also enter an
optional description. Click the Save button to save the SQL.
7. To access saved PL/SQL code, click the Saved SQL tab and select the name of the
saved PL/SQL code that you want to access.

Figure 5–1 SQL Commands Page

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Commands

Running PL/SQL Code in Script Editor


To create and run a script file of PL/SQL code in the SQL Editor page:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.
3. Click the Script Editor icon to display the Script Editor page.

Beta Draft Using PL/SQL 5-3


Entering and Executing PL/SQL Code

4. Click the Create button to create a SQL script.


5. In the Script Name field, enter a name for the script.
6. In the Script Name field, enter a name (my_plsql_block) for the script.
7. In the Script Editor entry area, enter the PL/SQL code shown in Example 5–1.
Note that some of the lines of codes are terminated with a semi-colon (;) and the
entire code unit is terminated with a slash (/).
8. Click the Run button in the Script Editor page to execute the code in the script.
9. Click the Run button in the Run Script page to confirm that you want to run the
script.
10. Click the script (my_plsql_block) in the Manage Scripts page. to display the
results of the script.
11. Select the Detail view and enable all the Show options in the Results page to
display details on the script results.
12. After you completed all the script, you can click the Save button to save the script
file for future use. Note that the .sql extension is appended to the SQL script
name.

Figure 5–2 Creating a Script of PL/SQL Code

For additional information about using SQL Scripts, and "Running SQL Statements in
the Script Editor Page" on page 4-3.

5-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

See Also:
■ Oracle Database Express Edition HTML DB User’s Guide for detailed
information on using SQL Scripts.

Utilizing the Main Features of PL/SQL


PL/SQL combines the data-manipulating power of SQL with the processing power of
procedural languages. You can control program flow with statements like IF and
LOOP. As with other procedural programming languages, you can declare variables,
define procedures and functions, and trap runtime errors.
PL/SQL lets you break complex problems down into easily understandable
procedural code, and reuse this code across multiple applications. When a problem
can be solved through plain SQL, you can issue SQL commands directly inside your
PL/SQL programs, without learning new APIs. PL/SQL's data types correspond with
SQL's column types, making it easy to interchange PL/SQL variables with data inside
a table.
■ Using PL/SQL Block Structure on page 5-5
■ Using Comments on page 5-6
■ Declaring Variables and Constants on page 5-7
■ Using Identifiers in PL/SQL on page 5-8
■ Assigning Values to a Variable With the Assignment Operator on page 5-8
■ Using Literals on page 5-9
■ Declaring and Assigning Variables With DEFAULT or NOT NULL on page 5-11
■ Assigning Values to a Variable With SELECT INTO on page 5-11
■ Inputting and Outputting Data with PL/SQL on page 5-12
■ Using %ROWTYPE and %TYPE Attributes to Declare Datatypes on page 5-12
■ Using PL/SQL Control Structures on page 5-14
■ Using Local PL/SQL Subprograms in PL/SQL Blocks on page 5-17
■ Working With PL/SQL Data Structures on page 5-19
■ Processing Queries with PL/SQL on page 5-21
■ Using Dynamic SQL in PL/SQL on page 5-22
■ Using Bind Variables on page 5-23

Using PL/SQL Block Structure


As Example 5–1 shows, a PL/SQL 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 exception
handling, see "Handling PL/SQL Errors" on page 5-23.
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 in
the executable part. Exceptions raised during execution can be dealt with in the
exception-handling part.

Beta Draft Using PL/SQL 5-5


Utilizing the Main Features of PL/SQL

Note the comments that are added to the PL/SQL code. See "Using Comments" on
page 5-6. Also, not the use of DBMS_OUTPUT.PUT_LINE to display output. See
"Inputting and Outputting Data with PL/SQL" on page 5-12.

Example 5–1 Simple PL/SQL Block


-- the following is an optional declarative part
DECLARE
monthly_salary NUMBER(6);
number_of_days_worked NUMBER(2);
pay_per_day NUMBER(6,2);

-- the following is the executable part, from BEGIN to END


BEGIN
monthly_salary := 2290;
number_of_days_worked := 21;
pay_per_day := monthly_salary/number_of_days_worked;

-- the following displays output from the PL/SQL block


DBMS_OUTPUT.PUT_LINE('The pay per day is ' || TO_CHAR(pay_per_day));

-- the following is an optional exception part that handles errors


EXCEPTION
WHEN ZERO_DIVIDE THEN
pay_per_day := 0;

END;
/

For another example of PL/SQL block structure, see Example 5–8 on page 5-11.

Using Comments
The PL/SQL compiler ignores comments, but you should not. Adding comments to
your program promotes readability and help others understand your code. Generally,
you use comments to describe the purpose and use of each code segment. PL/SQL
supports single-line and multi-line comment styles.
Single-line comments begin with a double hyphen (--) anywhere on a line and extend
to the end of the line. Multi-line comments begin with a slash-asterisk (/*), end with
an asterisk-slash (*/), and can span multiple lines. See Example 5–2.

Example 5–2 Using Comments


DECLARE -- Declare variables here.
monthly_salary NUMBER(6); -- This is the monthly salary.
number_of_days_worked NUMBER(2); -- This is the days in one month.
pay_per_day NUMBER(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/SQL block


DBMS_OUTPUT.PUT_LINE('The pay per day is ' || TO_CHAR(pay_per_day));

EXCEPTION

5-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

/* 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 is
zero before using it as a divisor. */
WHEN ZERO_DIVIDE THEN
pay_per_day := 0; -- set to 0 if divisor equals 0
END;
/

While testing or debugging a program, you might want to disable a line of code. The
following 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.

Declaring Variables and Constants


Variables can have any SQL datatype, such as VARCHAR2, DATE, or NUMBER, or a
PL/SQL-only datatype, such as BOOLEAN or PLS_INTEGER. You can also declare
nested tables, variable-size arrays (varrays for short), and records using the TABLE,
VARRAY, and RECORD composite datatypes. See "Working With PL/SQL Data
Structures" on page 5-19.
Declaring a constant is like declaring a variable except that you must add the keyword
CONSTANT and immediately assign a value to the constant. No further assignments to
the constant are allowed. For an example, see avg_days_worked_month in
Example 5–3.
For example, assume that you want to declare variables for employee data, such as
employee_id to hold 6-digit numbers and active_employee to hold the Boolean
value TRUE or FALSE. You declare these and related employee variables and constants
as shown in Example 5–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 the
PL/SQL block.
You can choose any naming convention for variables that is appropriate for your
application. For example, you could begin each variable name with the v_ prefix to
emphasize that these are variable names.

Example 5–3 Declaring Variables in PL/SQL


DECLARE -- declare the variables in this section
last_name VARCHAR2(30);
first_name VARCHAR2(25);
employee_id NUMBER(6);
active_employee BOOLEAN;
monthly_salary NUMBER(6);
number_of_days_worked NUMBER(2);
pay_per_day NUMBER(6,2);
avg_days_worked_month CONSTANT NUMBER(2) := 21; -- a constant variable
BEGIN
NULL; -- NULL statement does nothing, allows this block to executed and tested
END;
/

Beta Draft Using PL/SQL 5-7


Utilizing the Main Features of PL/SQL

Using Identifiers in PL/SQL


You use identifiers to name PL/SQL program items and units, such as constants,
variables, exceptions, and subprograms. An identifier consists of a letter optionally
followed by more letters, numerals, dollar signs, underscores, and number signs.
The declaration section in Example 5–4 illustrates some valid identifiers. You can see
additional examples of valid identifiers for variable names in Example 5–2 on page 5-6
and Example 5–3 on page 5-7.

Example 5–4 Valid Identifiers for Variables


DECLARE -- all declarations use valid identifiers
x NUMBER;
t2 NUMBER;
phone# VARHCAR2(12);
credit_limit NUMBER;
oracle$number NUMBER;
money$$$tree NUMBER;
SN## VARCHAR2(9);
try_again BOOLEAN;
BEGIN
NULL;
END;
/

Characters such as hyphens, slashes, and spaces are not allowed. For example the
following identifiers are not allowed:
mine&yours is not allowed because of the ampersand
debit-amount is not allowed because of the hyphen
on/off is not allowed because of the slash
user id is not allowed because of the space

You can use upper, lower, or mixed case to write identifiers. PL/SQL is not case
sensitive except within string and character literals. Every character, including dollar
signs, underscores, and number signs, is significant. If the only difference between
identifiers is the case of corresponding letters, PL/SQL considers them the same, as in
the following:
lastname is same as LASTNAME and LastName
LastName is the same as lastname and LASTNAME
LASTNAME is same as lastname and LastName

The size of an identifier cannot exceed 30 characters. Identifiers should be descriptive.


When possible, avoid obscure names such as cpm. Instead, use meaningful names such
as cost_per_thousand.
Some identifiers, called reserved words or keywords, have a special syntactic meaning
to PL/SQL. For example, the words BEGIN and END are reserved. Often, reserved
words and keywords are written in upper case for readability. Neither reserved words
or keywords should be used as identifiers and the use can cause compilation errors.
For information PL/SQL reserved words and keywords, see Oracle Database PL/SQL
User's Guide and Reference.

Assigning Values to a Variable With the Assignment Operator


You can assign values to a variable in several ways. One way uses the assignment
operator (:=), a colon followed by an equal sign, as shown in Example 5–5. You place

5-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

the variable to the left of the operator and an expression, including function calls, to
the right. Note that you can assign a value to a variable when it is declared.

Example 5–5 Assigning Values to Variables With the Assignment Operator


DECLARE -- declare and assiging variables
wages NUMBER(6,2);
hours_worked NUMBER := 40;
hourly_salary NUMBER := 22.50;
bonus NUMBER := 150;
country VARCHAR2(128);
counter NUMBER := 0;
done BOOLEAN := FALSE;
valid_id BOOLEAN;
BEGIN
wages := (hours_worked * hourly_salary) + bonus; -- compute wages
country := 'France'; -- assign a string literal
country := UPPER('Canada'); -- assign an uppercase string literal
done := (counter > 100); -- assign a BOOLEAN, in this case FALSE
valid_id := TRUE; -- assign a BOOLEAN
END;
/

Using Literals
A literal is an explicit numeric, character, string, or BOOLEAN value not represented by
an identifier. For example, 147 is a numeric literal and FALSE is a BOOLEAN literal.

Numeric Literals
Two 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, such
as +6. A real literal is an optionally signed whole or fractional number with a decimal
point, such as -3.14159. PL/SQL considers a number such as 25. to be real even
though it has an integral value.
Numeric literals cannot contain dollar signs or commas, but can be written using
scientific notation. Simply suffix the number with an E (or e) followed by an
optionally signed integer, such as -9.5e-3. E (or e) stands for times ten to the power
of.

Character Literals
A character literal is an individual character enclosed by single quotes (apostrophes),
such as '(' or '7'. Character literals include all the printable characters in the
PL/SQL character set: letters, numerals, spaces, and special symbols.
PL/SQL is case sensitive within character literals. For example, PL/SQL considers the
character literals 'Z' and 'z' to be different. Also, the character literals '0'..'9' are
not equivalent to integer literals but can be used in arithmetic expressions because
they are implicitly convertible to integers.

String Literals
A character value can be represented by an identifier or explicitly written as a string
literal, which is a sequence of zero or more characters enclosed by single quotes, such
as 'Hello, world!' and '$1,000,000'. All string literals except the null string ('')
have datatype CHAR.

Beta Draft Using PL/SQL 5-9


Utilizing the Main Features of PL/SQL

PL/SQL is case sensitive within string literals. For example, PL/SQL considers the
following 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 marks
within a complicated literal, particularly one that represents a SQL statement, can be
tricky. You can also define your own delimiter characters for the literal. You choose a
character that is not present in the string, and then do not need to escape other single
quotation marks inside the literal, such as the following string.
q'!I'm using the exclamation point for a delimiter here.!'

BOOLEAN Literals
BOOLEAN literals are the predefined values TRUE, FALSE, and NULL. NULL stands for a
missing, unknown, or inapplicable value. Remember, BOOLEAN literals are values, not
strings. For example, TRUE is no less a value than the number 25.

Datetime Literals
Datetime literals have various formats depending on the datetime datatype, such as
'14-SEP-05' or '14-SEP-05 09:24:04 AM'.
Example 5–6 shows some examples of the use of literals.

Example 5–6 Using Literals


DECLARE -- declare and assign variables
number1 PLS_INTEGER := 32000; -- numeric literal
number2 NUMBER(8,3);
char1 VARCHAR2(1) := 'x'; -- character literal
char2 VARCHAR2(1000);
boolean BOOLEAN := TRUE; -- BOOLEAN literal
date1 DATE := '11-AUG-2005'; -- DATE literal
time1 TIMESTAMP;
time2 TIMESTAMP WITH TIME ZONE;
BEGIN
number2 := 3.125346e3; -- numeric literal
number2 := -8300.00; -- numeric literal
number2 := -14; -- numeric literal
char2 := q'!I'm writing an example string.!'; -- string literal
char2 := 'I''m writing an example string.'; -- need two single quotes here
time1 := '11-AUG-2005 11:01:01 PM'; -- TIMESTAMP literal
time2 := '11-AUG-2005 09:26:56.66 PM +02:00';
END;
/

See Also:
■ Oracle Database SQL Reference for information on the syntax for
literals and the date and time types.
■ Oracle Database Application Developer's Guide - Fundamentals for
examples of performing date and time arithmetic.
■ Oracle Database PL/SQL User's Guide and Reference for information
on using literals with PL/SQL.

5-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

Declaring and Assigning Variables With DEFAULT or NOT NULL


You can use the keyword DEFAULT instead of the assignment operator to initialize
variables. Use DEFAULT for variables that have a typical value. Use the assignment
operator 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 so
that assigning a NULL raises an error. The NOT NULL constraint must be followed by an
initialization clause.
In Example 5–7 the declaration for avg_days_worked_month uses the DEFAULT to
assign a value of 21 and the declarations for active_employee and monthly_
salary use the NOT NULL constraint.

Example 5–7 Using DEFAULT and NOT NULL


DECLARE -- declare and assign variables
last_name VARCHAR2(30);
first_name VARCHAR2(25);
employee_id NUMBER(6);
active_employee BOOLEAN NOT NULL := TRUE; -- value cannot be NULL
monthly_salary NUMBER(6) NOT NULL := 2000; -- value cannot be NULL
number_of_days_worked NUMBER(2);
pay_per_day NUMBER(6,2);
employee_count NUMBER(6) := 0;
avg_days_worked_month NUMBER(2) DEFAULT 21; -- assign a default value
BEGIN
NULL; -- NULL statement does nothing, allows this block to executed and tested
END;
/

Assigning Values to a Variable With SELECT INTO


Another way to assign values to a variable is by selecting (or fetching) database values
into it. In Example 5–8, 10% of an employee's salary is selected into the bonus
variable. Now you can use the bonus variable in another computation or insert its
value into a database table.
In the example, DBMS_OUTPUT.PUT_LINE is used to display output from the PL/SQL
program. For more information, see "Inputting and Outputting Data with PL/SQL" on
page 5-12.

Example 5–8 Assigning Values to Variables by SELECTing INTO


DECLARE -- declare and assign values
bonus NUMBER(8,2);
emp_id NUMBER(6) := 100; -- declare variable and assign a test value
BEGIN
-- retreive a value from the employees table and assign to the bonus variable
SELECT salary * 0.10 INTO bonus FROM employees
WHERE employee_id = emp_id;
DBMS_OUTPUT.PUT_LINE ( 'Employee: ' || TO_CHAR(emp_id)
|| ' Bonus: ' || TO_CHAR(bonus) ); -- display data
END;
/

Beta Draft Using PL/SQL 5-11


Utilizing the Main Features of PL/SQL

Inputting and Outputting Data with PL/SQL


Most PL/SQL input and output is through SQL statements, to store data in database
tables or query those tables. All other PL/SQL I/O is done through APIs that interact
with other programs. For example, the DBMS_OUTPUT package has procedures such as
PUT_LINE. To see the result outside of PL/SQL requires another program, such as
SQL*Plus, to read and display the data passed to DBMS_OUTPUT. SQL*Plus does not
display DBMS_OUTPUT data unless you first issue the SQL*Plus command SET
SERVEROUTPUT ON. For information on SQL*Plus SET command, see "SQL*Plus SET
Commands" on page A-3.
Example 5–9 show the use of DBMS_OUTPUT.PUTLINE. Note the use of SET
SERVEROUTPUT ON to enable output.

Example 5–9 Using DBMS_OUTPUT to Display Output


-- enable SERVEROUTPUT in SQL*Plus to display with DBMS_OUTPUT.PUT_LINE
-- this enables SERVEROUTPUT for this SQL*Plus session only
SET SERVEROUTPUT ON

DECLARE
answer VARCHAR2(20); -- declare a variable
BEGIN
-- assign a value to a variable
answer := 'Maybe';
-- use PUT_LINE to display data from the PL/SQL block
DBMS_OUTPUT.PUT_LINE( 'The answer is: ' || answer );
END;
/

The DBMS_OUTPUT package is a predefined Oracle package. For information about


Oracle supplied packages, see "Oracle Product-Specific Packages" on page 6-17.

See Also:
■ SQL*Plus User's Guide and Reference for information SQL*Plus
commands.
■ Oracle Database PL/SQL Packages and Types Reference.for
information about Oracle supplied packages.

Using %ROWTYPE and %TYPE Attributes to Declare Datatypes


As part of the declaration for each PL/SQL variable, you declare its datatype. Usually,
this datatype is one of the types shared between PL/SQL and SQL, such as NUMBER or
VARCHAR2. For easier maintenance of code that interacts with the database, you can
also use the special qualifiers %ROWTYPE and %TYPE to declare variables that hold
table columns or table rows.

Using the %ROWTYPE Attribute to Declare Variables


For 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/SQL
record is the datatype that stores the same information as a row in a table.
In PL/SQL, records are used to group data. A record consists of a number of related
fields in which data values can be stored. The record can store an entire row of data
selected from the table or fetched from a cursor or cursor variable. For information on
records, see "Using Records" on page 5-21.

5-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

Columns in a row and corresponding fields in a record have the same names and
datatypes. In Example 5–10, you declare a record named emp_rec. Its fields have the
same names and datatypes as the columns in the employees table. You use dot
notation to reference fields, such as emp_rec.last_name.
In Example 5–10, SELECT is used to store row information from the employees table
into the emp_rec record. When you execute the SELECT INTO statement, the value in
the first_name column of the employees table is assigned to the first_name field
of emp_rec, the value in the last_name column is assigned to the last_name field
of emp_rec, and so on.

Example 5–10 Using %ROWTYPE with a Record


DECLARE -- declare variables
-- declare record variable that represents a row fetched from the employees table
emp_rec employees%ROWTYPE; -- declare variable with %ROWTYPE attribute
BEGIN
SELECT * INTO emp_rec FROM EMPLOYEES WHERE employee_id = 120; -- retrieve record
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emp_rec.first_name || ' '
|| emp_rec.last_name); -- display
END;
/

Declaring variables with %ROWTYPE has several advantages. First, you do not need to
know the exact datatype of the table columns. Second, if you change the database
definition of any of the table columns, the datatypes associated with the %ROWTYPE
declaration change accordingly at run time.
For more information %ROWTYPE, see Oracle Database PL/SQL User's Guide and
Reference..

Using the %TYPE Attribute to Declare Variables


The %TYPE attribute provides the datatype of a variable or table column. This is
particularly useful when declaring variables that will hold values of a table column.
For example, suppose you want to declare variables as the same datatype as columns
employee_id and last_name in table employees. To declare variables named
empid and emplname that have the same datatype as the table columns, use dot
notation and the %TYPE attribute. See Example 5–11.

Example 5–11 Using %TYPE With Table Columns


DECLARE -- declare variables using %TYPE attribute
empid employees.employee_id%TYPE; -- employee_id datatype is NUMBER(6)
emplname employees.last_name%TYPE; -- last_name datatype is VARCHAR2(25)
BEGIN
empid := 100301; -- this is OK because it fits in NUMBER(6)
-- empid := 3018907; -- this is too large and will cause an overflow
emplname := 'Patel'; -- this is OK because it fits in VARCHAR2(25)
DBMS_OUTPUT.PUT_LINE('Employee Id: ' || empid); -- display data
DBMS_OUTPUT.PUT_LINE('Employee name: ' || emplname); -- display data
END;
/

Declaring variables with %TYPE has two advantages. First, you need not know the
exact datatype of the table columns. Second, if you change the database definition of
columns, such as employee_id or last_name, the datatypes of empid and
emplname in Example 5–11 change accordingly at run time.
For more information %TYPE, see Oracle Database PL/SQL User's Guide and Reference.

Beta Draft Using PL/SQL 5-13


Utilizing the Main Features of PL/SQL

Using PL/SQL Control Structures


Control structures are the most important PL/SQL extension to SQL. Not only does
PL/SQL let you manipulate Oracle 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.

Conditional Control With IF-THEN


Often, it is necessary to take alternative actions depending on circumstances. The
IF-THEN statement lets you execute a sequence of statements conditionally. The forms
of the statement can be IF-THEN, IF-THEN-ELSE, or IF-THEN-ELSEIF-ELSE. The
IF clause checks a condition, the THEN clause defines what to do if the condition is
true and the ELSE clause defines what to do if the condition is false or null.
Example 5–12 shows a simple use of the IF-THEN statement.

Example 5–12 Using a Simple IF-THEN Statement


DECLARE
sales NUMBER(8,2) := 10100;
quota NUMBER(8,2) := 10000;
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120; -- use employee 120 for testing
BEGIN
IF sales > (quota + 200) THEN
bonus := (sales - quota)/4;
UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;
END IF;
END;
/

Example 5–13 shows the use of IF-THEN-ELSEIF-ELSE to determine the salary raise
an employee receives based on the hire date of the employee.

Example 5–13 Using the IF-THEN-ELSEIF Statement


DECLARE
bonus NUMBER(6,2);
emp_id NUMBER(6) := 120;
hire_date DATE;
BEGIN
SELECT hire_date INTO hire_date FROM employees WHERE employee_id = 120;
IF hire_date > TO_DATE('01-JAN-98') THEN
bonus := 500;
ELSIF hire_date > TO_DATE('01-JAN-96') THEN
bonus := 1000;
ELSE
bonus := 1500;
END IF;
UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;
END;
/

Conditional Control With the CASE Statement


To choose among several values or courses of action, you can use CASE constructs. The
CASE expression evaluates a condition and returns a value for each case. The case
statement evaluates a condition and performs an action, such as an entire PL/SQL

5-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

block, for each case. When possible, rewrite lengthy IF-THEN-ELSIF statements as
CASE statements because the CASE statement is more readable and more efficient.
Example 5–14 shows a simple CASE statement.

Example 5–14 Using the CASE-WHEN Statement


DECLARE
grade CHAR(1);
BEGIN
grade := 'B';
CASE grade
WHEN '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 5–15 determines the salary raise an employee receives based on the current
salary of the employee and the job Id. This complex example combines the CASE
expression with IF-THEN-ELSE statements.

Example 5–15 Using the IF-THEN_ELSE and CASE Statement


DECLARE -- declare variables
jobid employees.job_id%TYPE;
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 sal
SELECT job_id, salary INTO jobid, sal from employees WHERE employee_id = empid;
CASE -- check for conditions
WHEN jobid = 'PU_CLERK' THEN
IF sal < 3000 THEN sal_raise := .08;
ELSE sal_raise := .07;
END IF;
WHEN jobid = 'SH_CLERK' THEN
IF sal < 4000 THEN sal_raise := .06;
ELSE sal_raise := .05;
END IF;
WHEN jobid = 'ST_CLERK' THEN
IF sal < 3500 THEN sal_raise := .04;
ELSE sal_raise := .03;
END IF;
ELSE
BEGIN
-- if no conditions met, then the following
DBMS_OUTPUT.PUT_LINE('No raise for this job: ' || jobid);
END;
END CASE;
UPDATE employees SET salary = salary + salary * sal_raise
WHERE employee_id = empid; -- update a record in the employees table
COMMIT;
END;
/

Beta Draft Using PL/SQL 5-15


Utilizing the Main Features of PL/SQL

A sequence of statements that uses query results to select alternative actions is


common in database applications. Another common sequence inserts or deletes a row
only if an associated entry is found in another table. You can bundle these common
sequences into a PL/SQL block using conditional logic.

Iterative Control With LOOPs


LOOP statements let you execute a sequence of statements multiple times. You place
the keyword LOOP before the first statement in the sequence and the keywords END
LOOP after the last statement in the sequence.
The FOR-LOOP statement lets you specify a range of integers, then execute a sequence
of statements once for each integer in the range. In Example 5–16 the loop displays the
number and the square of the number for numbers 1 to 10. inserts 100 numbers, square
roots, squares, and the sum of squares into a database table:

Example 5–16 Using the FOR-LOOP


BEGIN
-- use a FOR loop to process a series of numbers
FOR i in 1..10 LOOP
DBMS_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, the
sequence of statements is executed, then control resumes at the top of the loop. If the
condition is false or null, the loop is bypassed and control passes to the next statement.
In Example 5–17, you find the first employee who has a salary over $15000 and is
higher in the chain of command than employee 120:

Example 5–17 Using WHILE-LOOP for Control


-- create a temporary table for this example
CREATE TABLE temp (tempid NUMBER(6), tempsal NUMBER(8,2), tempname VARCHAR2(25));
DECLARE -- declare variables
sal employees.salary%TYPE := 0;
mgr_id employees.manager_id%TYPE;
lname employees.last_name%TYPE;
starting_empid employees.employee_id%TYPE := 120;
BEGIN
SELECT manager_id INTO mgr_id FROM employees
WHERE employee_id = starting_empid; -- retrieve data from employees
-- use WHILE LOOP to process data
WHILE sal <= 15000 LOOP -- loop until sal > 15000
SELECT salary, manager_id, last_name INTO sal, mgr_id, lname
FROM employees WHERE employee_id = mgr_id;
END LOOP;
INSERT INTO temp VALUES (NULL, sal, lname); -- insert NULL for tempid in table
COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
INSERT INTO temp VALUES (NULL, NULL, 'Not found'); -- insert NULLs
COMMIT;
END;
/
-- display rows in table temp

5-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

SELECT * FROM temp;


-- drop temporary table
DROP TABLE temp;

The EXIT-WHEN statement lets you complete a loop if further processing is impossible
or undesirable. When the EXIT statement is encountered, the condition in the WHEN
clause is evaluated. If the condition is true, the loop completes and control passes to
the next statement. In Example 5–18, the loop completes when the value of total
exceeds 25,000:

Example 5–18 Using the EXIT-WHEN Statement


DECLARE -- declare and assign values to variables
total NUMBER(9) := 0;
counter NUMBER(6) := 0;
BEGIN
LOOP
counter := counter + 1; -- increment counter variable
total := total + counter * counter; -- compute total
-- exit loop when condition is true
EXIT WHEN total > 25000; -- LOOP until condition is met
END LOOP;
DBMS_OUTPUT.PUT_LINE('Counter: ' || TO_CHAR(counter) || ' Total: ' || TO_
CHAR(total)); -- display data
END;
/

Sequential Control With GOTO


The GOTO statement lets you branch to a label unconditionally. The label, an
undeclared identifier enclosed by double angle brackets, must precede an executable
statement or a PL/SQL block. When executed, the GOTO statement transfers control to
the labeled statement or block, as shown in Example 5–19.

Example 5–19 Using the GOTO Statement


DECLARE -- declare variables
p VARCHAR2(30);
n PLS_INTEGER := 37; -- test any integer > 2 for prime, here 37
BEGIN
-- loop through divisors to determine if a prime number
FOR j in 2..ROUND(SQRT(n))
LOOP
IF n MOD j = 0 THEN -- test for prime
p := ' is NOT a prime number'; -- not a prime number
GOTO print_now;
END IF;
END LOOP;
p := ' is a prime number';
<<print_now>>
DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p); -- display data
END;
/

Using Local PL/SQL Subprograms in PL/SQL Blocks


Subprograms are named PL/SQL blocks that can be called with a set of parameters
from inside a PL/SQL block. PL/SQL has two types of subprograms: procedures and
functions.

Beta Draft Using PL/SQL 5-17


Utilizing the Main Features of PL/SQL

Example 5–20 is an example of a declaration of a PL/SQL procedure in a PL/SQL


block. Note that the v1 and v2 variables are declared as IN OUT parameters to a
subprogram. An IN OUT parameter passes an initial value that is read inside a
subprogram and then returns a value that has been updated in the subprogram.

Example 5–20 Declaring a Procedure With IN OUT Parameters


DECLARE -- declare variables and subprograms
fname VARCHAR2(20) := 'randall';
lname VARCHAR2(25) := 'dexter';
PROCEDURE upper_name ( v1 IN OUT VARCHAR2, v2 IN OUT VARCHAR2) AS
BEGIN
v1 := UPPER(v1); -- change the string to uppercase
v2 := UPPER(v2); -- change the string to uppercase
END;
BEGIN
DBMS_OUTPUT.PUT_LINE(fname || ' ' || lname ); -- display initial values
upper_name (fname, lname); -- call the procedure with parameters
DBMS_OUTPUT.PUT_LINE(fname || ' ' || lname ); -- display new values
END;
/

Example 5–21 is an example of a declaration of a PL/SQL function in a PL/SQL 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 IN
parameters to a subprogram. An IN parameter passes an initial value that is read
inside a subprogram. Any update to the value of the parameter inside the subprogram
is not accessible outside the subprogram.

Example 5–21 Declaring a Function With IN Parameters


DECLARE -- declare variables and subprograms
fname VARCHAR2(20) := 'randall';
lname VARCHAR2(25) := 'dexter';
FUNCTION upper_name ( v1 IN VARCHAR2, v2 IN VARCHAR2)
RETURN VARCHAR2 AS
v3 VARCHAR2(45); -- this variable is local to the function
BEGIN
-- build a string that will be returned as the function value
v3 := v1 || ' + ' || v2 || ' = ' || UPPER(v1) || ' ' || UPPER(v2);
RETURN v3; -- return the value of v3
END;
BEGIN
-- call the function and display results
DBMS_OUTPUT.PUT_LINE(upper_name (fname, lname));
END;
/

In Example 5–22, both a variable and a numeric literal are passed as a parameter to a
more complex procedure.

Example 5–22 Declaring a Complex Procedure in a PL/SQL Block


DECLARE -- declare variables and subprograms
empid NUMBER;
PROCEDURE avg_min_max_sal (empid IN NUMBER) IS
jobid VARCHAR2(10);
avg_sal NUMBER;
min_sal NUMBER;
max_sal NUMBER;

5-18 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

BEGIN
-- determine the job Id for the employee
SELECT job_id INTO jobid FROM employees WHERE employee_id = empid;
-- calculate the average, minimum, and maximum salaries for that job Id
SELECT AVG(salary), MIN(salary), MAX(salary) INTO avg_sal, min_sal, max_sal
FROM employees WHERE job_id = jobid;
-- display data
DBMS_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 Ids
empid := 125;
avg_min_max_sal(empid);
avg_min_max_sal(112);
END;
/

Subprograms can also be declared in packages. For example of a subprogram


declaration in a package, see Example 6–6 on page 6-14. You can create subprograms
that are stored in the database. These subprograms can be called from other
subprograms, packages, and SQL statements. See Chapter 6, "Using Subprograms and
Packages".

Working With PL/SQL Data Structures


Data structure are composite datatypes that let you work with the essential properties
of data without being too involved with details. After you design a data structure, you
can focus on designing algorithms that manipulate the data structure.

Using Cursors
A cursor is a name for a specific private SQL area in which information for processing
the specific statement is kept. PL/SQL uses both implicit and explicit cursors. PL/SQL
implicitly declares a cursor for all SQL data manipulation statements on a set of rows,
including queries that return only one row. You can explicitly declare a cursor for one
row, as shown in Example 5–10 on page 5-13 declares an explicit cursor.
For queries that return more than one row, you can explicitly declare a cursor to
process the rows individually. See Example 5–23.

Example 5–23 Fetching With a Cursor


DECLARE -- declare variables and cursors
jobid employees.job_id%TYPE; -- variable for job_id
lastname employees.last_name%TYPE; -- variable for last_name
CURSOR c1 IS SELECT last_name, job_id FROM employees
WHERE job_id LIKE '%CLERK';
employees employees%ROWTYPE; -- record variable for row
CURSOR c2 is SELECT * FROM employees
WHERE job_id LIKE '%MAN' OR job_id LIKE '%MGR';
BEGIN
OPEN c1; -- open the cursor before fetching
LOOP
FETCH c1 INTO lastname, jobid; -- fetches 2 columns into variables

Beta Draft Using PL/SQL 5-19


Utilizing the Main Features of PL/SQL

EXIT WHEN c1%NOTFOUND;


DBMS_OUTPUT.PUT_LINE( RPAD(lastname, 25, ' ') || jobid );
END LOOP;
CLOSE c1;
DBMS_OUTPUT.PUT_LINE( '-------------------------------------' );
OPEN c2;
LOOP
FETCH c2 INTO employees; -- fetches entire row into the employees record
EXIT WHEN c2%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( RPAD(employees.last_name, 25, ' ') ||
employees.job_id );
END LOOP;
CLOSE c2;
END;
/

In Example 5–23, LIKE is used to specify the records to return with the query. For
information on LIKE, see "Restricting Data Using the WHERE Clause" on page 4-6.
For information on managing cursors with PL/SQL, see Oracle Database PL/SQL User's
Guide and Reference.

Using Collections
PL/SQL collection types let you declare high-level datatypes similar to arrays, sets,
and hash tables found in other languages. In PL/SQL, array types are known as
varrays (short for variable-size arrays), set types are known as nested tables, and hash
table types are known as associative arrays. Each kind of collection is an ordered
group of elements, all of the same type. Each element has a unique subscript that
determines its position in the collection. When declaring collections, you use a TYPE
definition.
To reference an element, use subscript notation with parentheses, as shown in
Example 5–24.

Example 5–24 Using a PL/SQL Collection Type


DECLARE -- declare variables
TYPE jobids_array IS VARRAY(12) OF VARCHAR2(10); -- declare VARRAY
jobids jobids_array; -- declare a variable of type jobids_array
howmany NUMBER; -- declare a variable to hold employee count
BEGIN
-- initialize the arrary with some job Id values
jobids := 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 array
SELECT 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 arbitrary


numbers of elements.You can use collections to move data into and out of database
tables using high-performance language features known as bulk SQL.

5-20 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL

See Also:
■ Oracle Database PL/SQL User's Guide and Reference for information
on PL/SQL collections.

Using Records
Records are composite data structures whose fields can have different datatypes. You
can use records to hold related items and pass them to subprograms with a single
parameter. When declaring records, you use the TYPE definition.
Example 5–25 shows how are records are declared.

Example 5–25 Declaring a Record Type


DECLARE -- declare RECORD type variables
TYPE timerec IS RECORD (hours SMALLINT, minutes SMALLINT);
TYPE meetin_typ IS RECORD (
date_held DATE,
duration timerec, -- nested record
location VARCHAR2(20),
purpose VARCHAR2(50));
BEGIN
-- NULL does nothing but allows unit to be compiled and tested
NULL;
END;
/

You can use the %ROWTYPE attribute to declare a record that represents a row in a table
or a row from a query result set, without specifying the names and types for the fields.
When using %ROWTYPE, the record type definition is implied and the TYPE keyword is
not necessary, as shown in Example 5–26.

Example 5–26 Using %ROWTYPE with a Cursor


DECLARE -- declare variables
CURSOR c1 IS
SELECT * FROM employees
WHERE employee_id = 120; -- declare cursor
-- declare record variable that represents a row fetched from the employees table
employee_rec c1%ROWTYPE; -- declare variable with %ROWTYPE attribute
BEGIN
-- open the explicit cursor c1 and use it to fetch data into employee_rec
OPEN c1;
FETCH c1 INTO employee_rec; -- retrieve record
DBMS_OUTPUT.PUT_LINE('Employee name: ' || employee_rec.last_name); -- display
END;
/

See Also:
■ Oracle Database PL/SQL User's Guide and Reference for information
on PL/SQL records.

Processing Queries with PL/SQL


Processing a SQL query with PL/SQL 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/SQL program issues a query and processes
the rows from the result set as shown in Example 5–27.

Beta Draft Using PL/SQL 5-21


Utilizing the Main Features of PL/SQL

Example 5–27 Processing Query Results in a LOOP


BEGIN
-- use values from SELECT for FOR LOOP processing
FOR someone IN (SELECT * FROM employees WHERE employee_id < 120 )
LOOP
DBMS_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 process
precisely by using individual statements to perform the query, retrieve data, and finish
processing.

Using Dynamic SQL in PL/SQL


PL/SQL supports both dynamic and static SQL. Dynamic SQL enables you to build
SQL statements dynamically at runtime while static SQL statements are known in
advance. You can create more general purpose, flexible applications by using dynamic
SQL because the full text of a SQL statement may be unknown at compilation. For
additional information about dynamic SQL, see Oracle Database Application Developer's
Guide - Fundamentals.
To process most dynamic SQL statements, you use the EXECUTE IMMEDIATE
statement. To process a multi-row query (SELECT statement), you use the OPEN-FOR,
FETCH, and CLOSE statements.
Example 5–28 illustrates several uses of dynamic SQL.

Example 5–28 Examples of Dynamic SQL


-- create a standalone procedure
CREATE OR REPLACE PROCEDURE raise_emp_salary (column_value NUMBER,
emp_column VARCHAR2, amount NUMBER) IS
column VARCHAR2(30);
sql_stmt VARCHAR2(200);
BEGIN
-- determine if a valid column name has been given as input
SELECT COLUMN_NAME INTO column FROM USER_TAB_COLS
WHERE 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 SQL%ROWCOUNT > 0 THEN
DBMS_OUTPUT.PUT_LINE('Salaries have been updated for: ' || emp_column
|| ' = ' || column_value);
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('Invalid Column: ' || emp_column);
END raise_emp_salary;
/

DECLARE
plsql_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;

5-22 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Handling PL/SQL Errors

EXECUTE IMMEDIATE 'BEGIN raise_emp_salary(:cvalue, :cname, :amt); END;'


USING 112, 'EMPLOYEE_ID', 10;
END;
/

DECLARE
sql_stmt VARCHAR2(200);
column VARCHAR2(30) := 'DEPARTMENT_ID';
dept_id NUMBER(4) := 46;
dept_name VARCHAR2(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 SQL_TRACE TRUE';
EXECUTE IMMEDIATE 'DROP TABLE bonus';
END;
/
-- rollback the changes
ROLLBACK;
-- delete the procedure
DROP PROCEDURE raise_emp_salary;

Using Bind Variables


When you embed an INSERT, UPDATE, DELETE, or SELECT SQL statement directly in
your PL/SQL code, PL/SQL turns the variables in the WHERE and VALUES clauses into
bind variables automatically. Oracle can reuse these SQL statement each time the same
code is executed. To run similar statements with different variable values, you can save
parsing overhead by calling a stored procedure that accepts parameters, then issues
the statements with the parameters substituted in the appropriate places.
You do need to specify bind variables with dynamic SQL, in clauses like WHERE and
VALUES where you normally use variables. Instead of concatenating literals and
variable values into a single string, replace the variables with the names of bind
variables (prefixed by a colon) and specify the corresponding PL/SQL variables with
the USING clause. Using the USING clause, instead of concatenating the variables into
the string, reduces parsing overhead and lets Oracle reuse the SQL statements.
In Example 5–28, :1 and :2 are bind variables for amount and column_value. In the
same example, there are additional bind variables, such as :cvalue, :cname, and
:amt.

Handling PL/SQL Errors


PL/SQL makes it easy to detect and process error conditions known as exceptions.
When an error occurs, an exception is raised: normal execution stops and control
transfers to special exception-handling code, which comes at the end of any PL/SQL
block. Each different exception is processed by a particular exception handler.
PL/SQL's exception handling is different from the manual checking you might be
used to from C programming, where you insert a check to make sure that every

Beta Draft Using PL/SQL 5-23


Handling PL/SQL Errors

operation succeeded. 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 conditions
involving variables or database operations. For example, if you try to divide a number
by zero, PL/SQL raises the predefined exception ZERO_DIVIDE automatically. See
"Summary of Predefined PL/SQL Exceptions" on page 5-24.
You can declare exceptions of your own, for conditions that you decide are errors, or to
correspond to database errors that normally result in ORA- error messages. When you
detect a user-defined error condition, you execute a RAISE statement. See "Declaring
PL/SQL Exceptions" on page 5-26.
This section includes the following topics:
■ Summary of Predefined PL/SQL Exceptions on page 5-24
■ Using the Exception Handler on page 5-25
■ Declaring PL/SQL Exceptions on page 5-26
■ Scope Rules for PL/SQL Exceptions on page 5-26
■ Continuing After an Exception is Raised on page 5-27

Summary of Predefined PL/SQL Exceptions


An internal exception is raised automatically if your PL/SQL program violates an
Oracle rule or exceeds a system-dependent limit. PL/SQL predefines some common
Oracle errors as exceptions. For example, PL/SQL raises the predefined exception NO_
DATA_FOUND if a SELECT INTO statement returns no rows.
To handle unexpected Oracle errors, you can use the OTHERS handler. Within this
handler, you can call the functions SQLCODE and SQLERRM to return the Oracle error
code and message text.
PL/SQL declares predefined exceptions globally in package STANDARD. You need not
declare them yourself. You can write handlers for predefined exceptions using the
names in Table 5–1.

Table 5–1 Predefined PL/SQL Exceptions


Exception Description
ACCESS_INTO_NULL A program attempts to assign values to the attributes of an uninitialized object
CASE_NOT_FOUND None of the choices in the WHEN clauses of a CASE statement is selected, and
there is no ELSE clause.
COLLECTION_IS_NULL A program attempts to apply collection methods other than EXISTS to an
uninitialized nested table or varray, or the program attempts to assign values to
the elements of an uninitialized nested table or varray.
CURSOR_ALREADY_OPEN A program attempts to open an already open cursor. A cursor must be closed
before it can be reopened. A cursor FOR loop automatically opens the cursor to
which it refers, so your program cannot open that cursor inside the loop.
DUP_VAL_ON_INDEX A program attempts to store duplicate values in a column that is constrained by
a unique index.
INVALID_CURSOR A program attempts a cursor operation that is not allowed, such as closing an
unopened cursor.

5-24 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Handling PL/SQL Errors

Table 5–1 (Cont.) Predefined PL/SQL Exceptions


Exception Description
INVALID_NUMBER n a SQL statement, the conversion of a character string into a number fails
because the string does not represent a valid number. (In procedural statements,
VALUE_ERROR is raised.) This exception is also raised when the LIMIT-clause
expression in a bulk FETCH statement does not evaluate to a positive number.
LOGIN_DENIED A program attempts to log on to Oracle with an invalid username or password.
NO_DATA_FOUND A SELECT INTO statement returns no rows, or your program references a
deleted element in a nested table or an uninitialized element in an index-by
table.
Because this exception is used internally by some SQL functions to signal
completion, you should not rely on this exception being propagated if you raise
it within a function that is called as part of a query.
NOT_LOGGED_ON A program issues a database call without being connected to Oracle.
PROGRAM_ERROR PL/SQL has an internal problem.
ROWTYPE_MISMATCH The host cursor variable and PL/SQL cursor variable involved in an
assignment have incompatible return types. When an open host cursor variable
is passed to a stored subprogram, the return types of the actual and formal
parameters must be compatible.
SELF_IS_NULL A program attempts to call a MEMBER method, but the instance of the object
type has not been initialized. The built-in parameter SELF points to the object,
and is always the first parameter passed to a MEMBER method.
STORAGE_ERROR PL/SQL runs out of memory or memory has been corrupted.
SUBSCRIPT_BEYOND_COUNT A program references a nested table or varray element using an index number
larger than the number of elements in the collection.
SUBSCRIPT_OUTSIDE_LIMIT A program references a nested table or varray element using an index number
(-1 for example) that is outside the legal range.
SYS_INVALID_ROWID The conversion of a character string into a universal rowid fails because the
character string does not represent a valid rowid.
TIMEOUT_ON_RESOURCE A time out occurs while Oracle is waiting for a resource.
TOO_MANY_ROWS A SELECT INTO statement returns more than one row.
VALUE_ERROR An arithmetic, conversion, truncation, or size-constraint error occurs. For
example, when your program selects a column value into a character variable, if
the value is longer than the declared length of the variable, PL/SQL aborts the
assignment and raises VALUE_ERROR. In procedural statements, VALUE_ERROR
is raised if the conversion of a character string into a number fails. (In SQL
statements, INVALID_NUMBER is raised.)
ZERO_DIVIDE A program attempts to divide a number by zero.

Using the Exception Handler


Using exceptions for error handling has several advantages. With exceptions, you can
reliably handle potential errors from many statements with a single exception handler:

Example 5–29 Managing Multiple Errors With a Single Exception Handler


DECLARE -- declare variables
emp_column VARCHAR2(30) := 'last_name';
table_name VARCHAR2(30) := 'emp'; -- set value to raise error
temp_var VARCHAR2(30);
BEGIN
temp_var := emp_column;
SELECT COLUMN_NAME INTO temp_var FROM USER_TAB_COLS

Beta Draft Using PL/SQL 5-25


Handling PL/SQL Errors

WHERE TABLE_NAME = 'EMPLOYEES' AND COLUMN_NAME = UPPER(emp_column);


-- processing here
temp_var := table_name;
SELECT OBJECT_NAME INTO temp_var FROM USER_OBJECTS
WHERE OBJECT_NAME = UPPER(table_name) AND OBJECT_TYPE = 'TABLE';
-- processing here
EXCEPTION
WHEN NO_DATA_FOUND THEN -- catches all 'no data found' errors
DBMS_OUTPUT.PUT_LINE ('No Data found for SELECT on ' || temp_var);
END;
/

Declaring PL/SQL Exceptions


Exceptions can be declared only in the declarative part of a PL/SQL block,
subprogram, or package. You declare an exception by introducing its name, followed
by the keyword EXCEPTION. In Example 5–30, you declare an exception named
past_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 error
condition, not a data item. Unlike variables, exceptions cannot appear in assignment
statements or SQL statements. However, the same scope rules apply to variables and
exceptions.

Scope Rules for PL/SQL Exceptions


You cannot declare an exception twice in the same block. You can, however, declare the
same exception in two different blocks.
Exceptions declared in a block are considered local to that block and global to all its
sub-blocks. Because a block can reference only local or global exceptions, enclosing
blocks cannot reference exceptions declared in a sub-block.
If you redeclare a global exception in a sub-block, the local declaration prevails. The
sub-block cannot reference the global exception, unless the exception is declared in a
labeled block and you qualify its name with the block label:
block_label.exception_name
Example 5–30 illustrates the scope rules:

Example 5–30 Scope of PL/SQL Exceptions


DECLARE
past_due EXCEPTION;
acct_num NUMBER;
BEGIN
DECLARE ---------- sub-block begins
past_due EXCEPTION; -- this declaration prevails
acct_num NUMBER;
due_date DATE := SYSDATE - 1; -- set on purpose to raise exception
todays_date DATE := SYSDATE;
BEGIN
IF due_date < todays_date THEN
RAISE past_due; -- this is not handled
END IF;
END; ------------- sub-block ends
EXCEPTION
WHEN past_due THEN -- does not handle raised exception
DBMS_OUTPUT.PUT_LINE('Handling PAST_DUE exception.');

5-26 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Handling PL/SQL Errors

WHEN OTHERS THEN


DBMS_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 of
past_due in the sub-block prevails. Though they share the same name, the two
past_due exceptions are different, just as the two acct_num variables share the same
name but are different variables. Thus, the RAISE statement and the WHEN clause refer
to different exceptions. To have the enclosing block handle the raised exception, you
must remove its declaration from the sub-block or define an OTHERS handler.

Continuing After an Exception is Raised


By default, you put an exception handler at the end of a subprogram to handle
exceptions that are raised anywhere inside the subprogram. To continue executing
from the spot where an exception happens, enclose the code that might raise an
exception inside another BEGIN-END block with its own exception handler. For
example, you might put separate BEGIN-END blocks around groups of SQL statements
that might raise NO_DATA_FOUND, or around arithmetic operations that might raise
DIVIDE_BY_ZERO. By putting a BEGIN-END block with an exception handler inside a
loop, you can continue executing the loop even if some loop iterations raise
exceptions.
You can still handle an exception for a statement, then continue with the next
statement. Place the statement in its own sub-block with its own exception handlers. If
an error occurs in the sub-block, a local handler can catch the exception. When the
sub-block ends, the enclosing block continues to execute at the point where the
sub-block ends, as shown in Example 5–31.

Example 5–31 Continuing After an Exception


-- create a temporary table for this example
CREATE TABLE employees_temp AS
SELECT employee_id, salary, commission_pct FROM employees;

DECLARE
sal_calc NUMBER(8,2);
BEGIN
INSERT INTO employees_temp VALUES (303, 2500, 0);
BEGIN -- sub-block begins
SELECT salary / commission_pct INTO sal_calc FROM employees_temp
WHERE employee_id = 303;
EXCEPTION
WHEN ZERO_DIVIDE THEN
sal_calc := 2500;
END; -- sub-block ends
INSERT INTO employees_temp VALUES (304, sal_calc/100, .1);
EXCEPTION
WHEN ZERO_DIVIDE THEN
NULL;
END;
/
-- view the results
SELECT * FROM employees_temp WHERE employee_id = 303 OR employee_id = 304;
-- drop the temporary table
DROP TABLE employees_temp;

Beta Draft Using PL/SQL 5-27


Handling PL/SQL Errors

In this example, if the SELECT INTO statement raises a ZERO_DIVIDE exception, the
local handler catches it and sets sal_calc to 2500. Execution of the handler is
complete, so the sub-block terminates, and execution continues with the INSERT
statement.

5-28 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
6
Using Subprograms and Packages

The chapter discusses the development of packages and subprograms with PL/SQL.
This section includes the following topics:
■ Overview of Packages and Subprograms on page 6-1
■ Managing Subprograms on page 6-3
■ Managing Packages on page 6-11
■ Oracle Product-Specific Packages on page 6-17

See Also:
■ "Using PL/SQL Packages" in Oracle Database PL/SQL User's Guide
and Reference for additional information on PL/SQL packages.
■ "Using PL/SQL Subprograms" in Oracle Database PL/SQL User's
Guide and Reference for information on PL/SQL subprograms

Note: The examples in this chapter and throughout this guide use
the Oracle HR sample schema. For information on the samples
schemas, see Oracle Database Sample Schemas.

Overview of Packages and Subprograms


Oracle offers the capability to store programs in the database. This functionality
enables commonly required code to be written and tested once and then accessed by
any application that requires the code. Database-resident program units also ensure
that the same processing is applied to the data when the code is invoked, making the
development of applications easier and providing consistency between developers.
You can write database-resident programs in PL/SQL and can use Object Browser to
manage source types such as PL/SQL packages, procedures, functions, and triggers.
The actions include creating, compiling, creating synonyms for, granting privileges on,
and showing dependencies for these source types.
This chapter describes the main types of PL/SQL program units: packages, package
bodies, and subprograms.
You can use PL/SQL to develop packages and stored (standalone) subprograms. Both
packages and stored subprograms are saved and stored in the database and can be
used as building blocks for applications.
This section includes the following topics:

Beta Draft Using Subprograms and Packages 6-1


Overview of Packages and Subprograms

■ Stored Subprograms on page 6-2


■ Packages on page 6-2

See Also: Oracle Database PL/SQL User's Guide and Reference to learn
about PL/SQL code and program units.

Stored Subprograms
Subprograms, which are either functions or procedures, can be compiled and stored in
an Oracle database, ready to be executed. Once compiled, it is a schema object known
as a stored procedure or stored function, which can be referenced by any number of
applications connected to that database.
You can use Object Browser to create stored procedures and functions, or you create
subprograms with SQL statements.
The SQL CREATE PROCEDURE statement lets you create stored procedures that are
stored in the database. The SQL CREATE FUNCTION statement lets you create stored
functions that are stored in an Oracle database.

See Also:
■ Oracle Database SQL Reference for information on CREATE
PROCEDURE.
■ Oracle Database SQL Reference for information on CREATE
FUNCTION.

Subprograms are stored in a compact compiled form. When called, they are loaded
and processed immediately. Subprograms take advantage of shared memory, so that
only one copy of a subprogram is loaded into memory for execution by multiple users.
Stored 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/SQL block are known
as local subprograms, which cannot be referenced by other applications and exist only
inside the enclosing block.
Stored subprograms are the key to modular, reusable PL/SQL code. Wherever you
might use a JAR file in Java, a module in Perl, a shared library in C++, or a DLL in
Visual Basic, you should use PL/SQL stored procedures, stored functions, and
packages.
You can call stored subprograms from a database trigger, another stored subprogram,
or interactively from SQL*Plus. You can also configure a web server so that the HTML
for a web page is generated by a stored subprogram, making it simple to provide a
web interface for data entry and report generation.

Packages
A package is a schema object that groups logically related PL/SQL 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. It
declares the types, variables, constants, exceptions, cursors, and subprograms that can
be referenced from outside the package. The body defines the queries for the cursors
and the code for the subprograms.
You can think of the spec as an interface and of the body as a black box. You can
debug, enhance, or replace a package body without changing the package spec.

6-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Subprograms

You can use Object Browser to create packages, or you create packages with SQL
statements.
To create package specs, use the SQL statement CREATE PACKAGE. A CREATE
PACKAGE BODY statement defines the package body.

See Also:
■ Oracle Database SQL Reference for information on the CREATE
PACKAGE SQL statement.
■ Oracle Database SQL Reference for information on the CREATE
PACKAGE BODY SQL statement.

The spec holds public declarations, which are visible to stored procedures and other
code outside the package. You must declare subprograms at the end of the spec after
all other items (except pragmas that name a specific function; such pragmas must
follow the function spec).
The body holds implementation details and private declarations, which are hidden
from code outside the package. Following the declarative part of the package body is
the optional initialization part, which holds statements that initialize package variables
and do any other one-time setup steps.

Managing Subprograms
Subprograms do not have to belong to a package. Program units that are created
outside of a package are called stored or standalone subprograms. Stored subprograms
can be either functions or procedures. These subprograms are stored in the database
and can be reused by multiple applications. Both procedures and functions can accept
parameters when they are executed (called). To execute a stored subprogram, you only
need to include its object name.
A PL/SQL procedure is a subprogram that performs a specific action. You specify the
name of the procedure, its parameters, its local variables, and the BEGIN-END block
that contains its code and handles any exceptions. A function is a subprogram that
computes a value. Functions and procedures are structured alike, except that functions
return a value. For information on subprograms in PL/SQL blocks, see "Using Local
PL/SQL Subprograms in PL/SQL Blocks" on page 5-17.
As with packages, you can use SQL statements, Object Browser, or Script Editor to
create, modify, run, and drop stored subprograms. In this section, examples are
primarily illustrated with SQL statements.
This section includes the following topics:
■ Creating Subprograms With Object Browser on page 6-4
■ Viewing Subprograms With Object Browser on page 6-5
■ Creating Subprograms in the Script Editor Page on page 6-6
■ Creating Stored Procedures With SQL CREATE PROCEDURE on page 6-7
■ Creating Stored Functions With SQL CREATE FUNCTION on page 6-8
■ Calling Stored Subprograms on page 6-8
■ Editing Subprograms on page 6-10
■ Dropping a Subprogram on page 6-10

Beta Draft Using Subprograms and Packages 6-3


Managing Subprograms

See Also:
■ Oracle Database Express Edition HTML DB User’s Guide for
information on managing functions with Object Browser
■ Oracle Database Express Edition HTML DB User’s Guide for
information on managing procedures with Object Browser

Creating Subprograms With Object Browser


You can use Object Browser to create stored procedures or functions. This section
explains how to create a procedure.
To create a procedure:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. Click the Create button and select Procedure from the drop-down list.
The Create Procedure page appears.
4. Enter the procedure name (award_bonus), check the box for Include Arguments,
and then click the Next button.
5. Enter information for the arguments. For example:
Name IN/OUT Type
emp_id IN NUMBER
bonus IN NUMBER

6. Enter the source code for the procedure body, then click the Next button.
7. Click the SQL tab to view the source code for the procedure body, as shown in
Example 6–1. If you need to make corrections, click the Previous button.
8. When you have finished, click the Finish button. You can click the Edit button to
make updates to the subprogram, such as adding additional variable declarations
outside the BEGIN .. END block.
9. Click the Compile button to compile the procedure. If errors are raised, correct the
source code and try compiling again. Compiling the procedure also saves any
changes to the procedure.
10. When you have finished, click the Finish button.

6-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Subprograms

Figure 6–1 Creating a Procedure With Object Browser

Viewing Subprograms With Object Browser


To find out which stored subprograms exist in your database, use the Object Browser.
To use Object Browser to view procedures and functions:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. Select Procedures or Functions in the object list, then click the procedure or
function you want to display.
The procedure or function information displays.

Beta Draft Using Subprograms and Packages 6-5


Managing Subprograms

Figure 6–2 Viewing a Procedure With Object Browser

Creating Subprograms in the Script Editor Page


To create and run subprograms in the SQL Script Editor page:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.
3. Click the Script Editor icon to display the Script Editor page.
4. Click the Create button to create a SQL script.
5. In the Script Name field, enter a name (my_procedure) for the script.
6. In the Script Editor entry area, enter the source code for the subprogram, as
shown in Example 6–1. Click the Run button if you want to run the script and
create the subprogram.
7. When you are finished, you can click the Save button to save the script file for
future use.

6-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Subprograms

Figure 6–3 Creating a Subprogram With the SQL Script Editor

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Scripts

Creating Stored Procedures With SQL CREATE PROCEDURE


The SQL CREATE PROCEDURE statement lets you create stored procedures that are
stored in the database. These stored (schema level) subprograms can be accessed from
SQL. You can use the optional OR REPLACE clause to modify an existing procedure.
As shown in Example 6–1, a procedure is like a miniature program, beginning with a
header followed by an optional declarative part, an executable part, and an optional
exception-handling part. Note the use of the OR REPLACE option which enables you to
update an existing subprogram.

Example 6–1 Creating a Stored Procedure


-- including OR REPLACE is more convenient when updating a subprogram
CREATE OR REPLACE PROCEDURE award_bonus (emp_id NUMBER, bonus NUMBER) AS
commission REAL;
comm_missing EXCEPTION;
BEGIN -- executable part starts here
SELECT commission_pct / 100 INTO commission FROM employees
WHERE employee_id = emp_id;
IF commission IS NULL THEN
RAISE comm_missing;
ELSE
UPDATE employees SET salary = salary + bonus * commission
WHERE employee_id = emp_id;
DBMS_OUTPUT.PUT_LINE('Employee ' || emp_id || ' received a bonus: '

Beta Draft Using Subprograms and Packages 6-7


Managing Subprograms

|| TO_CHAR(bonus * commission) );
END IF;
EXCEPTION -- exception-handling part starts here
WHEN comm_missing THEN
DBMS_OUTPUT.PUT_LINE('Employee ' || emp_id ||
' does not receive a commission.');
commission := 0;
WHEN OTHERS THEN
NULL; -- for other exceptions do nothing
END award_bonus;
/

When executed, this procedure processes an employee Id and a bonus amount. It uses
the Id to select the employee's commission percentage from a database table and, at
the same time, convert the commission percentage to a decimal amount. Then, it
checks the commission amount. If the commission is null, an exception is raised;
otherwise, the employee's salary is updated. For a discussion of exception handling,
see "Handling PL/SQL Errors" on page 5-23.
To execute (call) the procedure in Example 6–1, see Example 6–3.

Creating Stored Functions With SQL CREATE FUNCTION


The SQL CREATE FUNCTION statement lets you create stored functions that are stored
in an Oracle database. These stored (schema level) subprograms can be accessed from
SQL. You can use the optional OR REPLACE clause to modify an existing function.
Example 6–2 is an example of a stored function which calculates the difference
between the minimum and maximum salaries for a specific job Id.

Example 6–2 Creating a Stored Function


-- function calculates the difference between the minimum and maximum salaries
-- for a specified job Id
CREATE OR REPLACE FUNCTION min_max_sal_range (jobid VARCHAR2)
RETURN NUMBER IS
min_sal NUMBER;
max_sal NUMBER;
BEGIN
SELECT MIN(salary), MAX(salary) INTO min_sal, max_sal FROM employees
WHERE job_id = jobid;
RETURN (max_sal - min_sal);
END min_max_sal_range;
/

To execute (call) the function in Example 6–2, see Example 6–3.

Calling Stored Subprograms


You can call a stored subprogram in several ways. You can use the SQL CALL
statement, a BEGIN ... END block. You can also call a stored subprogram from another
subprogram or a package.
When calling a stored subprogram, you can write the actual parameters using either:
■ Positional notation: You specify the same parameters in the same order as they are
declared in the procedure. This notation is compact, but you must specify the
parameters (especially literals) in the correct order.

6-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Subprograms

■ Named notation: You specify the name of each parameter along with its value. An
arrow (=>) serves as the association operator. The order of the parameters is not
significant.
■ Mixed notation: You specify the first parameters with positional notation, then
switch to named notation for the last parameters.
Example 6–3 shows how you can call the stored procedure in Example 6–1.

Example 6–3 Techniques for Calling Stored Procedures


-- use the SQL CALL statement to execute the procedure
CALL award_bonus(179, 1000);

-- use a PL/SQL block to execute the procedure


BEGIN
award_bonus(179, 1000);
END;
/
-- using named notation for the parameters, rather than positional
BEGIN
award_bonus(bonus=>1000, emp_id=>179);
END;
/

For Example 6–3 the output of all the calls is similar to:
Employee 179 received a bonus: 1
Example 6–4 shows how you can call the stored function in Example 6–2. Because a
function returns a value, it is called as part of a line of PL/SQL code.

Example 6–4 Techniques for Calling Stored Function


-- create a PL/SQL block to call the function, you can also use another subprogram
DECLARE
v_jobid VARCHAR2(10) := 'ST_CLERK';
BEGIN
DBMS_OUTPUT.put_line('Job Id: ' || v_jobid);
DBMS_OUTPUT.put_line('The range between minimum and maximum salaries is: ' ||
TO_CHAR(min_max_sal_range(v_jobid)));
END;
/

For Example 6–4 the output of the PL/SQL block is similar to:
Job Id: ST_CLERK
The range between minimum and maximum salaries is: 1500

Using the BEGIN .. END block is recommended in several situations. Calling the
subprogram from a BEGIN .. END block allows named or mixed notation for
parameters which the CALL statement does not support. In addition, using the CALL
statement can suppress an ORA-01403: no data found error that has not been
handled in the PL/SQL subprogram.

See Also:
■ Oracle Database SQL Reference for information on the use of the
CALL statement.

Beta Draft Using Subprograms and Packages 6-9


Managing Subprograms

Editing Subprograms
You can use the SQL CREATE OR REPLACE statement, Object Browser, or Script Editor
to edit procedures and functions.
With the SQL CREATE OR REPLACE statement, simply modify the procedure or
function text and run the SQL CREATE OR REPLACE PROCEDURE or FUNCTION
statement.
To edit a subprogram in the SQL Script Editor page:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.
3. Click the Script Editor icon to display the Script Editor page.
4. Click the script icon that contains the subprogram that you want to edit.
5. In the Script Editor entry area, modify the source code for the subprogram. Click
the Run button if you want to recreate the subprogram.
6. When you are finished, you can click the Save button to save the script file for
future use.
To edit a subprogram with Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. Select Procedures or Functions in the object list, then click the subprogram you
want to display.
4. With the subprogram displayed, click Edit button to modify the subprogram code.
5. Click the Compile button to ensure your changes did raise any errors when
executed. Compiling the subprogram also saves the changes.

Dropping a Subprogram
You can drop subprograms from the database with Object Browser or the SQL DROP
statement.
To use Object Browser to drop procedures and functions:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. Select Procedures or Functions in the object list, then click the procedure or
function you want to drop.
4. Click the Drop button.
5. Click the Finish button to confirm.

6-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Packages

To drop procedures or functions with SQL statements, use the SQL DROP PROCEDURE
or DROP FUNCTION statement as shown in Example 6–5.

Example 6–5 Dropping Subprograms With the DROP Statement


-- drop the procedure award_bonus and remove from the database
DROP PROCEDURE award_bonus;

-- drop the function min_max_sal_range


DROP FUNCTION min_max_sal_range;

Managing Packages
Packages and package bodies can be written in PL/SQL code using SQL*Plus, Object
Browser, or Script Editor. You can view existing packages and package bodies in
Object Browser.
This section includes the following topics:
■ Writing Packages With PL/SQL Code on page 6-11
■ Creating Packages With Object Browser on page 6-12
■ Viewing Packages With Object Browser on page 6-13
■ Creating Packages in the Script Editor Page on page 6-13
■ Creating Packages With SQL CREATE PACKAGE on page 6-14
■ Editing Packages on page 6-15
■ Dropping Packages on page 6-16
■ Calling Subprograms in Packages on page 6-16
■ Accessing Variables in Packages on page 6-17

See Also: Oracle Database Express Edition HTML DB User’s Guide for
information on managing packages with Object Browser

Writing Packages With PL/SQL Code


With PL/SQL, you can break an application down into manageable, well-defined
modules. Using PL/SQL code, you can write program units that are stored as database
objects that can be reused. These objects include packages, subprograms, and triggers.
Subprograms and packages are discussed in this section; triggers are discussed in
Chapter 7, "Using Triggers".

Guidelines for Writing Packages


When writing packages, keep them general so they can be reused in future
applications. Become familiar with the Oracle-supplied packages, and avoid writing
packages that duplicate features already provided by Oracle.
Design and define package specs before the package bodies. Place in a spec only those
things that must be visible to calling programs. That way, other developers cannot
build unsafe dependencies on your implementation details.
To reduce the need for recompiling when code is changed, place as few items as
possible in a package spec. Changes to a package body do not require recompiling
calling procedures. Changes to a package spec require Oracle to recompile every
stored subprogram that references the package.

Beta Draft Using Subprograms and Packages 6-11


Managing Packages

Creating Packages With Object Browser


You can use Object Browser to create packages. This section explains how to create a
package specification.
To create a package specification:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. Click the Create button and select Package from the drop-down list.
The Create Package page appears.
4. Select the Specification option in the Create Package page and click the Next
button.
5. Enter the package name and then click the Next button.
6. Enter the source code for the package specification.
7. Click the Body tab to enter the source code for the package body.
8. Click the Compile button to run the package. If errors are raised, correct the
source code and try compiling again. Compiling the package also saves any
changes to the package.
9. When you have finished, click the Finish button.

Figure 6–4 Creating a Package With Object Browser

6-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Packages

Viewing Packages With Object Browser


To find out which packages and package bodies exist in your database, use the Object
Browser.
To use Object Browser to view packages and package bodies:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. Select Packages in the object list, then click the package you want to display.
The package specification information displays.
4. With the package specification displayed, click Body tab to view the package body
if it exists.

Creating Packages in the Script Editor Page


To create and run packages in the SQL Script Editor page:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.
3. Click the Script Editor icon to display the Script Editor page.
4. Click the Create button to create a SQL script.
5. In the Script Name field, enter a name for the script.
6. In the Script Editor entry area, enter the source code for the package. Click the
Run button if you want to run the script and create the package.
7. When you are finished, you can click the Save button to save the script file for
future use.

Beta Draft Using Subprograms and Packages 6-13


Managing Packages

Figure 6–5 Creating a Package With the SQL Script Editor

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Scripts

Creating Packages With SQL CREATE PACKAGE


To create packages, use the SQL CREATE PACKAGE and CREATE PACKAGE BODY
statements. You can use these SQL statement in SQL*Plus, the Script Editor, or Object
Browser. In Example 6–6, the OR REPLACE option is used so that you can update an
existing package.
In Example 6–6, the emp_actions package contain two procedures that update the
employees table and one function that provides information. The package
specification provides the declaration of the subprograms and the package body
provides the contents of the subprograms.

Example 6–6 Creating a Package and Package Body


CREATE OR REPLACE PACKAGE emp_actions AS -- package specification

PROCEDURE hire_employee (employee_id NUMBER, last_name VARCHAR2,


first_name VARCHAR2, email VARCHAR2, phone_number VARCHAR2,
hire_date DATE, job_id VARCHAR2, salary NUMBER, commission_pct NUMBER,
manager_id NUMBER, department_id NUMBER);
PROCEDURE fire_employee (emp_id NUMBER);
FUNCTION num_above_salary (emp_id NUMBER) RETURN NUMBER;
END emp_actions;
/
CREATE OR REPLACE PACKAGE BODY emp_actions AS -- package body
-- code for procedure hire_employee

6-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Packages

PROCEDURE hire_employee (employee_id NUMBER, last_name VARCHAR2,


first_name VARCHAR2, email VARCHAR2, phone_number VARCHAR2, hire_date DATE,
job_id VARCHAR2, salary NUMBER, commission_pct NUMBER,
manager_id NUMBER, department_id NUMBER) IS
BEGIN
INSERT INTO employees VALUES (employee_id, last_name, first_name, email,
phone_number, hire_date, job_id, salary, commission_pct, manager_id,
department_id);
END hire_employee;
-- code for procedure fire_employee
PROCEDURE fire_employee (emp_id NUMBER) IS
BEGIN
DELETE FROM employees WHERE employee_id = emp_id;
END fire_employee;
-- code for function num_above salary
FUNCTION num_above_salary (emp_id NUMBER) RETURN NUMBER IS
emp_sal NUMBER(8,2);
num_count NUMBER;
BEGIN
SELECT salary INTO emp_sal FROM employees WHERE employee_id = emp_id;
SELECT COUNT(*) INTO num_count FROM employees WHERE salary > emp_sal;
RETURN num_count;
END num_above_salary;
END emp_actions;
/

Applications that call the subprograms in a package only need to know the names and
parameters from the package specification. You can change the implementation details
inside the package body without affecting the calling applications.

Editing Packages
You can use the SQL CREATE OR REPLACE statement, Object Browser, or Script Editor
to edit packages and package bodies.
With the SQL CREATE OR REPLACE statement, simply modify the package
specification or body text and run the SQL CREATE OR REPLACE PACKAGE or
PACKAGE BODY statement.
To edit a package in the SQL Script Editor page:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.
3. Click the Script Editor icon to display the Script Editor page.
4. Click the script icon that contains the package that you want to edit.
5. In the Script Editor entry area, modify the source code for the package. Click the
Run button if you want to execute the package.
6. When you are finished, you can click the Save button to save the script file for
future use.
To edit a package with Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.

Beta Draft Using Subprograms and Packages 6-15


Managing Packages

The Object Browser home page appears.


3. Select Packages in the object list, then click the package you want to display.
The package specification information displays.
4. With the package specification displayed, click Edit button to modify the package
specification. You can click the Body tab to edit the source code for the package
body if it exists.
5. Click the Compile button to ensure your changes did raise any errors when
executed. Compiling the package also saves the changes.

Dropping Packages
You can use the SQL DROP statement or Object Browser to drop packages and
package bodies.
You can drop a package and/or package body with the SQL DROP statement. When
drop a package specification, the corresponding package body is dropped also. You
can choose to drop the only the package body. For example:
-- drop only the package body
DROP PACKAGE BODY my_package;
-- drop the package specification and package body
DROP PACKAGE my_package;

To drop a package and/or package body with Object Browser:


1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.
The Object Browser home page appears.
3. Select Packages in the object list, then click the package you want to display.
The package specification information displays.
4. With the package specification displayed, click Drop button to drop the package
specification and package body. You can click the Body tab and then the Drop
button to drop only the packaged body if it exists.
5. Click the Finish button to firm that you want to drop the package specification
and/or package body.

Calling Subprograms in Packages


To call the procedures of the emp_actions package created in Example 6–6, you can
execute the statements in Example 6–7. The procedures can be executed in a BEGIN ..
END block or with the SQL CALL statement. Note the use of the package name as a
prefix to the procedure name.

Example 6–7 Calling a Procedure in a Package


CALL emp_actions.hire_employee(300, 'Belden', 'Enrique', 'EBELDEN',
'555.111.2222', '31-AUG-04', 'AC_MGR', 9000, .1, 101, 110);

BEGIN
DBMS_OUTPUT.PUT_LINE( 'Number of employees with higher salary: ' ||
TO_CHAR(emp_actions.num_above_salary(120)));

6-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Oracle Product-Specific Packages

emp_actions.fire_employee(300);
END;
/
-- drop the package
DROP PACKAGE emp_actions;

Packages 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 caches
it in memory, saving on disk I/O for subsequent calls. Thus, packages enhance reuse
and improve performance in a multiuser, multi-application environment.
If a subprogram does not take any parameters, you can include an empty set of
parentheses or omit the parentheses, both in PL/SQL and in functions called from SQL
queries. For calls to a method that takes no parameters, an empty set of parentheses is
optional within PL/SQL scopes but required within SQL scopes.

Accessing Variables in Packages


You can create a package specification that is designated only to supply variables to
other packages or subprograms, as shown in Example 6–8. Note the use of the package
name as a prefix to the variable name.

Example 6–8 Using Variables in Packages


CREATE PACKAGE my_pkg AS
my_pi NUMBER := 3.14016408289008292431940027343666863227;
my_e NUMBER := 2.71828182845904523536028747135266249775;
END my_pkg;
/

CREATE PROCEDURE circle_area(radius NUMBER) IS


my_area NUMBER;
my_datatype VARCHAR2(30);
BEGIN
my_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 3
CALL circle_area(3);
-- call the circle_area procedure with radius equal to 4
BEGIN
circle_area(3);
END;
/
-- drop package and procedure
DROP PROCEDURE circle_area;
DROP PACKAGE my_pkg;

Oracle Product-Specific Packages


Oracle and various Oracle tools are supplied with product-specific packages that
define application programming interfaces (APIs) you can call from PL/SQL, SQL,
Java, or other programming environments. Here we mention a few of the more widely
used ones.

Beta Draft Using Subprograms and Packages 6-17


Oracle Product-Specific Packages

See Also:
■ Oracle Database PL/SQL Packages and Types Reference for
information on and usage of product-specific packages.

About the DBMS_OUTPUT Package


Package DBMS_OUTPUT enables you to display output from PL/SQL blocks,
subprograms, packages, and triggers. The package is especially useful for displaying
PL/SQL debugging information. The procedure PUT_LINE outputs information to a
buffer that can be read by another trigger, procedure, or package. You display the
information by calling the procedure GET_LINE or by setting SERVEROUTPUT ON in
SQL*Plus. See "Inputting and Outputting Data with PL/SQL" on page 5-12.
Example 6–9 shows how to display output from a PL/SQL block.

Example 6–9 Using PUT_LINE in the DBMS_OUTPUT Package


-- set server output to ON to display output from DBMS_OUTPUT
SET SERVEROUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE('These are the tables that ' || USER || ' owns:');
FOR item IN (SELECT table_name FROM user_tables)
LOOP
DBMS_OUTPUT.PUT_LINE(item.table_name);
END LOOP;
END;
/

About the DBMS_PIPE Package


Package DBMS_PIPE allows different sessions to communicate over named pipes. (A
pipe is an area of memory used by one process to pass information to another.) You can
use the procedures PACK_MESSAGE and SEND_MESSAGE to pack a message into a
pipe, then send it to another session in the same instance or to a waiting application
such as a UNIX program.
At the other end of the pipe, you can use the procedures RECEIVE_MESSAGE and
UNPACK_MESSAGE to receive and unpack (read) the message. Named pipes are useful
in many ways. For example, you can write a C program to collect data, then send it
through pipes to stored procedures in an Oracle database.

About the UTL_FILE Package


Package UTL_FILE lets PL/SQL programs read and write operating system (OS) text
files. 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 returns
a 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.

About the UTL_HTTP Package


Package UTL_HTTP allows your PL/SQL programs to make hypertext transfer
protocol (HTTP) callouts. It can retrieve data from the Internet or call Oracle Web
Server cartridges. The package has two entry points, each of which accepts a URL
(uniform resource locator) string, contacts the specified site, and returns the requested
data, which is usually in hypertext markup language (HTML) format.

6-18 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Oracle Product-Specific Packages

About the UTL_SMTP Package


Package UTL_SMTP allows your PL/SQL programs to send electronic mails (emails)
over Simple Mail Transfer Protocol (SMTP). The package provides interfaces to the
SMTP commands for an email client to dispatch emails to a SMTP server.

Beta Draft Using Subprograms and Packages 6-19


Oracle Product-Specific Packages

6-20 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
7
Using Triggers

This chapter discusses the use of database triggers with Oracle Express. Triggers are
database objects that can be created with PL/SQL code.
This section includes the following topics:
■ Overview of Triggers on page 7-1
■ Designing Triggers on page 7-5
■ Managing Triggers in the Database on page 7-7

See Also:
■ Oracle Database Concepts for information on triggers.
■ Oracle Database Application Developer's Guide - Fundamentals for
information on triggers.
■ Oracle Database SQL Reference for information on the CREATE
TRIGGER SQL statement.

Overview of Triggers
A database trigger is a stored subprogram associated with a database table, view, or
event. The trigger can be called once, when some event occurs, or many times, once for
each row affected by an INSERT, UPDATE, or DELETE statement. The trigger can be
called after the event, to record it or take some followup action. Or, the trigger can be
called before the event to prevent erroneous operations or fix new data so that it
conforms to business rules. The executable part of a trigger can contain procedural
statements as well as SQL data manipulation statements.
Triggers are created using the SQL CREATE TRIGGER statement. This statement can be
used with Object Browser, SQL Script Editor, or SQL*Plus. The CREATE (or CREATE OR
REPLACE) statement fails if any errors exist in the PL/SQL block.
■ Types of Triggers on page 7-2
■ Naming Triggers on page 7-2
■ When Is the Trigger Fired? on page 7-2
■ Controlling When a Trigger Is Fired on page 7-2
■ Accessing Column Values in Row Triggers on page 7-4
■ Detecting the DML Operation That Fired a Trigger on page 7-4
■ Enabled and Disabled Trigger Modes on page 7-5

Beta Draft Using Triggers 7-1


Overview of Triggers

■ Error Conditions and Exceptions in the Trigger Body on page 7-5

See Also: Oracle Database SQL Reference for information on trigger


creation syntax

Types of Triggers
A trigger is either a stored PL/SQL block or a PL/SQL, or C procedure associated with
a table, view, schema, or the database itself. Oracle automatically executes a trigger
when a specified event takes place, which usually is a DML statement being issued
against 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)

Naming Triggers
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 as
tables, views, and procedures. For example, a table and a trigger can have the same
name; however, to avoid confusion, this is not recommended.

When Is the Trigger Fired?


A trigger is fired based on a triggering statement, which specifies:
■ The SQL statement or the system event, database event, or DDL event that fires
the trigger body. The options include DELETE, INSERT, and UPDATE. One, two, or
all 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 statement


includes a column list, the trigger is fired only when one of the specified columns is
updated. If a triggering statement omits a column list, the trigger is fired when any
column of the associated table is updated. A column list cannot be specified for
INSERT or DELETE triggering statements. In Example 7–1 on page 7-10 the audit_
sal trigger specifies the salary column and is only fired after any UPDATE of an
employee's salary in the employees table. Updates of other columns would not fire
the trigger.

Controlling When a Trigger Is Fired


There are several ways to control when a trigger is fired.

7-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Overview of Triggers

Firing Triggers With the BEORE and AFTER Options


The BEFORE or AFTER option in the CREATE TRIGGER statement specifies exactly
when to fire the trigger body in relation to the triggering statement that is being run. In
a CREATE TRIGGER statement, the BEFORE or AFTER option is specified just before the
triggering statement. For example, the audit_sal trigger in Example 7–1 is an AFTER
trigger and the trigger in Example 7–2 is a BEFORE trigger.
In general, you use BEFORE or AFTER triggers to achieve the following results:
■ Use BEFORE row triggers to modify the row before the row data is written to disk.
■ Use AFTER row triggers to obtain, and perform operations, using the row Id.

Note: BEFORE row triggers are slightly more efficient than AFTER
row triggers. With AFTER row triggers, affected data blocks must be
read (logical read, not physical read) once for the trigger and then
again for the triggering statement. Alternatively, with BEFORE row
triggers, the data blocks must be read only once for both the triggering
statement and the trigger.

If an UPDATE or DELETE statement detects a conflict with a concurrent UPDATE, then


Oracle performs a transparent ROLLBACK and restarts the update. This can occur
many times before the statement completes successfully. Each time the statement is
restarted, the BEFORE statement trigger is fired again. The rollback does not undo
changes to any package variables referenced in the trigger. Your package should
include a counter variable to detect this situation.

Firing Triggers With the FOR EACH ROW Option


The FOR EACH ROW option determines whether the trigger is a row trigger or a
statement trigger. If you specify FOR EACH ROW, then the trigger fires once for each row
of the table that is affected by the triggering statement. These triggers are referred to as
row-level triggers. See the use of FOR EACH ROW in Example 7–1 on page 7-10 and
Example 7–2 on page 7-11.
The absence of the FOR EACH ROW option indicates that the trigger fires only once for
each 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 performing
validation checks for the entire statement.In Example 7–4 on page 7-12 the trigger fires
only once for each update of the employees table:

Firing Triggers Based on Conditions (WHEN Clause)


An optional trigger restriction can be included in the definition of a row trigger by
specifying a Boolean SQL expression in a WHEN clause.
If included, then the expression in the WHEN clause is evaluated for each row that the
trigger affects. If the expression evaluates to TRUE for a row, then the trigger body is
fired on behalf of that row. However, if the expression evaluates to FALSE or NOT. See
Example 7–2 on page 7-11.
The expression in a WHEN clause must be a SQL expression, and it cannot include a
subquery. You cannot use a PL/SQL expression (including user-defined functions) in
the WHEN clause. A WHEN clause cannot be included in the definition of a statement
trigger.

Beta Draft Using Triggers 7-3


Overview of Triggers

Accessing Column Values in Row Triggers


Within a trigger body of a row trigger, the PL/SQL code and SQL statements have
access to the old and new column values of the current row affected by the triggering
statement. 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 the
table are identified by :OLD.colum_name and :NEW.column_name. The use of :NEW
and :OLD is shown in Example 7–1 on page 7-10 and Example 7–2 on page 7-11.
Depending on the type of triggering statement, certain correlation names might not
have any meaning.
■ A trigger fired by an INSERT statement has meaningful access to new column
values only. Because the row is being created by the INSERT, the old values are
null.
■ A trigger fired by an UPDATE statement has access to both old and new column
values for both BEFORE and AFTER row triggers.
■ A trigger fired by a DELETE statement has meaningful access to :OLD column
values only. Because the row no longer exists after the row is deleted, the :new
values are NULL and cannot be modified.
Old and new values are available in both BEFORE and AFTER row triggers. A new
column value can be assigned in a BEFORE row trigger, but not in an AFTER row
trigger (because the triggering statement takes effect before an AFTER row trigger is
fired). If a BEFORE row trigger changes the value of NEW.column, then an AFTER row
trigger fired by the same statement sees the change assigned by the BEFORE row
trigger.
Correlation names can also be used in the Boolean expression of a WHEN clause. A
colon (:) must precede the OLD and NEW qualifiers when they are used in a trigger
body, but a colon is not allowed when using the qualifiers in the WHEN clause.

Detecting the DML Operation That Fired a Trigger


If more than one type of DML operation can fire a trigger, such as ON INSERT OR
UPDATE, 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 the
kind of DML operation fired the trigger. For an example of the use of IF-THEN with
INSERTING and UPDATING, see Example 7–4 on page 7-12.
In an UPDATE trigger, a column name can be specified with an UPDATING conditional
predicate to determine if the named column is being updated. For example, assume a
trigger 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 the
salary column. This way, the trigger can minimize its overhead when the column of
interest is not being changed.

7-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Designing Triggers

Enabled and Disabled Trigger Modes


A trigger can be in enabled or disabled modes. You would disable a trigger if you did
not want the trigger to execute, perhaps during maintenance activities on the database.
■ Enabled. An enabled trigger executes its trigger body if a triggering statement is
entered and the trigger restriction (if any) evaluates to TRUE.
■ Disabled. A disabled trigger does not execute its trigger body, even if a triggering
statement is entered and the trigger restriction (if any) evaluates to TRUE.
See "Enabling Triggers" on page 7-14 and "Disabling Triggers" on page 7-14.

Error Conditions and Exceptions in the Trigger Body


If a predefined or user-defined error condition or exception is raised during the
execution of a trigger body, then all effects of the trigger body, as well as the triggering
statement, are rolled back unless the error is trapped by an exception handler.
Therefore, a trigger body can prevent the execution of the triggering statement by
raising an exception. User-defined exceptions are commonly used in triggers that
enforce complex security authorizations or integrity constraints. See "Creating a
Trigger With an Exception Handler" on page 7-11 and "Handling PL/SQL Errors" on
page 5-23.

Designing Triggers
This section discusses the design of triggers.
This section includes the following topics:
■ Guidelines For Triggers on page 7-5
■ Restrictions on Creating Triggers on page 7-6
■ Privileges Needed to Work with Triggers on page 7-6

Guidelines For Triggers


Use the following guidelines when designing your triggers:
■ Use triggers to guarantee that when a specific operation is performed, related
actions are performed.
■ Do not define triggers that duplicate features already built into Oracle Database.
For example, do not define triggers to reject bad data if you can do the same
checking through declarative integrity constraints.
■ Limit the size of triggers. If the logic for your trigger requires much more than 60
lines of PL/SQL code, it is better to include most of the code in a stored procedure
and call the procedure from the trigger. The size of the trigger cannot be more than
32K.
■ Use triggers only for centralized, global operations that should be fired for the
triggering statement, regardless of which user or database application issues the
statement.
■ Do not create recursive triggers. For example, creating an AFTER UPDATE
statement trigger on the employees table that itself issues an UPDATE statement
on employees, causes the trigger to fire recursively until it has run out of
memory.

Beta Draft Using Triggers 7-5


Designing Triggers

■ Use triggers on DATABASE judiciously. They are executed for every user every
time the event occurs on which the trigger is created.

Restrictions on Creating Triggers


When creating triggers with PL/SQL code, there are some restrictions that are not
required for standard PL/SQL blocks. The following sections discuss these restrictions.

SQL Statements Allowed in Trigger Bodies


The body of a trigger can contain DML SQL statements. It can also contain SELECT
statements, but they must be SELECT... INTO... statements or the SELECT statement in
the definition of a cursor.
DDL statements are not allowed in the body of a trigger. Also, no transaction control
statements are allowed in a trigger. ROLLBACK, COMMIT, and SAVEPOINT cannot be
used.For system triggers, {CREATE/ALTER/DROP} TABLE statements and
ALTER...COMPILE are allowed.

Note: A procedure called by a trigger cannot run the previous


transaction control statements, because the procedure runs within the
context of the trigger body.

Statements inside a trigger can reference remote schema objects. However, pay special
attention when calling remote procedures from within a local trigger. If a timestamp or
signature mismatch is found during execution of the trigger, then the remote
procedure is not run, and the trigger is invalidated.

System Trigger Restrictions


Only committed triggers are fired. For example, if you create a trigger that should be
fired 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 when
the trigger on CREATE events was fired.
For example, if you execute the following SQL statement:
CREATE OR REPLACE TRIGGER my_trigger
AFTER CREATE ON DATABASE
BEGIN
NULL;
END;

Then, trigger my_trigger is not fired after the creation of my_trigger. Oracle
Database does not fire a trigger that is not committed.

Privileges Needed to Work with Triggers


To create a trigger in your schema, you must have the CREATE TRIGGER system
privilege, and either:
■ Own the table specified in the triggering statement, or
■ Have the ALTER privilege for the table in the triggering statement, or
■ Have the ALTER ANY TABLE system privilege
To create a trigger in another user's schema, or to reference a table in another schema
from a trigger in your schema, you must have the CREATE ANY TRIGGER system

7-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Triggers in the Database

privilege. With this privilege, the trigger can be created in any schema and can be
associated with any user's table. In addition, the user creating the trigger must also
have EXECUTE privilege on the referenced procedures, functions, or packages.
To create a trigger on DATABASE, you must have the ADMINISTER DATABASE
TRIGGER privilege. If this privilege is later revoked, then you can drop the trigger, but
not alter it.
The object privileges to the schema objects referenced in the trigger body must be
granted to the trigger owner explicitly (not through a role). The statements in the
trigger body operate under the privilege domain of the trigger owner, not the privilege
domain of the user issuing the triggering statement. This is similar to the privilege
model for stored procedures.

Managing Triggers in the Database


Triggers are another type of database object that you can manage through Object
Browser of the Oracle Database XE Graphical User Interface. You can also create and
update triggers with the SQL Editor page or the SQL*Plus command line. If you use
SQL*Plus, simply type in each line of code at the SQL prompt. For information on
using SQL*Plus, see Appendix A, "SQL*Plus".
■ Creating a Trigger With the Script Editor on page 7-7
■ Creating a Trigger With Object Browser on page 7-8
■ Viewing a Trigger With Object Browser on page 7-9
■ Creating a Trigger With the AFTER and FOR EACH ROW Option on page 7-10
■ Creating a Trigger With the BEFORE Option and WHEN Clause on page 7-11
■ Creating a Trigger With an Exception Handler on page 7-11
■ Creating a Trigger That Fires Once For Each Update on page 7-12
■ Creating LOGON and LOGOFF Triggers on page 7-13
■ Modifying Triggers on page 7-14
■ Enabling Triggers on page 7-14
■ Disabling Triggers on page 7-14
■ Compiling Triggers on page 7-15

See Also: Oracle Database Application Developer's Guide -


Fundamentals for information about the uses for and creation of
triggers

Creating a Trigger With the Script Editor


With the SQL Editor, you can create and update triggers.
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. On the home page, click the SQL icon to display the SQL page.
3. Click the Script Editor icon to display the Script Editor page.
4. Click the Create button to create a SQL script.
5. In the Script Name field, enter a name (my_trigger_script) for the script.

Beta Draft Using Triggers 7-7


Managing Triggers in the Database

6. In the Script Editor entry area, enter the source code for the trigger and any
supporting database objects.
7. Click the Run button in the Script Editor page to execute the statement(s) in the
script.
8. Click the Run button in the Run Script page to confirm that you want to run the
script.
9. Click the script (my_trigger_script) in the Manage Scripts page. to display the
results of the script.
10. Select the Detail view and enable all the Show options in the Results page to
display details on the script results.
11. After you completed the script, you can click the Save button to save the script file
for future use. Note that the .sql extension is appended to the SQL script name.

Figure 7–1 Create a Trigger With the SQL Editor

See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Scripts

Creating a Trigger With Object Browser


You can create and update triggers in the database with the Object Browser.
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4. To run the examples in this guide, log in as user HR with your
password for the HR account.
2. Click the Object Browser icon on the Database Home Page.
3. Click the Create button and select Trigger from the drop-down list.
4. Enter the name of the table (employees) that the trigger activity is based on and
click the Next button. You can also select a table name from the pop-up list.
5. Enter the trigger name (emp_salary_trigger) in the Trigger Name field.
6. Select the firing point (AFTER) from the Firing Point pull-down list.

7-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Triggers in the Database

7. Select an option (update of) from the Options list.


8. Select a column (salary) from the Column list.
9. Check the For Each Row option.
10. Enter the code for the Trigger Body field.

11. Click the Next button.

12. Click the SQL button to view the SQL statements for creating the trigger.

13. Click the Finish button to complete the operation.

Figure 7–2 Creating a Trigger With Object Browser

See Also: Oracle Database Express Edition HTML DB User’s Guide for
information on managing triggers with Object Browser

Viewing a Trigger With Object Browser


To find out which triggers exist in your database and display information about a
specific trigger, use the Object Browser.
To display information about a trigger with Object Browser:
1. Log in to the Database Home Page. See "Logging in to the Database Home Page"
on page 1-4.
2. Click the Object Browser icon on the Database Home Page.
3. Select Triggers in the object list, then select the trigger (emp_salary_trigger)
you want to display.
4. Click the Object Details, Code, Errors, or SQL tab to display all the information
about the trigger.

Beta Draft Using Triggers 7-9


Managing Triggers in the Database

Figure 7–3 Viewing Triggers With Object Browser

Creating a Trigger With the AFTER and FOR EACH ROW Option
Example 7–1 is an example of a trigger on the employees table. In the example, the
table-level trigger fires after salaries in the employees table are updated.
With the FOR EACH ROW option, the trigger writes a record to the emp_audit table for
each update. This record contains employee Id, the date of the update, the updated
salary, and the original salary. Note the use of :OLD.column_name and
:NEW.column_name to access the values in the columns before and after the update.
With the AFTER keyword, the trigger could also query or change the same table.
Triggers can only do that after the initial changes are applied and the table is back in a
consistent state.
Because the trigger uses the FOR EACH ROW clause, it might be executed multiple times,
such as when updating or deleting multiple rows. You might omit this clause if you
just want to record the fact that the operation occurred, but not examine the data for
each row.

Example 7–1 Creating a Database Trigger WIth the AFTER Option


-- create a table to use for this example
CREATE TABLE emp_audit ( emp_audit_id NUMBER(6), up_date DATE,
new_sal NUMBER(8,2), old_sal NUMBER(8,2) );
-- create the trigger
CREATE OR REPLACE TRIGGER audit_sal
AFTER UPDATE OF salary ON employees FOR EACH ROW
BEGIN
-- bind variables are used here for values

7-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Triggers in the Database

INSERT INTO emp_audit VALUES( :OLD.employee_id, SYSDATE,


:NEW.salary, :OLD.salary );
END;
/
-- fire the trigger with an update of salary
UPDATE employees SET salary = salary * 1.01 WHERE manager_id = 122;

-- check the audit table


SELECT * FROM emp_audit;

-- cleanup: rollback changes, drop the trigger and table


ROLLBACK;
DROP TRIGGER audit_sal;
DROP TABLE emp_audit;

Creating a Trigger With the BEFORE Option and WHEN Clause


In Example 7–2 you define the trigger that is fired for each row that is updated. If there
are five employees in department 20 and the salaries for all the employees in the
department are updated, then the trigger fires five times when those rows are
updated. Note the use of the WHEN clause to restrict the firing of the trigger.

Example 7–2 Creating a Database Trigger With the BEFORE Option


-- create a temporary table
CREATE TABLE emp_log (emp_id NUMBER, log_date DATE,
new_salary NUMBER, action VARCHAR2(50));

CREATE OR REPLACE TRIGGER log_salary_increase -- create a trigger


BEFORE UPDATE of salary ON employees FOR EACH ROW
WHEN (OLD.salary < 8000)
BEGIN
INSERT INTO emp_log (emp_id, log_date, new_salary, action)
VALUES (:NEW.employee_id, SYSDATE, :NEW.salary, 'New Salary');
END;
/
-- update the salary with the following UPDATE statement
-- trigger fires for each row that is udpated
UPDATE employees SET salary = salary * 1.01 WHERE department_id = 60;

-- view the log table


SELECT * FROM emp_log;

-- cleanup: rollback updates, drop the trigger and temporary table


ROLLBACK;
DROP TABLE emp_log;
DROP TRIGGER log_salary_increase;

Creating a Trigger With an Exception Handler


Example 7–3 shows use to include an exception handler with a trigger. In this example,
an exception is raised if the an UPDATE changes the job Id of an employee.

Example 7–3 Creating a Database Trigger With an Exception Handler


-- create a temporary table
CREATE TABLE emp_log (emp_id NUMBER, log_date DATE,
action VARCHAR2(50));

Beta Draft Using Triggers 7-11


Managing Triggers in the Database

CREATE OR REPLACE TRIGGER log_emp_updates -- create a trigger


BEFORE UPDATE ON employees FOR EACH ROW
DECLARE
jobid_exception EXCEPTION;
BEGIN
IF (:NEW.job_id <> :OLD.job_id) THEN
RAISE jobid_exception;
END IF;
INSERT INTO emp_log (emp_id, log_date, action)
VALUES (:NEW.employee_id, SYSDATE, 'Employee updated');
EXCEPTION
WHEN jobid_exception THEN
INSERT INTO emp_log (emp_id, log_date, action)
VALUES (:NEW.employee_id, SYSDATE, 'Employee job Id updated!');
END;
/
-- update employees with the following UPDATE statements
UPDATE employees SET salary = salary * 1.01 WHERE employee_id = 103;
-- the trigger raises an exception with this UPDATE
UPDATE employees SET job_id = 'ST_CLERK' WHERE employee_id = 103;

-- view the log table


SELECT * FROM emp_log;

-- cleanup: rollback updates, drop the trigger and temporary table


ROLLBACK;
DROP TABLE emp_log;
DROP TRIGGER log_emp_updates;

Creating a Trigger That Fires Once For Each Update


In Example 7–4 the FOR EACH ROW clause is omitted so the trigger fires only once for
each update of or insert into the employees table. Because there are two operations
that fire the trigger, this example includes IF-THEN statements to log the specific
operation that fired the trigger. The check for the INSERTING condition evaluates to
TRUE only if the statement that fired the trigger is an INSERT statement. The check for
the UPDATING condition evaluates to TRUE only if the statement that fired the trigger
is an UPDATE statement.

Example 7–4 Creating a Trigger That Fires Only Once


-- create a log table
CREATE TABLE emp_update_log (log_date DATE, action VARCHAR2(50));

-- create a trigger
CREATE OR REPLACE TRIGGER log_emp_update
AFTER UPDATE OR INSERT ON employees
DECLARE
v_action VARCHAR2(50);
BEGIN
IF UPDATING THEN
v_action := 'A row has been updated in the employees table';
END IF;
IF INSERTING THEN
v_action := 'A row has been inserted in the employees table';
END IF;
INSERT INTO emp_update_log (log_date, action)
VALUES (SYSDATE, v_action);

7-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Triggers in the Database

END;
/

-- fire the trigger with an update


UPDATE employees SET salary = salary * 1.01 WHERE department_id = 60;
INSERT INTO employees VALUES(305, 'Belden', 'Enrique', 'EBELDEN','555.111.2222',
'31-AUG-05', 'AC_MGR', 9000, .1, 101, 110);

-- view the log table


SELECT * FROM emp_update_log;

-- cleanup: rollback the added row and updates, drop the trigger and log table
ROLLBACK;
DROP TRIGGER log_emp_update;
DROP TABLE emp_update_log;

Creating LOGON and LOGOFF Triggers


You can create a trigger that performs some action when a user logs on or off the
database.
In Example 7–5, a trigger is created to write a record to a log table whenever a user
logs on to the HR account. In this simple example, the user name (USER), the type of
activity (logon or logoff), current system date (SYSDATE), and the number of
employees in the employees table are written to a table. Both SYSDATE and USER are
called pseudocolumns that return values. See "Using Pseudocolumns With SQL" on
page 4-11.

Example 7–5 LOGON Trigger


-- create a table to hold the data on user logons and logoffs
CREATE TABLE hr_log_table ( user_name VARCHAR2(30), activity VARCHAR2(20),
logon_date DATE, employee_count NUMBER );

-- create a trigger that inserts a record in hr_log_table


-- every time a user logs on to the HR schema
CREATE OR REPLACE TRIGGER on_hr_logon
AFTER LOGON
ON HR.schema
DECLARE
emp_count NUMBER;
BEGIN
SELECT COUNT(*) INTO emp_count FROM employees; -- count the number of employees
INSERT INTO hr_log_table VALUES(USER, 'Log on', SYSDATE, emp_count);
END;
/

In Example 7–6, a trigger is created to write a record to a table whenever a user logs off
the HR account.

Example 7–6 LOGOFF Trigger


-- create a trigger that inserts a record in hr_log_table
-- every time a user logs off the HR schema
CREATE OR REPLACE TRIGGER on_hr_logoff
BEFORE LOGOFF
ON HR.schema
DECLARE
emp_count NUMBER;

Beta Draft Using Triggers 7-13


Managing Triggers in the Database

BEGIN
SELECT COUNT(*) INTO emp_count FROM employees; -- count the number of employees
INSERT INTO hr_log_table VALUES(USER, 'Log off', SYSDATE, emp_count);
END;
/

After you log on and log off the HR account, you can check the hr_log_table to
view results of the triggers. For example:
SELECT * FROM hr_log_table;

Modifying Triggers
Like a stored procedure, a trigger cannot be explicitly altered: It must be replaced with
a new definition. (The ALTER TRIGGER statement is used only to recompile, enable, or
disable a trigger.)
When replacing a trigger, you must include the OR REPLACE option in the CREATE
TRIGGER statement. The OR REPLACE option is provided to allow a new version of an
existing trigger to replace the older version, without affecting any grants made for the
original version of the trigger.
Alternatively, the trigger can be dropped using the DROP TRIGGER statement, and you
can rerun the CREATE TRIGGER statement.
To drop a trigger, the trigger must be in your schema, or you must have the DROP ANY
TRIGGER system privilege.

Enabling Triggers
By default, a trigger is automatically enabled when it is created; however, it can later
be disabled. After you have completed the task that required the trigger to be disabled,
re-enable the trigger, so that it fires when appropriate.
Enable a disabled trigger using the ALTER TRIGGER statement with the ENABLE
option. To enable the disabled trigger named REORDER of the INVENTORY table, enter
the following statement:
ALTER TRIGGER log_emp_update ENABLE;
All triggers defined for a specific table can be enabled with one statement using the
ALTER TABLE statement with the ENABLE clause with the ALL TRIGGERS option. For
example, to enable all triggers defined for the INVENTORY table, enter the following
statement:
ALTER TABLE employees ENABLE ALL TRIGGERS;

Disabling Triggers
You might temporarily disable a trigger if:
■ An object it references is not available.
■ You need to perform a large data load, and you want it to proceed quickly without
firing triggers.
■ You are reloading data.
By default, triggers are enabled when first created. Disable a trigger using the ALTER
TRIGGER statement with the DISABLE option.

7-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Triggers in the Database

For example, to disable the trigger named REORDER of the INVENTORY table, enter the
following statement:
ALTER TRIGGER emp_log_update DISABLE;
All triggers associated with a table can be disabled with one statement using the
ALTER TABLE statement with the DISABLE clause and the ALL TRIGGERS option. For
example, to disable all triggers defined for the INVENTORY table, enter the following
statement:
ALTER TABLE employees DISABLE ALL TRIGGERS;

Compiling Triggers
Triggers are similar to PL/SQL anonymous blocks with the addition of the :NEW and
:OLD capabilities, but their compilation is different. A PL/SQL anonymous block is
compiled each time it is loaded into memory.
Triggers, in contrast, are fully compiled when the CREATE TRIGGER statement is
entered, and the code is stored in the data dictionary. This means that a trigger is
executed directly.
If errors occur during the compilation of a trigger, then the trigger is still created. If a
DML statement fires this trigger, then the DML statement fails. Runtime that trigger
errors always cause the DML statement to fail. You can use the SHOW ERRORS
statement in SQL*Plus to see any compilation errors when you create a trigger in
SQL*Plus, or you can SELECT the errors from the USER_ERRORS view as follows:
SELECT * FROM USER_ERRORS WHERE TYPE = 'TRIGGER';

You can enter the previous SQL statement in the SQL Commands page. For
information on entering SQL statements in the SQL Commands page, see "Running
SQL Statements in the SQL Commands Page" on page 4-2.

Dependencies for Triggers


Compiled triggers have dependencies. They become invalid if a depended-on object,
such as a stored procedure or function called from the trigger body, is modified.
Triggers that are invalidated for dependency reasons are recompiled when next
invoked.
You can examine the ALL_DEPENDENCIES view to see the dependencies for a trigger.
For example, you can enter the following statement in the SQL Commands page to
show the dependencies for the triggers in the HR schema:
SELECT NAME, REFERENCED_OWNER, REFERENCED_NAME, REFERENCED_TYPE
FROM ALL_DEPENDENCIES
WHERE OWNER = 'HR' and TYPE = 'TRIGGER';

For information on entering SQL statements in the SQL Commands page, see
"Running SQL Statements in the SQL Commands Page" on page 4-2.
Triggers may depend on other functions or packages. If the function or package
specified in the trigger is dropped, then the trigger is marked invalid. An attempt is
made to validate the trigger on occurrence of the event. If the trigger cannot be
validated successfully, then it is marked VALID WITH ERRORS, and the event fails.

Beta Draft Using Triggers 7-15


Managing Triggers in the Database

Note:
■ There is an exception for STARTUP events: STARTUP events
succeed even if the trigger fails. There are also exceptions for
SHUTDOWN events and for LOGON events if you login as SYSTEM.

Recompiling Triggers
Use the ALTER TRIGGER statement to recompile a trigger manually. For example, the
following statement recompiles the emp_log_update trigger:
ALTER TRIGGER emp_log_update COMPILE;

To recompile a trigger, you must own the trigger or have the ALTER ANY TRIGGER
system privilege.

7-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
8
Working in a Global Environment

This chapter describes how to use Oracle's database access products with Unicode and
provides useful information for SQL and PL/SQL programming in a globalization
support environment.
This section includes the following topics:
■ Overview of Globalization Support on page 8-1
■ Setting up the Globalization Support Environment on page 8-3
■ SQL and PL/SQL Programming with Unicode on page 8-19
■ Locale-Dependent SQL Functions with Optional NLS Parameters on page 8-22

See Also:
■ Oracle Database Express Edition installation guide for Linux or
Windows for information on setting globalization parameters and
environmental variables.
■ Oracle Database Globalization Support Guide for a complete
discussion of globalization support with Oracle Database Express
Edition, including setting up the globalization support
environment.
■ Oracle Database Reference for information on initialization
parameters used for globalization support
■ Oracle Database SQL Reference for information on date and time
formats.

Overview of Globalization Support


Oracle's globalization support enables you to store, process, and retrieve data in native
languages. It ensures that database utilities, error messages, sort order, and date, time,
monetary, numeric, and calendar conventions automatically adapt to any native
language and locale.
Oracle's globalization support includes National Language Support (NLS) features.
National Language Support is the ability to choose a national language and store data
in a specific character set. Globalization support enables you to develop multilingual
applications and software products that can be accessed and run from anywhere in the
world simultaneously. An application can render content of the user interface and
process data in the native users' languages and locale preferences.

Beta Draft Working in a Global Environment 8-1


Overview of Globalization Support

Note: There are two distributions of Oracle Database Express


Edition, one for Western Europe and the other for all languages.
■ The Western European version includes a database created using a
single byte LATIN1 (WE8MSWIN1252) character set. The database
can store Western European language text, such as French,
Spanish, Portuguese, Italian, Dutch, German, Danish, Swedish,
Norwegian, Finnish, Icelandic, as well as English. Database error
messages are available in Brazilian Portuguese, English, French,
German, Italian, and Spanish. The Oracle Database XE Graphical
User Interface is available in English only.
■ The Universal version includes a multibyte Unicode (AL32UTF8)
Database. The database is suitable data of all languages, including
Greek, Russian, Polish, Romanian, Hungarian, Arabic, Hebrew,
Turkish, Chinese, Japanese, Korean, and all the Western European
languages listed in the previous package. Both database error
messages and Oracle Database XE Graphical User Interface are
available in Brazilian Portuguese, Chinese (Simplified and
Traditional), English, French, German, Italian, Japanese, Korean
and Spanish.
The smaller Western European version is suitable for Western
European language deployment, in environments where working
with an English only development interface is acceptable. The larger
Universal package offers support for the development and
deployment in all languages, and should be the choice when a
Unicode database is desired.

Globalization Support Features


Oracle's standard features include:
■ Language Support
The database enables you to store, process, and retrieve data in native languages.
Through the use of Unicode databases and datatypes, the Oracle database
supports most contemporary languages.
See "Setting NLS Parameters" on page 8-4.
■ Territory Support
The database supports cultural conventions that are specific to geographical
locations. The default local time format, date format, and numeric and monetary
conventions depend on the local territory setting.
See "Language and Territory Parameters" on page 8-5.
■ Date and Time Formats
Different conventions for displaying the hour, day, month, and year can be
handled in local formats. Time zones and daylight saving support are also
available.
See "Date and Time Parameters" on page 8-8.
■ Monetary and Numeric Formats
Currency, credit, debit symbols, and numbers can be represented in local formats.

8-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment

See "Monetary Parameters" on page 8-13 and "Numeric and List Parameters" on
page 8-12.
■ Calendars Feature
Oracle 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" on page 8-11.
■ Linguistic Sorting
Oracle provides linguistic definitions for culturally accurate sorting and case
conversion.
See "Linguistic Sorting and Searching" on page 8-15.
■ Character Set Support
Oracle supports a large number of single-byte, multibyte, and fixed-width
encoding schemes that are based on national, international, and vendor-specific
standards.
■ Character Semantics
Oracle provides character semantics. It is useful for defining the storage
requirements for multibyte strings of varying widths in terms of characters instead
of bytes.
See "Length Semantics" on page 8-18.
■ Unicode Support
Unicode is a universal encoded character set that enables you to store information
in any language, using a single character set. Oracle Database Express Edition
provides products such as SQL and PL/SQL for inserting and retrieving Unicode
data.
See "SQL and PL/SQL Programming with Unicode" on page 8-19.

Running the Examples


You can run the SQL examples in this chapter using the SQL Commands page, Script
Editor page, or the SQL*Plus command line. You will need to log in as the HR user to
use the SQL statements in the examples.
For information on running SQL statements in the SQL Commands page or Script
Editor page, see "Executing SQL Statements" on page 4-2. For information on running
SQL statements using the SQL*Plus command line, see Appendix A, "SQL*Plus".

Setting up the Globalization Support Environment


This section discusses how to set up a globalization support environment.
This section includes the following topics:
■ Setting NLS Parameters on page 8-4
■ Choosing a Locale with the NLS_LANG Environment Variable on page 8-5
■ Language and Territory Parameters on page 8-5
■ Date and Time Parameters on page 8-8

Beta Draft Working in a Global Environment 8-3


Setting up the Globalization Support Environment

■ Calendar Definitions on page 8-11


■ Numeric and List Parameters on page 8-12
■ Monetary Parameters on page 8-13
■ Linguistic Sorting and Searching on page 8-15
■ Length Semantics on page 8-18

Setting NLS Parameters


NLS (National Language Support) parameters determine the locale-specific behavior
on both the client and the server. NLS parameters can be specified several ways. In this
guide, altering parameters for the user session and overriding the parameters in SQL
functions are discussed. Both of these techniques accomplished through the use of SQL
statements.
You can alter the NLS parameters settings by:
■ Setting NLS parameters in an ALTER SESSION statement to override the default
values that are set for the session in the initialization parameter file, or that are set
by 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 the
current user session and are not present the next time you log in.

See Also:
■ "Setting NLS Parameters" in Oracle Database Globalization
Support Guide for details on setting the NLS parameters
■ Oracle Database SQL Reference for more information about the
ALTER SESSION statement
■ Oracle Database Administrator's Guide for information on the
initialization parameter file

■ Using NLS parameters within a SQL function to override the default values that
are set for the session in the initialization parameter file, set for the client with
environment variables, or set for the session by the ALTER SESSION statement.
For example:
TO_CHAR(hiredate,'DD/MON/YYYY','nls_date_language = FRENCH')

See Also:
■ "Setting NLS Parameters" in Oracle Database Globalization
Support Guide for details on setting the NLS parameters
■ Oracle Database SQL Reference for more information about SQL
functions, including the TO_CHAR function

Additional methods for setting the NLS parameters require that you shutdown and
restart the database. These techniques include the following:
■ Including parameters in the Oracle Database XE initialization parameter file to
specify the default session NLS environment on the server side. For example:
NLS_TERRITORY = "CZECH REPUBLIC"

8-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment

See Also: Oracle Database Express Edition installation guide for


Linux or Windows for information on setting globalization
parameters and environmental variables.

■ Using NLS environment variables on the client, which may be


platform-dependent, to specify locale-dependent behavior for the client and also
to override the default values set for the session in the initialization parameter file.
For example, on a Linux system:
% setenv NLS_SORT FRENCH

See Also: Oracle Database Express Edition installation guide for


Linux or Windows for information on setting globalization
parameters and environmental variables.

Choosing a Locale with the NLS_LANG Environment Variable


A locale is a linguistic and cultural environment in which a system or program is
running. Setting the NLS_LANG environment parameter is the simplest way to specify
locale behavior for Oracle software. It sets the language and territory used by the client
application and the database server. It also sets the client's character set, which is the
character set for data entered or displayed by a client program.
The NLS_LANG parameter sets the language and territory environment used by both
the server session (for example, SQL command execution) and the client application
(for example, display formatting in Oracle tools).
You might want to modify the NLS environment dynamically during the session. To
do 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 set
with the ALTER SESSION statement.

The ALTER SESSION statement modifies only the session environment. The local
client NLS environment is not modified, unless the client explicitly retrieves the new
settings and modifies its local environment.

See Also:
■ Oracle Database Express Edition installation guides for
information on the NLS_LANG environmental variable
■ Oracle Database SQL Reference for information on the ALTER
SESSION statement.

Language and Territory Parameters


Setting different NLS parameters for local territories allows the database session to use
different cultural settings. For example, you can set the euro (EUR) as the primary
currency and the Japanese yen (JPY) as the secondary currency for a given database
session even when the territory is defined as AMERICA.
This section contains information about the following parameters:
■ NLS_LANGUAGE on page 8-6
■ NLS_TERRITORY on page 8-7

Beta Draft Working in a Global Environment 8-5


Setting up the Globalization Support Environment

NLS_LANGUAGE
The NLS_LANGUAGE parameter can be set to any valid language name and the default
is derived from the NLS_LANG setting. NLS_LANGUAGE specifies the default
conventions for the following session characteristics:
■ Language for server messages
■ Language for day and month names and their abbreviations (specified in the SQL
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. (GROUP
BY uses a binary sort unless ORDER BY is specified.)
Example 8–1 and Example 8–2 show the results from setting NLS_LANGUAGE to
different values. In Example 8–1, the ALTER SESSION statement is issued to set NLS_
LANGUAGE to Italian.

Example 8–1 NLS_LANGUAGE=ITALIAN


ALTER SESSION SET NLS_LANGUAGE=Italian;

-- enter a SELECT to check the format of the output after the ALTER SESSION
SELECT last_name, hire_date, ROUND(salary/8,2) salary FROM employees
WHERE employee_id IN (111, 112, 113);

You should see results similar to the following:


LAST_NAME HIRE_DATE SALARY
------------------------- --------- ----------
Sciarra 30-SET-97 962.5
Urman 07-MAR-98 975
Popp 07-DIC-99 862.5

Note that the month name abbreviations are in Italian.


In Example 8–2, the ALTER SESSION statement is issued to change the language to
German.

Example 8–2 NLS_LANGUAGE=GERMAN


ALTER SESSION SET NLS_LANGUAGE=German;

SELECT last_name, hire_date, ROUND(salary/8,2) salary FROM employees


WHERE employee_id IN (111, 112, 113);

You should see results similar to the following:


LAST_NAME HIRE_DATE SALARY
------------------------- --------- ----------
Sciarra 30-SEP-97 962.5
Urman 07-MRZ-98 975
Popp 07-DEZ-99 862.5

Note that the language of the month abbreviations has changed to German.

8-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment

See Also:
■ Oracle Database Express Edition installation guides for
information on the supported languages in the Oracle Database
Express Edition.
■ Oracle Database Globalization Support Guide for more information
on supported languages.

NLS_TERRITORY
The NLS_TERRITORY parameter can be set to any valid territory name and the default
is derived from the NLS_LANG setting. NLS_TERRITORY specifies the conventions for
the following default date and numeric formatting characteristics:
■ Date format
■ Decimal character and group separator
■ Local currency symbol
■ ISO currency symbol
■ Dual currency symbol
The territory can be modified dynamically during the session by specifying the new
NLS_TERRITORY value in an ALTER SESSION statement. For example, to change the
territory 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 default
values for the new territory. Example 8–3 and Example 8–4 show behavior that results
from different settings of NLS_TERRITORY and NLS_LANGUAGE.

Example 8–3 NLS_LANGUAGE=AMERICAN, NLS_TERRITORY=AMERICA


-- set NLS_LANAGUAGE and NLS_TERRITORY
ALTER SESSION SET NLS_LANGUAGE = American NLS_TERRITORY = America;

-- enter the following SELECT to view the format of the output for currency
SELECT TO_CHAR(salary,'L99G999D99') salary FROM employees
WHERE 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:
SALARY
--------------------
$24,000.00
$17,000.00
$17,000.00

In Example 8–4 an ALTER SESSION statement is issued to change the territory to


Germany.

Example 8–4 NLS_LANGUAGE=AMERICAN, NLS_TERRITORY=GERMANY


-- set NLS_TERRITORY to Germany for this session
ALTER SESSION SET NLS_TERRITORY = Germany;

SELECT TO_CHAR(salary,'L99G999D99') salary FROM employees


WHERE employee_id IN (100, 101, 102);

Beta Draft Working in a Global Environment 8-7


Setting up the Globalization Support Environment

You should see results similar to the following:


SALARY
-------------------
€24.000,00
€17.000,00
€17.000,00

Note that the currency symbol has changed from $ to €. The numbers have not
changed because the underlying data is the same.

See Also:
■ Oracle Database Express Edition installation guides for
information on the supported territories in the Oracle Database
Express Edition.
■ Oracle Database Globalization Support Guide for more information
on supported territories

Date and Time Parameters


Oracle enables you to control the display of date and time, allowing different
conventions for displaying the hour, day, month, and year to be handled in local
formats. For example, in the United Kingdom, the date is displayed using the
DD/MM/YYYY format, while China commonly uses the YYYY-MM-DD format.
This section contains the following topics:
■ Date Formats on page 8-8
■ Time Formats on page 8-10

Date Formats
Different date formats are shown in Table 8–1.

Table 8–1 Examples of Short Date Formats


Country Description Example
Estonia dd.mm.yyyy 28.02.2005
Germany dd.mm.rr 28.02.05
China yyyy-mm-dd 2005-02-28
UK dd/mm/yyyy 28/02/2005
US mm/dd/yyyy 02/28/2005

This section includes the following parameters:


■ NLS_DATE_FORMAT on page 8-8
■ NLS_DATE_LANGUAGE on page 8-9

NLS_DATE_FORMAT The NLS_DATE_FORMAT parameter defines the default date format


to use with the TO_CHAR and TO_DATE functions. The NLS_TERRITORY parameter
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"

8-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment

The Oracle default date format may not always corresponds to the cultural specific
convention used in a given territory. You can utilize the short date and long date
format in SQL, using the 'DS' and 'DL' format masks respectively, to obtain dates in
a more localized formats. The examples in this section show the differences between
some of the date formats.

Example 8–5 Using the Default, Short, and Long Date Formats
-- Use an ALTER SESSION statement to change the territory to America,
-- and the language to American
ALTER SESSION SET NLS_TERRITORY = America NLS_LANGUAGE = American;

-- After the session is altered, select the dates with the format masks
SELECT hire_date, TO_CHAR(hire_date,'DS') "Short",
TO_CHAR(hire_date,'DL') "Long" FROM employees
WHERE employee_id IN (111, 112, 113);

The results of the query in Example 8–5 are similar to the following:
HIRE_DATE Short Long
--------- ---------- -----------------------------
30-SEP-97 9/30/1997 Tuesday, September 30, 1997
07-MAR-98 3/7/1998 Saturday, March 07, 1998
07-DEC-99 12/7/1999 Tuesday, December 07, 1999

To 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 must
be enclosed by single quotes. For example:
NLS_DATE_FORMAT = '"Date: "MM/DD/YYYY'

NLS_DATE_LANGUAGE The NLS_DATE_LANGUAGE parameter specifies the language for


the day and month names produced by the TO_CHAR and TO_DATE functions. NLS_
DATE_LANGUAGE overrides the language that is specified implicitly by NLS_
LANGUAGE. NLS_DATE_LANGUAGE has the same syntax as the NLS_LANGUAGE
parameter, 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 functions
■ Month and day abbreviations used by the default date format (NLS_DATE_
FORMAT)
Example 8–6 shows how to use NLS_DATE_LANGUAGE to set the date language to
French.

Example 8–6 NLS_DATE_LANGUAGE=FRENCH, Month and Day Names


-- set NLS_DATE_LANAGUAGE for this user session
ALTER SESSION SET NLS_DATE_LANGUAGE = FRENCH;

-- display the current system date


SELECT 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 2005

Beta Draft Working in a Global Environment 8-9


Setting up the Globalization Support Environment

The 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: Oracle Database SQL Reference

Time Formats
Different time formats are shown in Table 8–2.

Table 8–2 Examples of Time Formats


Country Description Example
Estonia hh24:mi:ss 13:50:23
Germany hh24:mi:ss 13:50:23
China hh24:mi:ss 13:50:23
UK hh24:mi:ss 13:50:23
US hh:mi:ssxff am 1:50:23.555 PM

This section contains information about the following parameters:


■ NLS_TIMESTAMP_FORMAT on page 8-10
■ NLS_TIMESTAMP_TZ_FORMAT on page 8-10

NLS_TIMESTAMP_FORMAT NLS_TIMESTAMP_FORMAT defines the default date 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 valid datetime format mask.
The following example shows a value for NLS_TIMESTAMP_FORMAT:
NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH:MI:SS.FF'

NLS_TIMESTAMP_TZ_FORMAT NLS_TIMESTAMP_TZ_FORMAT defines the default date


format for the TIMESTAMP and TIMESTAMP WITH LOCAL TIME ZONE datatypes. 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 datetime format 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 8–7 the TO_TIMESTAMP_TZ function uses the format value that was
specified for NLS_TIMESTAMP_TZ_FORMAT.

Example 8–7 Setting NLS_TIMESTAMP_TZ_FORMAT


-- display August 20, 2005 using the format of NLS_TIMPSTAMP_TZ_FORMAT
SELECT 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_ANGELES

8-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment

Calendar Definitions
This section includes the following topics:
■ Calendar Formats on page 8-11
■ NLS_CALENDAR on page 8-12

Calendar Formats
The following calendar information is stored for each territory:
■ First Day of the Week on page 8-11
■ First Calendar Week of the Year on page 8-11
■ Number of Days and Months in a Year on page 8-11
■ First Year of Era on page 8-11

First Day of the Week Some cultures consider Sunday to be the first day of the week.
Others consider Monday to be the first day of the week. A German calendar starts
with Monday.
The first day of the week is determined by the NLS_TERRITORY parameter.

First Calendar Week of the Year Some countries use week numbers for scheduling,
planning, and bookkeeping. Oracle supports this convention. In the ISO standard, the
week number can be different from the week number of the calendar year. For
example, 1st Jan 1988 is in ISO week number 53 of 1987. An ISO week always starts
on a Monday and ends on a Sunday.
To support the ISO standard, Oracle provides the IW date format element. It returns
the ISO week number.
The first calendar week of the year is determined by the NLS_TERRITORY parameter.

Number of Days and Months in a Year Oracle supports six calendar systems in addition to
Gregorian, the default:
■ Japanese Imperial—uses the same number of months and days as Gregorian, but
the year starts with the beginning of each Imperial Era
■ ROC Official—uses the same number of months and days as Gregorian, but the
year 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 30
days each. The last month has either 29 days or 30 days (leap year).
■ Thai Buddha—uses a Buddhist calendar
■ Arabic Hijrah—has 12 months with 354 or 355 days
■ English Hijrah—has 12 months with 354 or 355 days
The calendar system is specified by the NLS_CALENDAR parameter.

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. For
example, 1998 is the tenth year of the Heisei era.

Beta Draft Working in a Global Environment 8-11


Setting up the Globalization Support Environment

NLS_CALENDAR
Many different calendar systems are in use throughout the world. NLS_CALENDAR
specifies which calendar system Oracle uses. The default value is Gregorian. The
value can be any valid calendar format name.
NLS_CALENDAR can have one of the following values:
■ Arabic Hijrah
■ English Hijrah
■ Gregorian
■ Japanese Imperial
■ Persian
■ ROC Official (Republic of China)
■ Thai Buddha
In Example 8–8 NLS_CALENDAR is set to English Hijrah.

Example 8–8 NLS_CALENDAR='English Hijrah'


-- set NLS_CALENDAR with ALTER SESSION
ALTER SESSION SET NLS_CALENDAR='English Hijrah';

-- display the current system date


SELECT SYSDATE FROM DUAL;

You should see output similar to the following, depending on the current system date:
SYSDATE
--------------------
24 Ramadan 1422

Numeric and List Parameters


This section includes the following topics:
■ Numeric Formats on page 8-12
■ NLS_NUMERIC_CHARACTERS on page 8-13

Numeric Formats
The database must know the number-formatting convention used in each session to
interpret numeric strings correctly. For example, the database needs to know whether
numbers are entered with a period or a comma as the decimal character (234.00 or
234,00). Similarly, applications must be able to display numeric information in the
format expected at the client site.
Examples of numeric formats are shown in Table 8–3.

Table 8–3 Examples of Numeric Formats


Country Numeric Formats
Estonia 1 234 567,89
Germany 1.234.567,89
China 1,234,567.89
UK 1,234,567.89

8-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment

Table 8–3 (Cont.) Examples of Numeric Formats


Country Numeric Formats
US 1,234,567.89

Numeric formats are derived from the setting of the NLS_TERRITORY parameter, but
they can be overridden by the NLS_NUMERIC_CHARACTERS parameter.

NLS_NUMERIC_CHARACTERS
The NLS_NUMERIC_CHARACTERS parameter specifies the decimal character and
group separator. The group separator is the character that separates integer groups to
show thousands and millions, for example. The group separator is the character
returned by the G number format mask. The decimal character separates the integer
and decimal parts of a number. Setting NLS_NUMERIC_CHARACTERS overrides the
default values derived from the setting of NLS_TERRITORY. The value can be any two
valid numeric characters for the decimal character and group separator.
Any character can be the decimal character or group separator. The two characters
specified 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 (<), greater than sign (>). Either character can be a
space.
To set the decimal character to a comma and the grouping separator to a period, define
NLS_NUMERIC_CHARACTERS as follows:
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ",.";
SQL statements can include numbers represented as numeric or text literals. Numeric
literals are not enclosed in quotes. They are part of the SQL language syntax and
always use a dot as the decimal character and never contain a group separator. Text
literals are enclosed in single quotes. They are implicitly or explicitly converted to
numbers, if required, according to the current NLS settings.
The following SELECT statement formats the number 4000 with the decimal character
and group separator specified in the ALTER SESSION statement:
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ",.";
SELECT TO_CHAR(4000, '9G999D99') FROM DUAL;

You should see output similar to the following:


TO_CHAR(4
---------
4.000,00

Monetary Parameters
Oracle enables you to define radix symbols and thousands separators by locales. For
example, 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 is
important to display the amount appropriately by locale.
This section includes the following topics:
■ Currency Formats on page 8-14
■ NLS_CURRENCY on page 8-14

Beta Draft Working in a Global Environment 8-13


Setting up the Globalization Support Environment

■ NLS_ISO_CURRENCY on page 8-14


■ NLS_DUAL_CURRENCY on page 8-15

Currency Formats
Different currency formats are used throughout the world. Some typical ones are
shown in Table 8–4.

Table 8–4 Currency Format Examples


Country Example
Estonia 1 234,56 kr
Germany 1.234,56€
China ¥1,234.56
UK £1,234.56
US $1,234.56

NLS_CURRENCY
NLS_CURRENCY specifies the character string returned by the L number format mask,
the local currency symbol. Setting NLS_CURRENCY overrides the default setting
defined implicitly by NLS_TERRITORY. The value can be any valid currency symbol
string.

Example 8–9 Displaying the Local Currency Symbol


-- select and format the salary column from employees
SELECT TO_CHAR(salary, 'L099G999D99') "salary" FROM employees
WHERE salary > 11000;

You should see output similar to the following:


SALARY
---------------------
$024,000.00
$017,000.00
$017,000.00
$012,000.00
$014,000.00
$013,500.00
$012,000.00
$011,500.00
$013,000.00
$012,000.00

NLS_ISO_CURRENCY
NLS_ISO_CURRENCY specifies the character string returned by the C number format
mask, the ISO currency symbol. Setting NLS_ISO_CURRENCY overrides the default
value 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 to
US dollars or Australian dollars. ISO specifications define unique currency symbols for
specific territories or countries. For example, the ISO currency symbol for the US
dollar is USD. The ISO currency symbol for the Australian dollar is AUD.

8-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment

NLS_ISO_CURRENCY has the same syntax as the NLS_TERRITORY parameter, and all
supported territories are valid values.
To specify the ISO currency symbol for France, set NLS_ISO_CURRENCY as shown in
Example 8–10.

Example 8–10 Setting NLS_ISO_CURRENCY


-- set NLS_ISO_CURRENCY to France
ALTER SESSION SET NLS_ISO_CURRENCY = FRANCE;

-- display the salary of selected employees


SELECT TO_CHAR(salary, 'C099G999D99') "Salary" FROM employees
WHERE department_id = 60;

You should see output similar to the following:


Salary
--------------------
EUR009,000.00
EUR006,000.00
EUR004,800.00
EUR004,800.00
EUR004,200.00

NLS_DUAL_CURRENCY
Use NLS_DUAL_CURRENCY to override the default dual currency symbol defined
implicitly by NLS_TERRITORY. The value can be any valid symbol.
NLS_DUAL_CURRENCY was introduced to support the euro currency symbol during
the euro transition period.

Linguistic Sorting and Searching


Different languages have their own sorting rules. Some languages are collated
according to the letter sequence in the alphabet, some according to the number of
stroke counts in the letter, and some are ordered by the pronunciation of the words.
Treatment of letter accents also differs among languages. For example, in Danish, Æ is
sorted 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 basic
linguistic definition treats strings as sequences of independent characters.
This section includes the following topics:
■ NLS_SORT on page 8-15
■ NLS_COMP on page 8-17

NLS_SORT
The NLS_SORT parameter specifies the collating sequence for ORDER BY queries. It
overrides the default NLS_SORT value that is derived from NLS_LANGUAGE. The value
of NLS_SORT can be BINARY or any valid linguistic sort name:
NLS_SORT = BINARY | sort_name
If the value is BINARY, then the collating sequence is based on the numeric code of the
characters in the underlying encoding scheme. Depending on the datatype, this will
either be in the binary sequence order of the database character set or the national

Beta Draft Working in a Global Environment 8-15


Setting up the Globalization Support Environment

character set. If the value is a named linguistic sort, sorting is based on the order of the
defined sort. Most, but not all, languages supported by the NLS_LANGUAGE parameter
also support a linguistic sort with the same name.
You can set the NLS_SORT parameter to change the linguistic sorting behavior of the
your SQL session. Spain traditionally treats ch, ll as well as ñ as letters of their own,
ordered after c, l and n respectively. Example 8–11 and Example 8–12 illustrate the
effect of using a Spanish sort against the employee names Chen and Chung. In
Example 8–11, the NLS_SORT parameter is set to BINARY.
In Example 8–11, LIKE is used to specify the records to return with the query. For
information on LIKE, see "Restricting Data Using the WHERE Clause" on page 4-6.

Example 8–11 Setting NLS_SORT to BINARY


-- set the NLS_SORT for this user session
ALTER SESSION SET NLS_SORT=binary;

-- select the last name of those employees whose last name begin with C
SELECT last_name FROM employees
WHERE last_name LIKE 'C%' ORDER BY last_name;

The output of Example 8–11 appears:


LAST_NAME
--------------
Cabrio
Cambrault
Cambrault
Chen
Chung
Colmenares

In Example 8–12, the NLS_SORT parameter is set to SPANISH_M.

Example 8–12 Setting NLS_SORT to Spanish


-- set the NLS_SORT for this user session
ALTER SESSION SET NLS_SORT=spanish_m;

-- select the last name of those employees whose last name begin with C
SELECT last_name FROM employees
WHERE last_name LIKE 'C%' ORDER BY last_name;

The output of Example 8–12 appears:


LAST_NAME
--------------
Cabrio
Cambrault
Cambrault
Colmenares
Chen
Chung

Note that the order of last names in the output from the SELECT statement in
Example 8–11 and Example 8–12 is different.

8-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment

See Also:
■ Oracle Database Globalization Support Guide for more information
on supported linguistic sorts.

NLS_COMP
When using comparison operators, characters are compared according to their binary
codes in the designated encoding scheme. A character is greater than another if it has a
higher binary code. Because the binary sequence of characters may not match the
linguistic sequence for a particular language, such comparisons might not be
linguistically correct.
The value of the NLS_COMP parameter affects the comparison behavior of SQL
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 SQL
statements when you want to perform a linguistic comparison instead of a binary
comparison. When NLS_COMP is set to LINGUISTIC, SQL operations perform a
linguistic comparison based on the value of NLS_SORT.
Example 8–13 and Example 8–14 illustrate the effect of performing a binary
comparison follow by a Spanish linguistic sensitive comparison against the employee
names. In Example 8–13 the NLS_COMP parameter is set to BINARY while NLS_SORT is
set to Spanish.

Example 8–13 Setting NLS_COMP to BINARY


-- set NLS_SORT and NLS_COMP for this user session
ALTER SESSION SET NLS_SORT=spanish_m NLS_COMP=binary;

-- select the last name of those employees whose last name begin with C
SELECT last_name FROM employees
WHERE last_name LIKE 'C%';

The output of Example 8–13 appears:


LAST_NAME
--------------
Cabrio
Cambrault
Cambrault
Chen
Chung
Colmenares

In Example 8–14 the NLS_COMP parameter is set to LINGUISTIC while NLS_SORT is


set to Spanish.

Example 8–14 Setting NLS_COMP to BINARY


-- set NLS_SORT and NLS_COMP for this user session
ALTER SESSION SET NLS_SORT=spanish_m NLS_COMP=linguistic;

-- select the last name of those employees whose last name begin with C
SELECT last_name FROM employees
WHERE last_name LIKE 'C%';

The output of Example 8–14 appears:


LAST_NAME

Beta Draft Working in a Global Environment 8-17


Setting up the Globalization Support Environment

--------------
Cabrio
Cambrault
Cambrault
Colmenares

Note the difference in the output of Example 8–13 and Example 8–14. In Spanish ch is
treated as a separate character following c so ch is excluded when a Spanish linguistic
sensitive comparison is performed in Example 8–14.

Case and Accent Insensitive Searching


Operations inside a database are sensitive to the case and the accents of the characters.
Sometimes you might need to perform case-insensitive or accent-insensitive
comparisons. Use the NLS_SORT session parameter to specify a case-insensitive or
accent insensitive sort.
To specify a case-insensitive or accent-insensitive sort:
■ Append _CI to an Oracle sort name for a case-insensitive sort. For example:
BINARY_CI: accent sensitive and case insensitive binary sort
GENERIC_M_CI: accent sensitive and case insensitive GENERIC_M sort

■ Append _AI to an Oracle sort name for an accent-insensitive and case-insensitive


sort. For example:
BINARY_AI: accent insensitive and case insensitive binary sort
FRENCH_M_AI: accent insensitive and case insensitive FRENCH_M sort

Length Semantics
In single-byte character sets, the number of bytes and the number of characters in a
string are the same. In multibyte character sets, a character or code point consists of
one or more bytes. Calculating the number of characters based on byte lengths can be
difficult in a variable-width character set. Calculating column lengths in bytes is called
byte semantics, while measuring column lengths in characters is called character
semantics.
Character semantics is useful for defining the storage requirements for multibyte
strings of varying widths. For example, in a Unicode database (AL32UTF8), suppose
that you need to define a VARCHAR2 column that can store up to five Chinese
characters together with five English characters. Using byte semantics, this column
requires 15 bytes for the Chinese characters, which are three bytes long, and 5 bytes for
the English characters, which are one byte long, for a total of 20 bytes. Using character
semantics, the column requires 10 characters.
The expressions in the following list use byte semantics. Note the BYTE qualifier in the
VARCHAR2 expression and the B suffix in the SQL function name.
■ VARCHAR2(20 BYTE)
■ SUBSTRB(string, 1, 20)
The expressions in the following list use character semantics. Note the CHAR qualifier
in the VARCHAR2 expression.
■ VARCHAR2(20 CHAR)
■ SUBSTR(string, 1, 20)

8-18 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
SQL and PL/SQL Programming with Unicode

This section includes the following topic:


■ NLS_LENGTH_SEMANTICS on page 8-19

NLS_LENGTH_SEMANTICS
The NLS_LENGTH_SEMANTICS parameter specifies BYTE (default) or CHAR semantics.
By default, the character datatypes CHAR and VARCHAR2 are specified in bytes, not
characters. Hence, the specification CHAR(20) in a table definition allows 20 bytes for
storing character data.
NLS_LENGTH_SEMANTICS enables you to create CHAR, VARCHAR2, and LONG columns
using either byte or character length semantics. NCHAR, NVARCHAR2, CLOB, and NCLOB
columns are always character-based. Existing columns are not affected.
Example 8–15 shows an example of creating a table. When the database character set is
WE8MSWIN1252, the last_name column of the table can hold up to 10 Western
European characters, occupying a maximum of 10 bytes. When the database character
set is Unicode (AL32UTF8), last_name can still hold up to 10 Unicode characters
regardless of the language; however, it can occupy a maximum of 40 bytes.

Example 8–15 Length Semantics and CREATE TABLE


CREATE 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:
■ Oracle Database Concepts for more information about length
semantics

SQL and PL/SQL Programming with Unicode


SQL is the fundamental language with which all programs and users access data in an
Oracle database either directly or indirectly. PL/SQL is a procedural language that
combines the data manipulating power of SQL with the data processing power of
procedural languages. Both SQL and PL/SQL can be embedded in other programming
languages.
Oracle Express provides products such as SQL and PL/SQL for inserting and
retrieving Unicode data. Data is transparently converted between the database and
client programs, which ensures that client programs are independent of the database
character set and national character set. In addition, client programs are sometimes
even independent of the character datatype, such as NCHAR or CHAR, used in the
database.
The PL/SQL and SQL engines process PL/SQL programs and SQL statements on
behalf of client-side programs such as server-side PL/SQL stored procedures. They
allow PL/SQL programs to declare CHAR, VARCHAR2, NCHAR, and NVARCHAR2
variables and to access SQL CHAR and NCHAR datatypes in the database.
This section describes Unicode-related features in SQL and PL/SQL that you can
deploy for multilingual applications.
This section contains the following topics:
■ Overview of Unicode on page 8-20

Beta Draft Working in a Global Environment 8-19


SQL and PL/SQL Programming with Unicode

■ SQL NCHAR Datatypes on page 8-20


■ Unicode String Literals on page 8-21

See Also:
■ Oracle Database SQL Reference
■ Oracle Database PL/SQL User's Guide and Reference

Overview of Unicode
Unicode is a universal encoded character set that enables you to store information in
any language, using a single character set. Unicode provides a unique code value for
every 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 datatype based on the Unicode standard.
You can store Unicode characters in an Oracle database in two ways:
■ You can create a Unicode database that enables you to store UTF-8 encoded
characters as SQL CHAR datatypes.
■ You can support multilingual data in specific columns by using Unicode
datatypes. You can store Unicode characters into columns of the SQL NCHAR
datatypes regardless of how the database character set has been defined. The
NCHAR datatype is an exclusively Unicode datatype.

SQL NCHAR Datatypes


There are three SQL NCHAR datatypes:
■ The NCHAR Datatype on page 8-20
■ The NVARCHAR2 Datatype on page 8-21

The NCHAR Datatype


When you define a table column or a PL/SQL variable as the NCHAR datatype, the
length is always specified as the number of characters. For example, the following
statement 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 30
characters times 3 bytes for each character, or 90 bytes.
The national character set, which is used for all NCHAR datatypes, is defined when the
database is created. The national character set can be either UTF8 or AL16UTF16. The
default is AL16UTF16.
The maximum column size allowed is 2000 characters when the national character set
is UTF8 and 1000 when it is AL16UTF16. The actual data is subject to the maximum
byte limit of 2000. The two size constraints must be satisfied at the same time. In

8-20 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
SQL and PL/SQL Programming with Unicode

PL/SQL, the maximum length of NCHAR data is 32767 bytes. You can define an NCHAR
variable of up to 32767 characters, but the actual data cannot exceed 32767 bytes. If
you insert a value that is shorter than the column length, then Oracle pads the value
with blanks to whichever length is smaller: maximum character length or maximum
byte length.

Note: UTF8 may affect performance because it is a variable-width


character set. Excessive blank padding of NCHAR fields decreases
performance. Consider using the NVARCHAR datatype or changing
to the AL16UTF16 character set for the NCHAR datatype.

The NVARCHAR2 Datatype


The NVARCHAR2 datatype specifies a variable length character string that uses the
national character set. When you create a table with an NVARCHAR2 column, you
specify the maximum number of characters for the column. Lengths for NVARCHAR2
are always in units of characters, just as for NCHAR. Oracle subsequently stores each
value in the column exactly as you specify it, if the value does not exceed the column's
maximum length. Oracle does not pad the string value to the maximum length.
The maximum column size allowed is 4000 characters when the national character set
is UTF8 and 2000 when it is AL16UTF16. The maximum length of an NVARCHAR2
column in bytes is 4000. Both the byte limit and the character limit must be met, so the
maximum number of characters that is actually allowed in an NVARCHAR2 column is
the number of characters that can be written in 4000 bytes.
In PL/SQL, the maximum length for an NVARCHAR2 variable is 32767 bytes. You can
define NVARCHAR2 variables up to 32767 characters, but the actual data cannot exceed
32767 bytes.
The following statement creates a table with one NVARCHAR2 column whose
maximum length in characters is 2000 and maximum length in bytes is 4000.
CREATE TABLE table2 (column2 NVARCHAR2(2000));

Unicode String Literals


You can input Unicode string literals in SQL and PL/SQL as follows:
■ Put a prefix N before a string literal that is enclosed with single quote marks. This
explicitly indicates that the following string literal is an NCHAR string literal. For
example, N'résumé' is an NCHAR string literal. This has the same limitation as
enclosing the string literal with single quote marks, where the data can be lost
during the conversion to the server's database character set. To avoid the potential
loss of data, you can set the environment variable ORA_NCHAR_LITERAL_
REPLACE to true. This will transparently replace the N' internally and preserve
the text literal for SQL processing. By default, this environment variable is set to
false to maintain backward compatibility.
■ Use the NCHR(n) SQL function, which returns a unit of character code in the
national character set, which is AL16UTF16 or UTF8. The result of concatenating
several NCHR(n) functions is NVARCHAR2 data. In this way, you can bypass the
client and server character set conversions and create an NVARCHAR2 string
directly. For example, NCHR(32) represents a blank character.
Because NCHR(n) is associated with the national character set, portability of the
resulting value is limited to applications that run with the same national character

Beta Draft Working in a Global Environment 8-21


Locale-Dependent SQL Functions with Optional NLS Parameters

set. If this is a concern, then use the UNISTR function to remove portability
limitations.
■ Use the UNISTR('string') SQL function. UNISTR('string') converts a string to
the national character set. To ensure portability and to preserve data, include only
ASCII characters and Unicode encoding in the following form: \xxxx, where
xxxx is the hexadecimal value of a character code value in UTF-16 encoding
format. For example, UNISTR('G\0061ry') represents 'Gary'. The ASCII
characters are converted to the database character set and then to the national
character set. The Unicode encoding is converted directly to the national character
set.
The last two methods can be used to encode any Unicode string literals.

Locale-Dependent SQL Functions with Optional NLS Parameters


All SQL functions whose behavior depends on globalization support conventions
allow NLS parameters to be specified. These functions are:
TO_CHAR
TO_DATE
TO_NUMBER
NLS_UPPER
NLS_LOWER
NLS_INITCAP
NLSSORT

Explicitly specifying the optional NLS parameters for these functions enables the
functions to be evaluated independently of the session's NLS parameters. This feature
can be important for SQL statements that contain numbers and dates as string literals.
For example, the following query is evaluated correctly if the language specified for
dates is AMERICAN:
SELECT last_name FROM employees WHERE hire_date > '01-JAN-1999';

Such a query can be made independent of the current date language by using a
statement similar to the following:
SELECT last_name FROM employees
WHERE hire_date > TO_DATE('01-JAN-1999','DD-MON-YYYY',
'NLS_DATE_LANGUAGE = AMERICAN');

In this way, SQL statements that are independent of the session language can be
defined where necessary. Such statements are necessary when string literals appear in
SQL statements in views, CHECK constraints, or triggers.

Note: Only SQL statements that must be independent of the


session NLS parameter values should explicitly specify optional
NLS parameters in locale-dependent SQL functions. Using session
default values for NLS parameters in SQL functions usually results
in better performance.

All character functions support both single-byte and multibyte characters. Except
where explicitly stated, character functions operate character by character, rather than
byte by byte.
The rest of this section includes the following topics:

8-22 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Locale-Dependent SQL Functions with Optional NLS Parameters

■ Default Values for NLS Parameters in SQL Functions on page 8-23


■ Specifying NLS Parameters in SQL Functions on page 8-23
■ Unacceptable NLS Parameters in SQL Functions on page 8-24

Default Values for NLS Parameters in SQL Functions


When SQL functions evaluate views and triggers, default values from the current
session are used for the NLS function parameters. When SQL functions evaluate
CHECK constraints, they use the default values that were specified for the NLS
parameters when the database was created.

Specifying NLS Parameters in SQL Functions


NLS parameters are specified in SQL functions as 'parameter = value'. For example:
'NLS_DATE_LANGUAGE = AMERICAN'
The following NLS parameters can be specified in SQL functions:
NLS_DATE_LANGUAGE
NLS_NUMERIC_CHARACTERS
NLS_CURRENCY
NLS_ISO_CURRENCY
NLS_DUAL_CURRENCY
NLS_CALENDAR
NLS_SORT

Table 8–5 shows which NLS parameters are valid for specific SQL functions.

Table 8–5 SQL Functions and Their Valid NLS Parameters


SQL Function Valid NLS Parameters
TO_DATE NLS_DATE_LANGUAGE,
NLS_CALENDAR
TO_NUMBER NLS_NUMERIC_CHARACTERS,
NLS_CURRENCY,
NLS_DUAL_CURRENCY,
NLS_ISO_CURRENCY,
TO_CHAR NLS_DATE_LANGUAGE,
NLS_NUMERIC_CHARACTERS,
NLS_CURRENCY,
NLS_ISO_CURRENCY,
NLS_DUAL_CURRENCY,
NLS_CALENDAR
TO_NCHAR NLS_DATE_LANGUAGE,
NLS_NUMERIC_CHARACTERS,
NLS_CURRENCY,
NLS_ISO_CURRENCY,
NLS_DUAL_CURRENCY,
NLS_CALENDAR
NLS_UPPER NLS_SORT
NLS_LOWER NLS_SORT
NLS_INITCAP NLS_SORT
NLSSORT NLS_SORT

Beta Draft Working in a Global Environment 8-23


Locale-Dependent SQL Functions with Optional NLS Parameters

Example 8–16 illustrates how to use NLS parameters in SQL functions.

Example 8–16 Using NLS Parameters in SQL Functions

SELECT 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 employees


ORDER BY NLSSORT(last_name, 'NLS_SORT = German');

Note: In some languages, some lowercase characters correspond


to more than one uppercase character or vice versa. As a result, the
length of the output from the NLS_UPPER, NLS_LOWER, and NLS_
INITCAP functions can differ from the length of the input.

Unacceptable NLS Parameters in SQL Functions


The following NLS parameters are not accepted in SQL functions except for NLSSORT:
■ NLS_LANGUAGE
■ NLS_TERRITORY
■ NLS_DATE_FORMAT
NLS_DATE_FORMAT and NLS_TERRITORY_FORMAT are not accepted as parameters
because they can interfere with required format masks. A date format must always be
specified 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 the
TO_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 you
specify NLS_LANGUAGE in the TO_CHAR function, for example, then its value is
ignored if it differs from the session value of NLS_DATE_LANGUAGE.

8-24 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
A
SQL*Plus

SQL*Plus is an interactive and batch command-line query tool that is installed with
Oracle Database Express Edition.
This section includes the following topics:
■ Overview of SQL*Plus on page A-1
■ Using SQL*Plus on page A-1

See Also:
■ SQL*Plus User's Guide and Reference for complete information
about SQL*Plus
■ Oracle Database SQL Reference for information on using SQL
statements
■ Oracle Database Express Edition 2 Day DBA Guide for information
on setting environmental variables for SQL*Plus and connecting
with SQL*Plus

Overview of SQL*Plus
SQL*Plus has its own commands and environment, and it provides access to the
Oracle Database Express Edition. It enables you to enter and execute SQL, PL/SQL,
and SQL*Plus commands to perform the following:
■ Format, perform calculations on, store, and print from query results
■ Examine table and object definitions
■ Develop and run batch scripts
■ Perform database administration
You can use SQL*Plus to generate reports interactively, to generate reports as batch
processes, and to output the results to text file, to screen, or to HTML file for browsing
on the Internet.

Using SQL*Plus
This section describes SQL*Plus, Oracle's command line tool for executing SQL and
PL/SQL.
■ Starting and Exiting SQL*Plus on page A-2
■ Displaying Help With SQL*Plus on page A-2

Beta Draft SQL*Plus A-1


Using SQL*Plus

■ Entering and Executing SQL Statements and Commands on page A-2


■ SQL*Plus DESCRIBE Command on page A-3
■ SQL*Plus SET Commands on page A-3
■ Running Scripts From SQL*Plus on page A-3
■ Spooling From SQL*Plus on page A-4
■ Using Variables With SQL*Plus on page A-4

Note: Before starting SQL*Plus, make sure that the necessary


environmental variables have been set up properly. See the Oracle
Database Express Edition 2 Day DBA Guide for information on setting
environmental variables for SQL*Plus.

Starting and Exiting SQL*Plus


To start SQL*Plus from the operating system command prompt, enter the following:
sqlplus
When prompted, enter the username and password of the user account (schema) that
you want to access. For example, enter HR for the username and your_hr_password
when prompted.
After you have started SQL*Plus, the SQL> prompt displays for you to type in SQL
statements, as follows:
SQL>
When you want to quit or exit SQL*Plus, type EXIT or QUIT at the SQL prompt, as
follows:
SQL> EXIT

Displaying Help With SQL*Plus


To display a list of help topics for SQL*Plus commands enter HELP INDEX at the SQL
prompt as follows:
SQL> HELP INDEX
From the list of SQL*Plus help topics, you can display help on an individual topic by
entering HELP with a topic name. For example the following displays help on the
SQL*Plus COLUMN command, which enables you to format column output:
SQL> HELP COLUMN

Entering and Executing SQL Statements and Commands


To enter and execute SQL statements or commands, type in the statement or command
at the SQL prompt. At the end of a SQL statement, put a semi-colon (;) and then press
the Enter key to execute the statement. For example:
SQL> 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:
SQL> SELECT employee_id, first_name, last_name
2 FROM employees

A-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL*Plus

3 WHERE employee_id >= 105 AND employee_id <= 115;

Note that a terminating semi-colon (;) is optional with SQL *Plus commands.

SQL*Plus DESCRIBE Command


SQL*Plus provides the DESCRIBE to display a description of a database object. For
example, the following displays the structure of the employees table. This
description is useful when constructing SQL statements that manipulate the
employees table.
SQL> DESCRIBE employees
Name Null? 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 DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)

SQL*Plus SET Commands


The SQL*Plus SET commands can be used to specify various SQL*Plus settings, such
as the format of the output from SQL*Plus statements. For example, the following SET
commands specify the number of lines per page display and the number of characters
per line in the output:
SQL> SET PAGESIZE 200
SQL> SET LINESIZE 140

To enable output from PL/SQL blocks with DBMS_OUTPUT


To view all the settings, enter the following at the SQL prompt:
SQL> SHOW ALL

See Also:
■ SQL*Plus User's Guide and Reference for information setting up the
SQL*Plus environment with a login file

Running Scripts From SQL*Plus


You can use a text editor to create SQL*Plus script files containing SQL*Plus, SQL, and
PL/SQL statements. For consistency, use the .sql extension for the script file name. A
SQL script file can be executed with a START or @ command as follows:
SQL> @c:\my_scripts\my_sql_script.sql
You can use SET ECHO ON to cause a script to echo each statement that is executed. You
can use SET TERMOUT OFF to prevent the script output from displaying on the screen.

Beta Draft SQL*Plus A-3


Using SQL*Plus

When running a script, you should include the full path name unless the script is
located in the directory where SQL*Plus was launched.

See Also:
■ SQL*Plus User's Guide and Reference for information on setting the
SQL*Plus SQLPATH environment environmental variable to
specify the default location of SQL scripts.

Spooling From SQL*Plus


The SPOOL command can be used to direct the output from SQL*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:
SQL> SPOOL my_log_file.log
If you want to append the output to an existing file:
SQL> SPOOL my_log_file.log APPEND
To stop spooling and close a file, enter the following:
SQL> SPOOL OFF

Using Variables With SQL*Plus


You can write queries that use variables to make your SELECT statements more
flexible. You can define the variable prior to running a SQL statement or you can
prompt for a variable value at the time that the SQL statement is run.
When using a variable in a SQL statement, the variable name must be begin with an
ampersand (&).
This section includes the following topics:
■ Prompting for a Variable on page A-4
■ Defining a Variable Value for a Query on page A-4

Prompting for a Variable


In Example A–1, including the variable &emp_id causes the SQL statement to prompt
for a value when the statement is executed. You can then enter the employee_id that
you want to display, such as employee Id 125.

Example A–1 Defining a Variable


-- prompt for employee_id in a query, such as 125
SELECT employee_id, last_name, job_id FROM employees WHERE employee_id = &emp_id;

Defining a Variable Value for a Query


In Example A–2, the variable &jobid is defined prior to running the SQL statement
and the defined value is substituted for the variable when the statement is executed.

Example A–2 Prompting for a Variable


-- define a variable value for a query as follows
DEFINE jobid = "ST_CLERK"
-- run a query using the defined value
SELECT employee_id, last_name FROM employees WHERE job_id = '&jobid';

A-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL*Plus

Beta Draft SQL*Plus A-5


Using SQL*Plus

A-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Index

Symbols blocks
anonymous, 5-2
:= assignment operator, 5-8
BEGIN, 5-5
DECLARE, 5-5
A END, 5-5
EXCEPTION, 5-5
ACCESS_INTO_NULL exception, 5-24
nesting, 5-1, 5-2
adding data to a table, 3-15
structure, 5-5
AFTER triggers
BODY
correlation names and, 7-4
CREATE PACKAGE SQL statement, 6-3
specifying, 7-2
with SQL CREATE PACKAGE statement, 6-3,
ALTER INDEX statement, 4-17
6-14
ALTER TABLE statement, 4-17
Boolean
DISABLE ALL TRIGGERS clause, 7-15
literals, 5-10
ENABLE ALL TRIGGERS clause, 7-14
ALTER TRIGGER statement
DISABLE clause, 7-14 C
ENABLE clause, 7-14 C number format mask, 8-14
anonymous PL/SQL blocks, 5-2 calendars
apostrophes, 5-10 parameter, 8-11
application development
CALL
basic concepts, 1-3 SQL statement, 6-16
arrays calling
PL/SQL, 5-20 stored subprograms, 6-9
assignment operator, 5-8 subprograms in packages, 6-16
assignments calls
IN OUT parameters, 5-18 subprograms, 6-8
attributes CASE expressions
%ROWTYPE, 5-12 overview, 5-14
%TYPE, 5-13 case sensitivity
identifier, 5-8
B string literal, 5-10
CASE_NOT_FOUND exception, 5-24
BEFORE triggers
century
correlation names and, 7-4
date format masks, 2-8
specifying, 7-2
character data
BEGIN
storing, 2-3
block structure, 5-5
character literals, 5-9
BINARY_DOUBLE
quoting, 4-5
datatypes, 2-7
using in SQL statements, 4-5
BINARY_DOUBLE datatype, 2-4
character set
BINARY_FLOAT
national, 8-21
datatypes, 2-6
character sets
BINARY_FLOAT datatype, 2-4
national, 8-20
bind variables
check constraints, 3-8
PL/SQL, 5-23
how to use, 3-8

Beta Draft Index-1


COLLECTION_IS_NULL exception, 5-24 creating
collections functions, 6-2, 6-8
PL/SQL, 5-20 packages, 6-3, 6-14
column alias procedures, 6-2, 6-7
using with SELECT, 4-5 creating a constraint
column constraints, 3-6 using SQL statement, 4-17
columns creating a table, 3-9
accessing in triggers, 7-4 using SQL statement, 4-16
adding to a table, 3-11 creating an index
datatypes, 3-5 SQL statement, 4-17
dropping from a table, 3-12 creating indexes, 3-23
listing in an UPDATE trigger, 7-4 creating indexes for use with constraints, 3-20
unique key, 3-8 currencies
comments formats, 8-14
in PL/SQL, 5-6 CURSOR_ALREADY_OPEN exception, 5-24
COMMIT statement, 4-10 cursors
comparison operators definition, 5-19
BETWEEN, 4-6 explicit, 5-19
equality, 4-6 implicit, 5-19
IN, 4-6
LIKE, 4-6
D
NULL, 4-6
composite keys data
foreign, 3-9 integrity checking on input, 2-5
conditional predicates data definition language (DDL)
trigger bodies, 7-4 SQL statements, 4-15
CONSTANT data integrity rules
for declaring constants, 5-7 as constraints, 3-7
constants data manipulation language
declaring, 5-7 described, 4-8
declaring in PL/SQL, 5-7 data structures
constraints PL/SQL, 5-19
adding to a table, 3-12 database home page
check, 3-8 available tools, 1-4
column, 3-6 logging in, 1-4
dropping, 3-15 database objects
ensuring data integrity, 3-6 managing, 3-1
modifying, 3-14 naming, 3-2
NOT NULL, 5-11 database resident program units, 6-1
table-level, 3-7 database triggers, 7-1
types, 3-7 datatypes
viewing, 3-14 BINARY_DOUBLE, 2-4, 2-7
control structures BINARY_FLOAT, 2-4, 2-6
PL/SQL, 5-14 CHAR, 2-3
correlation names, 7-3 character, 2-3
NEW, 7-4 description, 3-5
OLD, 7-4 floating-point number, 2-6
when preceded by a colon, 7-4 in table columns, 3-5
CREATE introduction, 1-3
with PROCEDURE statement, 6-2, 6-7 NCHAR, 2-3
CREATE FUNCTION statement, 6-2, 6-8 NUMBER, 2-5
CREATE INDEX statement, 4-17 numeric, 2-4
CREATE PROCEDURE statement, 6-2, 6-7 NVARCHAR2, 2-3
CREATE SEQUENCE statement, 4-18 overview, 2-1
CREATE statement VARCHAR2, 2-3
packages, 6-3, 6-14 date and time data
with FUNCTION, 6-2, 6-8 storing, 2-7
CREATE SYNONYM statement, 4-18 date and time parameters, 8-8
CREATE TABLE statement, 4-16 DATE datatype, 2-7
CREATE TRIGGER statement, 7-1 date formats, 8-8

Index-2 Beta Draft


dates dropping a sequence
ISO standard, 8-11 using SQL statement, 4-18
NLS_DATE_LANGUAGE parameter, 8-9 dropping a synonym
datetime using SQL statement, 4-18
literals, 5-10 dropping a table, 3-19
days using SQL statement, 4-18
format element, 8-10 DUAL
DBMS_OUTPUT dummy table, 4-11
procedures for displaying output in dummy table
PL/SQL, 5-12 DUAL, 4-11
DBMS_OUTPUT package DUP_VAL_ON_INDEX exception, 5-24
displaying output, 5-12 dynamic SQL, 5-22
displaying output from PL/SQL, 6-18
using PUT_LINE to display output, 5-11
E
DBMS_PIPE package, 6-18
declarations enabled trigger
constants, 5-7 definition, 7-5
exceptions in PL/SQL, 5-26 enabling
PL/SQL %ROWTYPE and %TYPE, 5-12 triggers, 7-5, 7-14
PL/SQL subprograms, 5-17 END
using NOT NULL constraint, 5-11 block structure, 5-5
declarative part ensuring data integrity
of PL/SQL block, 5-5 with constraints, 3-6
DECLARE error handling
block structure, 5-5 PL/SQL, 5-23
DELETE statement, 4-8, 4-9 EXCEPTION
column values and triggers, 7-4 block structure, 5-5
dependencies exception handlers
in stored triggers, 7-15 PL/SQL, 5-23
schema objects exception-handling part
trigger management, 7-6 of PL/SQL block, 5-5
DESCRIBE command exceptions
SQL*Plus, A-3 advantages of PL/SQL, 5-25
design considerations declaring in PL/SQL, 5-26
Oracle Database Express Edition, 3-1 during trigger execution, 7-5
developing applications list of predefined in PL/SQL, 5-24
overview with Oracle Database Express predefined in PL/SQL, 5-24
Edition, 1-1 scope rules in PL/SQL, 5-26
disabled trigger executable part
definition, 7-5 of PL/SQL block, 5-5
disabling EXIT-WHEN statement
triggers, 7-5, 7-14 overview, 5-17
displaying a table, 3-10
displaying output F
from PL/SQL, 5-11
setting SERVEROUTPUT, 5-12, 6-18 FALSE value, 5-10
using DBMS_OUTPUT.PUT_LINE, 5-11 file I/O, 6-18
displaying PL/SQL output floating-point number
with DBMS_OUTPUT, 5-12 datatypes, 2-6
distributed databases floating-point numbers, 2-4
triggers and, 7-6 FOR EACH ROW clause, 7-3
dot notation, 5-13 foreign key
DROP INDEX statement, 4-17 adding, 3-13
DROP SEQUENCE statement, 4-18 referential integrity between tables, 3-9
DROP SYNONYM statement, 4-18 format elements
DROP TABLE statement, 4-18 day, 8-10
DROP TRIGGER statement, 7-14 month, 8-10
dropping format masks, 8-13
indexes, 3-22 TO_DATE function, 2-9
triggers, 7-14 formats

Beta Draft Index-3


currency, 8-14 indexes
date, 8-8 ascending, 3-20
numeric, 8-12 choose the correct order of columns for
time, 8-10 composites, 3-22
FUNCTION column, 3-20
with CREATE statement, 6-2, 6-8 concatenated, 3-20
functions creating, 3-23
creating, 6-2, 6-8 creating for use with constraints, 3-20
execute, 6-3 descending, 3-20
managing, 6-3 displaying, 3-23
overview, 6-1 drop if not required, 3-22
SQL aggregate, 4-15 dropping, 3-22, 3-24
SQL arithmetic operators, 4-13 function-based, 3-20
SQL character, 4-12 guidelines, 3-21
SQL date, 4-13 limit the number, 3-22
SQL numeric, 4-13 managing, 3-19
normal type, 3-20
order of columns, 3-22
G
single column, 3-20
globalization support types, 3-20
altering NLS parameter settings, 8-4 initialization
calendar definitions, 8-11 using DEFAULT, 5-11
date and time parameter settings, 8-8 INSERT statement, 4-8
default values for NLS parameters in SQL column values and triggers, 7-4
functions, 8-23 integrity constraints
features, 8-2 CHECK, 3-8
language and territory parameter settings, 8-5 triggers vs., 7-5
linguistic sorting and searching, 8-15 INTERVAL DAY TO SECOND datatype, 2-7
locale, 8-5 INTERVAL YEAR TO MONTH datatype, 2-7
monetary parameter settings, 8-13 introduction
National Language Support (NLS) features, 8-1 OCCI, 1-5
NLS_LANG parameter setting, 8-5 OCI, 1-5
numeric and list parameter settings, 8-12 Open Database Connectivity (ODBC), 1-6
overview, 8-1 Oracle Data Provider for .NET, 1-6
programming with unicode, 8-19 Oracle Database Express Edition, 1-2
setting up the environment, 8-3 Oracle Database Extensions for .NET, 1-7
specifying values for NLS parameters in SQL Oracle Developer Tools for Visual Studio, 1-7
functions, 8-23 Oracle HTML DB Developer, 1-8
unacceptable NLS parameters in SQL Oracle JDBC, 1-8
functions, 8-24 Oracle Provider for OLE DB, 1-8
GOTO statement PHP, 1-8
overview, 5-17 PL/SQL, 1-2
SQL, 1-2
H INVALID_CURSOR exception, 5-24
INVALID_NUMBER exception, 5-25
HELP command ISO standard date format, 8-11
SQL*Plus, A-2
HR user
locked account, 1-4 J
logging in, 1-4 JDBC
hypertext markup language (HTML), 6-18 introduction, 1-8
hypertext transfer protocol (HTTP) joins
UTL_HTTP package, 6-18 displaying data from multiple tables with
SELECT, 4-7
I
identifiers K
maximum length, 5-8 keywords
IEEE 754 standard for floating-point numbers, 2-6 use in PL/SQL, 5-8
IF-THEN-ELSE statement
overview, 5-14

Index-4 Beta Draft


L settings, 8-4
specifying in SQL functions, 8-23
language support, 8-2
unacceptable in SQL functions, 8-24
length semantics, 8-18
NLS_CALENDAR parameter, 8-12
linguistic sorts
NLS_COMP parameter, 8-17
parameters, 8-15
NLS_CURRENCY parameter, 8-14
list parameter, 8-12
NLS_DATE_FORMAT parameter, 2-9, 8-8
literals
NLS_DATE_LANGUAGE parameter, 8-9
Boolean, 5-10
NLS_DUAL_CURRENCY parameter, 8-15
character, 5-9
NLS_INITCAP SQL function, 8-22
datetime, 5-10
NLS_ISO_CURRENCY parameter, 8-14
numeric, 5-9
NLS_LANG parameter, 8-5
string, 5-9
choosing a locale, 8-5
types of PL/SQL, 5-9
NLS_LANGUAGE parameter, 8-6
local subprograms, 6-2
NLS_LOWER SQL function, 8-22
locale
NLS_NUMERIC_CHARACTERS parameter, 8-13
globalization support, 8-5
NLS_SORT parameter, 8-15
logging into database home page, 1-4
NLS_TERRITORY parameter, 8-7
LOGIN_DENIED exception, 5-25
NLS_TIMESTAMP_FORMAT parameter
LOOP statement
parameters
overview, 5-16
NLS_TIMESTAMP_FORMAT, 8-10
NLS_UPPER SQL function, 8-22
M NLSSORT SQL function, 8-22
NO_DATA_FOUND exception, 5-25
managing database objects
NOT NULL constraint
Object Browser, 3-2
using in variable declaration, 5-11
overview, 3-1
NOT_LOGGED_ON exception, 5-25
managing indexes, 3-19
notation
managing tables, 3-4
positional versus named, 6-8
maximum size
NUMBER datatype, 2-5
identifier, 5-8
numeric datatypes, 2-4
modifying a constraint
numeric formats, 8-12
using SQL statement, 4-17
numeric literals, 5-9
modifying a table
numeric parameters, 8-12
using SQL statement, 4-17
NVARCHAR2 datatype, 2-3, 8-21
modifying an index
SQL statement, 4-17
modifying data in a table, 3-18 O
modularity, 6-11 Object Browser
monetary parameters, 8-13 managing database objects, 3-2
months Object Reports
format element, 8-10 viewing database objects, 3-3
multi-line comments, 5-6 OCCI
introduction, 1-5
N OCI
introduction, 1-5
national character literals
OLD correlation name, 7-4
quoting, 4-5
Open Database Connectivity (ODBC)
national character set, 8-20, 8-21
introduction, 1-6
National Language Support (NLS)
Oracle Data Provider for .NET
features, 8-1
introduction, 1-6
globalization support, 8-1
Oracle Database Express Edition
NCHAR datatype, 2-3, 8-20
design considerations, 3-1
NCHR SQL function, 8-21
developing applications, 1-1
nested tables
introduction, 1-2
PL/SQL, 5-20
language distributions, 8-2
nesting
Oracle Database Extensions for .NET
block, 5-1, 5-2
introduction, 1-7
NEW correlation name, 7-4
Oracle Developer Tools for Visual Studio
NLS parameters
introduction, 1-7
default values in SQL functions, 8-23

Beta Draft Index-5


Oracle HTML DB Developer NLS_DUAL_CURRENCY, 8-15
introduction, 1-8 NLS_ISO_CURRENCY, 8-14
Oracle JDBC NLS_LANG, 8-5
introduction, 1-8 NLS_LANGUAGE, 8-6
Oracle Provider for OLE DB NLS_NUMERIC_CHARACTERS, 8-13
introduction, 1-8 NLS_SORT, 8-15
ORDER BY clause NLS_TERRITORY, 8-7
using with SELECT, 4-7 numeric, 8-12
overview setting, 8-4
datatypes, 2-1 time and date, 8-8
developing applications with Oracle Database time zone, 8-10
Express Edition, 1-1 performance
functions, 6-1 index column order, 3-22
globalization support, 8-1 PHP
managing database objects, 3-1 introduction, 1-8
packages, 6-1 pipe, 6-18
PL/SQL, 5-1 PL/SQL, 5-1
procedures, 6-1 %ROWTYPE attribute, 5-12
SQL, 4-1 %TYPE attribute, 5-12
SQL*Plus, A-1 anonymous blocks, 5-2
subprograms, 6-1 arrays, 5-20
triggers, 7-1 assigning values with SELECT INTO, 5-11
assignment operator, 5-8
bind variables, 5-23
P
block structure, 5-5
PACKAGE collections, 5-20
with SQL CREATE statement, 6-3, 6-14 comments, 5-6
package control structures, 5-14
writing with PL/SQL, 6-11 cursor, 5-19
PACKAGE BODY data structures, 5-19
with SQL CREATE statement, 6-3, 6-14 declarations using DEFAULT, 5-11
packaged subprograms, 6-2 declarations using NOT NULL, 5-11
packages declaring constants, 5-7
accessing variables, 6-17 declaring variables, 5-7
body, 6-2 DEFAULT keyword for assignments, 5-11
calling subprograms in, 6-16 displaying output, 5-11, 6-18
creating, 6-3, 6-14 entering and executing code, 5-2
creating with Object Browser, 6-12 entering code in Script Editor, 5-3
creating with Script Editor, 6-13 entering code in SQL Commands, 5-2
dropping, 6-16 error handling, 5-23
editing, 6-15 exception handling, 5-23
guidelines for writing, 6-11 identifiers, 5-8
hidden declarations, 6-3 input data, 5-12
overview, 6-1 introduction, 1-2
overview of Oracle supplied, 6-17 literals, 5-9
product-specific, 6-17 local subprograms, 5-17
specification, 6-2 nested tables, 5-20
understanding, 6-2 output data, 5-12
variables, 6-17 overview of, 5-1
viewing with Object Browser, 6-13 processing queries, 5-21
visibility of contents, 6-3 program units, 5-1
parameters programming with unicode, 8-19
calendar, 8-11 records, 5-21
linguistic sorts, 8-15 SELECT INTO, 5-11
monetary, 8-13 stored procedures, 5-2
NLS_CALENDAR, 8-12 subprograms
NLS_COMP, 8-17 calling, 6-9
NLS_CURRENCY, 8-14 trigger bodies, 7-4
NLS_DATE_FORMAT, 8-8 using dynamic SQL, 5-22
NLS_DATE_LANGUAGE, 8-9 using features, 5-5

Index-6 Beta Draft


variable assignments, 5-8 S
writing reusable code, 6-11
PL/SQL and SQL and Unicode, 8-19 scale
primary key greater than precision, 2-5
for a table, 3-7 schema objects
PRIMARY KEY constraints accessing, 3-1
multiple columns in, 3-8 description, 3-1
UNIQUE key constraint vs., 3-8 tables, 3-4
privileges schemas
dropping triggers, 7-14 description, 3-1
needed on triggers, 7-6 scientific notation, 5-9
recompiling triggers, 7-16 scope
triggers, 7-6 exceptions in PL/SQL, 5-26
PROCEDURE Script Editor
with CREATE statement, 6-2, 6-7 executing SQL statements, 4-3
procedures, 5-2 SELECT INTO
called by triggers, 7-6 PL/SQL, 5-11
creating, 6-2, 6-7 SELECT statements, 4-4
execute, 6-3 SELF_IS_NULL exception, 5-25
managing, 6-3 sequences
overview, 6-1 creating, 3-27
stored procedures, 5-2 description, 3-26
program units, 5-1, 6-11 displaying, 3-27
PROGRAM_ERROR exception, 5-25 dropping, 3-28
pseudocolumns managing, 3-26
ROWNUM, 4-11 using in SQL statements, 4-11
SYSDATE, 4-11 SERVEROUTPUT
USER, 4-11 displaying output from PL/SQL, 5-12
using in SQL statements, 4-11 setting ON to display output, 6-18
PUT_LINE SET command
displaying output with, 5-11 for SQL*Plus settings, A-3
single-line comments, 5-6
sorting
Q specifying nondefault linguistic sorts, 8-15, 8-17
queries source types
in DML, 4-8 description, 6-1
quoting character literals, 4-5 managing, 6-1
SPOOL command
SQL*Plus, A-4
R SQL, 1-2
raising exceptions aggregate functions, 4-15
triggers, 7-5 arithmetic operators, 4-13
records character functions, 4-12
definition, 5-12 character literals in statements, 4-5
PL/SQL, 5-21 column alias, 4-5
removing a row in a table, 3-18 committing changes with COMMIT, 4-10
reserved words comparison operators, 4-6
syntactic meaning in PL/SQL, 5-8 creating a constraint, 4-17
restrictions creating a table, 4-16
system triggers, 7-6 creating an index, 4-17
ROLLBACK statement, 4-10 data definition language (DDL), 4-15
row triggers data manipulation language (DML), 4-8
defining, 7-3 date functions, 4-13
timing, 7-2 deleting rows in a table with DELETE, 4-9
UPDATE statements and, 7-4 displaying data from multiple tables, 4-7
ROWNUM dropping a sequence, 4-18
pseudocolumn, 4-11 dropping a synonym, 4-18
ROWTYPE attribute dropping a table, 4-18
declaring, 5-12 dynamic, 5-22
ROWTYPE_MISMATCH exception, 5-25 executing statements, 4-2
executing statements in Script Editor, 4-3

Beta Draft Index-7


executing statements in SQL Commands, 4-2 prompt, A-2
functions, 4-11 using variables, A-4
inserting rows in a table with INSERT, 4-8 standalone subprograms, 6-2
introduction of, 1-2 execute, 6-3
joining tables in SELECT, 4-7 managing, 6-3
modifying a constraint, 4-17 statement triggers
modifying a table, 4-17 conditional code for statements, 7-4
modifying an index, 4-17 specifying SQL statement, 7-2
numeric functions, 4-13 timing, 7-2
ORDER BY clause in SELECT, 4-7 UPDATE statements and, 7-4
overview of, 4-1 valid SQL statements, 7-6
PL/SQL and, 5-1 STORAGE_ERROR exception, 5-25
programming with unicode, 8-19 stored procedures, 5-2
pseudocolumns, 4-11 stored subprograms, 6-2
querying data, 4-4 in Oracle database, 6-2
retrieving data from tables, 4-4 storing, 2-4
SELECT statement, 4-4 string literals, 5-9
sequences, 4-11 Unicode, 8-21
statement types, 4-2 Structured Query Language (SQL), 1-2, 4-1
transaction control statements, 4-10 subprograms
types of statements, 4-2 calling from SQL*Plus, 6-8, 6-9
undoing changes with ROLLBACK, 4-10 calling in packages, 6-16
updating data in a table with UPDATE, 4-9 calling with parameters, 6-8
using with Oracle Database Express Edition, 4-1 CREATE FUNCTION, 6-8
WHERE clause in SELECT, 4-6 CREATE PROCEDURE, 6-7
SQL Commands creating with Object Browser, 6-4
executing SQL statements, 4-2 creating with Script Editor, 6-6
SQL functions declaring PL/SQL, 5-17
default values for NLS parameters, 8-23 dropping, 6-10
NCHR, 8-21 editing, 6-10
NLS_INITCAP, 8-22 functions, 6-2
NLS_LOWER, 8-22 local, 6-2
NLS_UPPER, 8-22 managing, 6-3
NLSSORT, 8-22 mixed notation parameters, 6-8
specifying NLS parameters, 8-23 named parameters, 6-8
TO_CHAR, 8-22 overview, 6-1
TO_DATE, 8-22 packaged, 6-2
TO_NUMBER, 8-22 positional parameters, 6-8
unacceptable NLS parameters, 8-24 procedures, 6-2
UNISTR, 8-22 standalone, 6-2
SQL statements stored, 6-2
categories, 4-2 viewing with Object Browser, 6-5
in trigger bodies, 7-4, 7-6 SUBSCRIPT_BEYOND_COUNT exception, 5-25
not allowed in triggers, 7-6 SUBSCRIPT_OUTSIDE_LIMIT exception, 5-25
SQL*Plus synonyms
defining a variable, A-4 creating, 3-28
DESCRIBE command, A-3 description, 3-28
displaying help, A-2 displaying, 3-29
entering commands and statements, A-2 dropping, 3-29
executing commands and statements, A-2 managing, 3-28
exiting, A-2 SYS_INVALID_ROWID exception, 5-25
HELP command, A-2 SYSDATE
overview, A-1 pseudocolumn, 4-11
prompting for a variable, A-4
running SQL scripts, A-3
T
SET command, A-3
settings, A-3 table-level constraints, 3-7
SPOOL command, A-4 tables
spooling output, A-4 adding a column, 3-11
starting from the operating system command adding a foreign key, 3-13

Index-8 Beta Draft


adding a new constraint, 3-12 creating with an exception handler, 7-11
adding data, 3-15 creating with BEFORE and WHEN, 7-11
creating, 3-9 creating with Object Browser, 7-8
displaying, 3-10 creating with Script Editor, 7-7
dropping, 3-19 dependencies, 7-15
dropping a column, 3-12 designing, 7-5
managing, 3-4 detecting the operation that fired a trigger, 7-4
modifying data, 3-18 disabling, 7-5, 7-14
primary key, 3-7 enabling, 7-5, 7-14
removing a row, 3-18 error conditions and exceptions, 7-5
viewing data, 3-17 errors, 7-5
territory definition, 8-7 events, 7-2
territory support, 8-2 exceptions, 7-5
time and date data fired multiple times with BEFORE option, 7-3
storing, 2-7 firing once for each update, 7-12
time and date parameters, 8-8 FOR EACH ROW clause, 7-3
time zone FOR EACH ROW option, 7-3
parameters, 8-10 guidelines for design, 7-5
TIMEOUT_ON_RESOURCE exception, 5-25 illegal SQL statements, 7-6
TIMESTAMP datatype, 2-7 integrity constraints vs., 7-5
TIMESTAMP WITH LOCAL TIME ZONE managing, 7-7
datatype, 2-7 modifying, 7-14
TIMESTAMP WITH TIME ZONE datatype, 2-7 naming, 7-2
TO_CHAR SQL function, 8-22 NEW column value, 7-4
default date format, 8-8 OLD column value, 7-4
group separator, 8-13 overview, 7-1
language for dates, 8-9 privileges, 7-6
spelling of days and months, 8-9 to drop, 7-14
TO_DATE function, 2-9 privileges needed, 7-6
TO_DATE SQL function, 8-22 procedures and, 7-6
default date format, 8-8 recompiling, 7-16
language for dates, 8-9 remote dependencies and, 7-6
spelling of days and months, 8-9 restrictions, 7-3, 7-6
TO_NUMBER SQL function, 8-22 row, 7-3
TOO_MANY_ROWS exception, 5-25 stored, 7-15
transaction control statements, 4-10 types, 7-2
transactions viewing with Object Browser, 7-9
transaction control statements, 4-10 WHEN clause, 7-3
trigger when fired, 7-2
disabled triggrs
definition, 7-5 triggering statement, 7-2
enabled TRUE value, 5-10
definition, 7-5 TYPE attribute
triggers declaring, 5-13
accessing column values, 7-4
AFTER, 7-2, 7-4
U
AFTER option, 7-3
as a stored PL/SQL subprogram, 7-1 Unicode
BEFORE, 7-2, 7-4 PL/SQL and SQL, 8-19
BEFORE option, 7-3 programming, 8-3
body, 7-6 programming with SQL and PL/SQL, 8-19
column list in UPDATE, 7-4 string literals, 8-21
compiled, 7-15 unique key
compiling, 7-15 on a column, 3-8
conditional predicates, 7-4 UNIQUE key constraints
controlling when fired, 7-2 PRIMARY KEY constraint vs., 3-8
correlation names, 7-4 UNISTR SQL function, 8-22
creating, 7-1, 7-6 UPDATE statement, 4-8, 4-9
creating LOGON and LOGOFF, 7-13 column values and triggers, 7-4
creating with AFTER and FOR EACH ROW, 7-10 triggers and, 7-4

Beta Draft Index-9


URL (uniform resource locator), 6-18
USER
pseudocolumn, 4-11
UTL_FILE package, 6-18
UTL_HTTP package, 6-18
UTL_SMTP package, 6-19

V
VALUE_ERROR exception, 5-25
VARCHAR2 datatype, 2-3
variables
accessing in packages, 6-17
bind, 5-23
declaring in PL/SQL, 5-7
passing as IN OUT parameter, 5-18
using with SQL*Plus, A-4
viewing table data, 3-17
views
creating, 3-25
description, 3-24
displaying, 3-26
dropping, 3-26
managing, 3-24
visibility
of package contents, 6-3

W
WHEN clause, 7-3
cannot contain PL/SQL expressions, 7-3
correlation names, 7-4
examples, 7-11
WHERE clause
using with SELECT, 4-6
WHILE-LOOP statement
overview, 5-16

Z
ZERO_DIVIDE exception, 5-25

Index-10 Beta Draft

You might also like