2 Day Developer Guide
2 Day Developer Guide
2 Day Developer Guide
October 2005
Beta Draft
Oracle Database Express Edition 2 Day Developer Guide, 10g Release 2 (10.2)
B25108-01
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
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
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
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
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/
Structure
This guide contains the following chapters:
Appendix A, "SQL*Plus"
This appendix provides an overview of SQL*Plus.
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.
See Also:
■ Oracle Database Application Developer's Guide - Fundamentals for a
complete overview of application development with Oracle.
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".
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".
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.
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.
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.
1-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Other Development Environments
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
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.
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
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
1-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Other Development Environments
See Also:
■ Oracle Database Express Edition 2 Day Plus .NET Developer Guide
See Also:
■ Oracle Database Express Edition 2 Day Plus .NET Developer Guide
See Also:
■ Oracle Database Express Edition 2 Day Plus .NET Developer Guide
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
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
1-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
2
Using Datatypes
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
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.
See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using Object Browser
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
See Also:
■ Oracle Database SQL Reference for information on datatypes
■ Oracle Database Globalization Support Guide for information on
globalization support
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
Table 2–1 show how Oracle stores data using different values for precision and scale.
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.
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
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.
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.
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
3-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Overview of Managing Objects
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
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.
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).
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 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.
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.
■ 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.
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
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.
3-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables
3-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables
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.
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
3-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Tables
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.
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
See Also: Oracle Database Express Edition HTML DB User’s Guide for
information on managing indexes
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.
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.
■ 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.
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.
3-22 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Indexes
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.
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.
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.
13. Click the SQL button to view the SQL statement that creates the view.
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.
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.
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
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
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.
See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Commands
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.
See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Scripts
4-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Retrieving Data With Queries
See Also:
■ Oracle Database SQL Reference for detailed information on the SQL
SELECT statement.
See Also:
■ Oracle Database Globalization Support Guide to learn about national
character sets
■ Oracle Database SQL Reference to learn about character literals
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–3 shows how to use SELECT with a WHERE clause and several comparison
operators to retrieve specific data from the employees table.
-- 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 retrieves employees where the last name starts with Mar
SELECT employee_id, last_name FROM employees WHERE last_name LIKE 'Mar%';
-- 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
See Also:
■ Oracle Database SQL Reference for detailed information on using
the WHERE clause.
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.
-- 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 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.
4-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Manipulating Data With SQL Statements
-- 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.
-- update the salary for employee 301, multiply the salary by 105%
UPDATE employees SET salary = salary * 1.05 WHERE employee_id = 301;
See Also:
■ Oracle Database SQL Reference for information on the UPDATE
statement.
See Also:
■ Oracle Database SQL Reference for information on the DELETE
statement.
See Also:
■ Oracle Database SQL Reference for information on the COMMIT
statement.
-- rollback the delete statement because the previous DELETE was incorrect
ROLLBACK;
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
See Also:
■ Oracle Database SQL Reference for detailed information on SQL
functions.
-- 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.
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.
-- 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';
-- 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;
4-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using Pseudocolumns, Sequences, and SQL Functions
See Also: Oracle Database SQL Reference for details about each
function
■ 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.
4-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL Data Definition Language Statements
FROM employees;
Example 4–18 shows how to use date functions with format masks.
-- 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;
-- you can use MIN to find the minimum salary for employees with manager 122
SELECT MIN(salary) FROM employees WHERE manager_id = 122;
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
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.
4-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL Data Definition Language Statements
-- 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;
-- 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';
4-18 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL Data Definition Language Statements
4-20 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
5
Using PL/SQL
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.
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".
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.
See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Commands
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.
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.
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.
EXCEPTION
5-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL
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.
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
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.
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.
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.
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
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;
/
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.
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.
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..
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.
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.
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–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.
5-16 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Utilizing the Main Features of PL/SQL
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:
In Example 5–22, both a variable and a numeric literal are passed as a parameter to a
more complex procedure.
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;
/
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.
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.
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.
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.
See Also:
■ Oracle Database PL/SQL User's Guide and Reference for information
on PL/SQL records.
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.
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
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;
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
5-24 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Handling PL/SQL Errors
5-26 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Handling PL/SQL Errors
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.
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;
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.
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
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
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
6-6 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Subprograms
See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Scripts
|| 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.
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.
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.
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.
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.
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
6-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Packages
See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Scripts
6-14 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Packages
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.
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;
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.
See Also:
■ Oracle Database PL/SQL Packages and Types Reference for
information on and usage of product-specific packages.
6-18 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
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
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.
7-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Overview of Triggers
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.
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
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
■ Use triggers on DATABASE judiciously. They are executed for every user every
time the event occurs on which the trigger is created.
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.
Then, trigger my_trigger is not fired after the creation of my_trigger. Oracle
Database does not fire a trigger that is not committed.
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.
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.
See Also: Oracle Database Express Edition HTML DB User’s Guide for
detailed information on using SQL Scripts
7-8 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Triggers in the Database
12. Click the SQL button to view the SQL statements for creating the trigger.
See Also: Oracle Database Express Edition HTML DB User’s Guide for
information on managing 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.
7-10 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Managing Triggers in the Database
-- 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;
/
-- cleanup: rollback the added row and updates, drop the trigger and log table
ROLLBACK;
DROP TRIGGER log_emp_update;
DROP TABLE emp_update_log;
In Example 7–6, a trigger is created to write a record to a table whenever a user logs off
the HR account.
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.
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.
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.
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.
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
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.
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.
-- 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);
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.
-- 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);
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 Formats
Different date formats are shown in Table 8–1.
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'
You should see output similar to the following, depending on the current system date:
TO_CHAR(SYSDATE,'DAY:DDMON
--------------------------
Jeudi :06 Octobre 2005
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');
Time Formats
Different time formats are shown in Table 8–2.
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.
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.
You should see output similar to the following, depending on the current system date:
SYSDATE
--------------------
24 Ramadan 1422
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.
8-12 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Setting up the Globalization Support Environment
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;
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
Currency Formats
Different currency formats are used throughout the world. Some typical ones are
shown in Table 8–4.
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.
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.
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.
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
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.
-- 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;
-- 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;
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.
-- select the last name of those employees whose last name begin with C
SELECT last_name FROM employees
WHERE last_name LIKE 'C%';
-- select the last name of those employees whose last name begin with C
SELECT last_name FROM employees
WHERE last_name LIKE 'C%';
--------------
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.
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
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.
See Also:
■ Oracle Database Concepts for more information about length
semantics
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.
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.
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.
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.
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
Table 8–5 shows which NLS parameters are valid for specific SQL functions.
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
A-2 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
Using SQL*Plus
Note that a terminating semi-colon (;) is optional with SQL *Plus commands.
See Also:
■ SQL*Plus User's Guide and Reference for information setting up the
SQL*Plus environment with a login file
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.
A-4 Oracle Database Express Edition 2 Day Developer Guide Beta Draft
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
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