Entry Topic
Oracle7 Server SQL Language Reference Manual

Oracle7™ Server SQL Language Reference Manual

PREFACE

CHAPTER 1. INTRODUCTION TO SQL

CHAPTER 2. ELEMENTS OF SQL

CHAPTER 3. OPERATORS, FUNCTIONS, EXPRESSIONS, CONDITIONS

CHAPTER 4. COMMANDS - SUMMARY OF COMMANDS TO COMMENT

CHAPTER 5. COMMANDS - COMMITTO CREATE ROLE

CHAPTER 6. COMMANDS - CREATE ROLLBACK SEGMENT TO DROP SYNONYM

CHAPTER 7. COMMANDS - DROP TABLE TO ROLLBACK

CHAPTER 8. COMMANDS - ROLLBACK TO WHENEVER

APPENDIX A. SUMMARY OF CHANGES TO SQL IN ORACLE7

APPENDIX B. SYNTAX

APPENDIX C. ORACLE AND STANDARD SQL

APPENDIX D. OPERATING SYSTEM SPECIFIC INFORMATION


This help file created via:

 Version 1.0n

© 1994 Oracle Corporation Inc.

Authored by KM .


Part# A12714-1


Oracle7ä Server SQL Language Reference Manual
Oracle7™ Server SQL Language Reference Manual

Part No. A12714-1

August 10, 1993

Oracle7 Server SQL Language Reference Manual

Part No. A12714-1

Copyright  1993 Oracle Corporation

Contributing Author:  Brian Linden

Contributors:  Lori Asher, Steven Bobrowski, Bill Bridge, Stephen Faris, John Frazzini, Gary Hallmark, Michael Hartstein, Terry Hayes, Ruth Hiltner, Ken Jacobs, Jonathan Klein, Robert Kooi, Walter Lindsay, Andrew Mendelsohn, Mark Moore, Ed Peeler, Maria Pratt, and Kevin Wharton

This software/documentation contains proprietary information of Oracle Corporation; it is provided under a license agreement containing restrictions on use and disclosure and is also protected by copyright law.  Reverse engineering of the software is prohibited.

If this software/documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the following legend is applicable:

Restricted Rights Legend  Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software (October 1988). Oracle Corporation, 500 Oracle Parkway, Redwood City, CA  94065.

If this software/documentation is delivered to a U.S. Government Agency not within the Department of Defense, then it is delivered with "Restricted Rights," as defined in FAR 52.227-14, Rights in Data - General, including Alternate III (June 1987).

The information in this document is subject to change without notice.   If you find any problems in the documentation, please report them to us in writing.   Oracle Corporation does not warrant that this document is error-free.

ORACLE, CASE*Dictionary, Pro*Ada, Pro*COBOL, Pro*FORTRAN, Pro*Pascal, Pro*PL/I, SQL*Connect, SQL*DBA, SQL*Forms, SQL*Loader, SQL*Net, and SQL*Plus are registered trademarks of Oracle Corporation.

CASE*Designer, CASE*Method, ORACLE7, ORACLE Parallel Server, PL/SQL, Pro*C, SQL*Module, and Trusted ORACLE7 are trademarks of Oracle Corporation.

DEC, VAX, and VMS are registered trademarks of Digital Equipment Corportion.  DECnet is a trademark of Digital Equipment Coropration.

HP is a registered trademark of Hewlett-Packard.

IBM is a registered trademark of International Business Machines.

DB2 and SQL/DS are trademarks of International Business Machines.


Preface


PREFACE

The ORACLE7 Server SQL Language  contains a complete description of SQL (Structured Query Language), the relational database language that is used to create, store, modify, retrieve, and manage information in an ORACLE7 database.

The language described in this Manual is the SQL implemented by Oracle Corporation for the ORACLE7 Server. This SQL is a superset of the American National Standards Institute (ANSI) and the International Standards Organization (ISO) SQL standard.

This Manual describes all features of ORACLE7's SQL language, including those available only with the optional components of ORACLE7. These components include:

•	procedural option

•	distributed option

•	Parallel Server option

This Manual notes any features that are only available with one of these options. This Manual also describes and notes parts of ORACLE7's SQL language used only with the Trusted ORACLE7 Server.

This Manual also includes embedded SQL for use with the ORACLE Precompilers. For additional information on embedded SQL, see the Programmer's Guide to the ORACLE Precompilers. For information on PL/SQL, ORACLE's procedural language extension to SQL, see the PL/SQL User's Guide and .

Audience

This Manual is intended for technical professionals and computer programmers as well as for non-programmers who want to use SQL. The description of each feature is addressed to an ORACLE user who using the feature, as opposed to another user who may be affected by the feature.

How this Manual is Organized

This Manual is divided into these parts: @HALFLINESMUSH =

Chapter 1:  Introduction to SQL      This chapter defines SQL and describes its history as well as the advantages of using it to access relational databases.

Chapter 2:  Elements of SQL      This chapter describes the basic building blocks of an ORACLE database and the ORACLE SQL language.

Chapter 3:  Operators, Functions, Expressions, Conditions      This chapter describes how to use SQL operators and functions to combine data into expressions and conditions.

Chapter 4:  Commands      This chapter lists and describes all of the SQL commands in alphabetical order.

Appendix A:  Summary of Changes to SQL in ORACLE7      This appendix lists differences in the SQL language between ORACLE Version 6 and ORACLE7. If you are very familiar with ORACLE Version 6, you may want to look at this appendix for a summary of the changes to SQL for ORACLE7.

Appendix B:  Syntax      This appendix provides a summary of SQL syntax.

Appendix C:  ORACLE and Standard SQL      This appendix describes the compliance of ORACLE SQL to the ANSI and ISO SQL standards and lists parts of the ORACLE SQL that extend beyond these standards.

Appendix D:  Operating System Specific Information      This appendix lists the information in this Manual that varies depending on the operating system on which you are using ORACLE. For the actual information for your operating system, see the ORACLE installation or user's guide for your operating system.

Related Publications

This Manual occasionally refers to other ORACLE manuals for information about ORACLE concepts other than SQL. References to these manuals are also marked with the icons shown in the left margin:SQL*Forms Designer's Reference>SQL*Plus User's Guide and Reference Manual>SQL*Module User's Guide and Reference>

•

•	ORACLE7 Server Concepts , Part No. 6693-70. This manual provides general information about ORACLE and how it works.

•	ORACLE7 Server Administrator's , Part No. 6694-70. This guide tells you how to administer ORACLE.

•	ORACLE7 Server Application , Part No. 6695-70. This guide tells you how to develop applications for ORACLE.

•	ORACLE7 Server Utilities User's Guide, Part No. 3602-70. This guide tells you how to use SQL*DBA, Export, Import, and SQL*Loader, the utilities bundled with ORACLE.

•	PL/SQL User's Guide and , Part No. 800-20. This guide provides information about PL/SQL, ORACLE's procedural language extension to SQL.

•	Programmer's Guide to the , Part No. 5315-15. This guide tells you how to use the ORACLE Precompilers to write embedded SQL programs.

•	Programmer's Guide to the ORACLE , Part No. 5411-70. This guide tells you how to write programs using the ORACLE Call Interfaces (OCIs).

•	ORACLE7 Parallel Server Administrator's , Part No. 5990-70. This guide provides information about using ORACLE with the Parallel Server option to access a single database with multiple instances.

•	ORACLE7 Server Migration , Part No. 6617-70. This guide tells you how to migrate an ORACLE Version 6 database to ORACLE7.

•	Trusted ORACLE7 Server Administrator's , Part No. 6610-70. This guide provides information specific to using Trusted ORACLE, Oracle's multilevel secure database management system product.

This Manual also refers to other ORACLE manuals that contain detailed information for using ORACLE on a specific operating system. These ORACLE manuals are often called installation or user's guides, although the exact name may vary among operating systems. For example, for information on using ORACLE specifically on the DEC VAX/VMS operating system, you should refer to the ORACLE7 Server for VMS Installation and Administrator's Guide. In this Manual, occasions when you should refer to operating system specific ORACLE manuals are marked with the icon shown in the left margin. Also,  Appendix D "Operating System Specific  lists all parts of SQL that depend on your operating system.

This Manual also refers to other ORACLE manuals that contain detailed information for using ORACLE with SQL*Net, Oracle's networking product, with a specific network protocol. For example, for information on connecting to ORACLE through SQL*Net with the TCP/IP protocol, you should refer to the SQL*Net TCP/IP User's Guide. In this Manual, occasions when you should refer to protocol specific SQL*Net manuals are marked with the icon shown in the left margin.

Oracle Corporation also publishes a file commonly named README.DOC. This file is available on your distribution media and describes differences between minor releases of Oracle software that are not accompanied by new manuals. The exact name and location of this file may vary depending on your operating system. Read this file to learn about changes to the software that do not appear in the manuals.

Conventions Used in this Manual

This section explains the conventions used in this Manual including:

•	icons

•	text

•	syntax diagrams and notation

•	examples

•	example data

 Icons

In addition to the book icons shown in the previous section, these special icons alert you to particular information in this Manual:

Suggestion: The lightbulb highlights suggestions and practical tips that could save time, make procedures easier, and so on.

Warning: The warning symbol highlights text that warns you of actions that could be particularly damaging or fatal to your system.

 Text

This section explains the conventions used within the text:

UPPERCASE	Uppercase text is used to call attention to names of  SQL and SQL*DBA commands, SQL keywords, filenames, and initialization parameters. For information on initialization parameters, see Appendix A "Initialization  of the ORACLE7 Server Administrator's Guide.

italics	Italicized text is used call to attention to definitions of terms and parameters of SQL commands.

 Syntax Diagrams and Notation

The syntax diagrams and notation in this Manual show the complete syntax for SQL commands, functions, and other elements. This section tells you how to read syntax diagrams and examples and write SQL statements based on them. Syntax diagrams are made up of these items:

Keywords      Keywords are words that have special meanings in the SQL language. In the syntax diagrams in this Manual, keywords appear in uppercase. You must use keywords in your SQL statements exactly as they appear in the syntax diagram, except that they can be either uppercase or lowercase. For example, you must use the CREATE keyword to begin your CREATE TABLE statements just as it appears in the CREATE TABLE syntax diagram.

Parameters      Parameters act as place-holders in syntax diagrams. They appear in lowercase. Parameters are usually names of database objects, ORACLE datatype names, or expressions. When you see a parameter in a syntax diagram, substitute an object or expression of the appropriate type in your SQL statement. For example, to write a CREATE TABLE statement, use the name of the table you want to create, such as EMP, in place of the table parameter in the syntax diagram. Note that parameter names appear in italics in the text.

This lists shows parameters that appear in the syntax diagrams in this Manual and examples of the values you might substitute for them in your statements:

Parameter	Description	Examples

table	The substitution value 	emp

must be the name of

an object of the type

specified by the pa

rameter. For a list of

all types of objects,,

see the section "Sche

ma Objects" on page

2 - 2.

c	The substitution value 	T

must be a single char

acter from your com	s

puter's character set.

'text'	The substitution value 	'Employee re

must be a character 	cords'

literal in single

quotes. See the syntax

description of 'text' on

page 2 - 17.,

char	The substitution value 	ename

must be an expression

of datatype CHAR or 	'Smith'

VARCHAR2 or a

character literal in

single quotes.

condition	The substitution value 	ename > 'A'

must be a condition

that evaluates to

TRUE or FALSE. See

the syntax description

of condition on page

NO TAG.

date	The substitution value 	TO_DATE(

d	must be a date 	'01-Jan-1994',

constant or an expres	'DD-MON-YYYY')

sion of DATE data

type.

expr	The substitution value 	sal + 1000

can be an expression

of any datatype as de

fined in the syntax de

scription of expr on

page NO TAG.

integer	The substitution value 	72

must be an integer as

defined by the syntax

description of integer

on page 2 - 18.

label	The substitution value 	TO_LABEL(

must be an expression 	'SENSITIVE:

of datatype MLSLA	ALPHA')

BEL. For information

on such expressions,

see the Trusted

ORACLE7 Server .

number 	The substitution value 	AVG(sal)

m	must be an  expres

n	sion of NUMBER da	15 * 7

tatype or a number

constant as defined in

the syntax description

of number on page

2 - 19.

raw	The substitution value 	HEXTORAW('7D')

must be an expression

of datatype RAW.

rowid	The substitution value 	00000462.0001.0001

must be an expression

of datatype ROWID.

subquery 	The substitution value 	SELECT ename

must be a SELECT 	 	FROM emp

statement contained

in another SQL state

ment. See the syntax

description of sub

query on page 8 - 357.

:host_variable	The substitution value 	:employee_number

must be the name of a

variable declared in

an embedded SQL

program. This Manu

al also uses :host_inte

ger and :host_string to

indicate specific data

types.

cursor	The substitution value 	curs1

must be the name of a

cursor in an em

bedded SQL pro

gram.

db_name	The substitution value 	sales_db

must be the name of a

non-default database

in an embedded SQL

program.

db_string	The substitution value

must be the database

identification string

for a SQL*Net data

base connection.  For

details,, see the user's

guide for your specif

ic SQL*Net protocol.,

statement_name	The substitution value 	s1

block_name	must be an identifier 	b1

for a SQL statement

or PL/SQL block.

This Manual uses these different means for showing syntax:

•	syntax diagrams

•	BNF notation

Syntax Diagrams      This Manual uses syntax diagrams to show SQL commands in Chapter 4 "Commands" and to show other elements of the SQL language in Chapter 2 "Elements of SQL" and Chapter 3 "Operators, Functions, . These syntax diagrams use lines and arrows to show syntactic structure. This list shows combinations of lines and arrows and their meanings within syntax diagrams:

BNF Notation      This Manual uses BNF notation to show SQL functions in Chapter 3 "Operators,  and SQL commands in Appendix B "Syntax". BNF notation uses punctuation to show syntactic structure. This list shows the punctuation marks, their purposes, and examples of how they appear in BNF notation:

Punctuation	Meaning	Example

braces with	You must use one of 	{ ENABLE

vertical bars	the items in the braces 	| DISABLE

{ | }	separated by vertical 	| COMPILE }

bars.

brackets	You can optionally 	[PUBLIC]

[ ]	use the item in the

brackets. If the brack	[ CACHE integer

ets enclose multiple 	| NOCACHE]

items separated by

vertical bars,, you can

use any one item or

none at all.

ellipsis	You can optionally re	[, column] ...

...	peat the previous

item multiple times.

underline	If you omit all brack	[EXCLUSIVE

eted items,, ORACLE 	| PARALLEL ]

uses the underlined

item by default.

 Examples

This Manual also contains many example SQL statements. These examples show you how to use elements of SQL. This is an example of a CREATE TABLE statement:

CREATE TABLE accounts

(accno    NUMBER,

 owner    VARCHAR2(10),

 balance  NUMBER(7,2) )

Note that examples appear in a different font than the text.

Examples follow these case conventions:

•	Keywords, such as CREATE and NUMBER, appear in uppercase.

•	Names of database objects and their parts, such as ACCOUNTS and ACCNO, appear in lowercase, although they appear in uppercase in the text.

SQL is not case-sensitive (except for quoted identifiers), so you need not follow these conventions when writing your own SQL statements, although your statements may be easier for you to read if you do.

Some ORACLE tools require you to terminate SQL statements with a special character. For example, SQL statements issued through SQL*DBA or SQL*Plus must be terminated with a semi-colon (;). The examples shown in this Manual are not terminated. If you issue these examples statements to ORACLE, you must terminate them with the special character expected by the ORACLE tool you are using.

 Example Data

Many of the examples in this Manual operate on sample tables. The definitions of some of these tables appear in a SQL script available on your distribution media. On most operating systems the name of this script is UTLSAMPL.SQL, although its exact name and location may vary depending on your operating system. This script creates sample users and creates these sample tables in the schema of the user SCOTT:

CREATE TABLE dept

(deptno    NUMBER(2)      CONSTRAINT pk_dept PRIMARY KEY,

 dname     VARCHAR2(14),

 loc       VARCHAR2(13) )

CREATE TABLE emp

(empno     NUMBER(4)      CONSTRAINT pk_emp PRIMARY KEY,

 ename     VARCHAR2(10),

 job       VARCHAR2(9),

 mgr       NUMBER(4),

 hiredate  DATE,

 sal       NUMBER(7,2),

 comm      NUMBER(7,2),

 deptno    NUMBER(2)    CONSTRAINT fk_deptno REFERENCES emp )

CREATE TABLE bonus

(ename     VARCHAR2(10),

 job       VARCHAR2(9),

 sal       NUMBER,

 comm      NUMBER )

CREATE TABLE salgrade

(grade     NUMBER,

 losal     NUMBER,

 hisal     NUMBER )

The script also fills the sample tables with this data:

SELECT * FROM dept

DEPTNO  DNAME      LOC

------- ---------- ---------

10      ACCOUNTING NEW YORK

20      RESEARCH   DALLAS

30      SALES      CHICAGO 40      OPERATIONS BOSTON

SELECT * FROM emp

EMPNO ENAME   JOB          MGR  HIREDATE    SAL   COMM  DEPTNO

----- ------- --------- ------ --------- ------ ------ -------

7369 SMITH   CLERK       7902 17-DEC-80    800             20

7499 ALLEN   SALESMAN    7698 20-FEB-81   1600    300      30

7521 WARD    SALESMAN    7698 22-FEB-81   1250    500      30

7566 JONES   MANAGER     7839 02-APR-81   2975             20

7654 MARTIN  SALESMAN    7698 28-SEP-81   1250   1400      30

7698 BLAKE   MANAGER     7839 01-MAY-81   2850             30

7782 CLARK   MANAGER     7839 09-JUN-81   2450             10

7788 SCOTT   ANALYST     7566 19-APR-87   3000             20

7839 KING    PRESIDENT        17-NOV-81   5000             10

7844 TURNER  SALESMAN    7698 08-SEP-81   1500             30

7876 ADAMS   CLERK       7788 23-MAY-87   1100             20

7900 JAMES   CLERK       7698 03-DEC-81    950             30

7902 FORD    ANALYST     7566 03-DEC-81   3000             20

7934 MILLER  CLERK       7782 23-JAN-82   1300             10

SELECT * FROM salgrade

GRADE LOSAL HISAL

----- ----- -----

1     700   1200

2     1201  1400

3     1401  2000

4     2001  3000

5     3001  9999

To perform all the operations of the script, run it when you are logged into ORACLE as the user SYSTEM.

Your Comments Are Welcome

We value and appreciate your comments as an ORACLE user and reader of the manuals. As we write, revise, and evaluate, your opinions are the most important input we receive. At the back of this Manual is a Reader's Comment Form that we encourage you to use to tell us both what you like and what you dislike about this (or other) Oracle manuals. If the form has been used, or you would like to contact us, please use the following address or FAX number, or call us at (415) 506-7000.

  	ORACLE7 Server Documentation Manager

 	Oracle Corporation

 	500 Oracle Parkway

 	Redwood Shores, CA  94065

FAX:  (415) 506-7200


CHAPTER 1. INTRODUCTION TO SQL

SQL (Structured Query Language, pronounced "sequel") is the set of commands that all programs and users must use to access data within the ORACLE database. Application programs and ORACLE tools often allow users to access the database without directly using SQL, but these applications in turn must use SQL when executing the user's request. This chapter provides background information on the SQL language used by most relational database systems. Topics include:

•	history of SQL

•	SQL standards

•	benefits of SQL

•	embedded SQL

•	ORACLE SQL lexical conventions

•	ORACLE tools support for SQL

________________________________________

History of SQL

The relational database model was originally developed by Dr. E.F. Codd in the early 1970s. The SQL language was originally developed by IBM in a prototype relational database management system, System R, in the mid 1970s. The original SQL language (SEQUEL2) was described in the November 1976 IBM Journal of R&D. In 1979, Oracle Corporation introduced the first commercially available implementation of SQL. SQL has also been implemented in IBM's DB2 and SQL/DS database systems. Today SQL is widely implemented and is accepted as the industry standard database access language.

________________________________________

SQL Standards

The American National Standards Institute (ANSI) has adopted SQL as the standard language for relational database management systems as defined in the document ANSI X3.135-1989 "Database Language SQL with Integrity Enhancement", or ANSI SQL89. This standard supersedes the earlier version ANSI X3.135-1986 and includes the Integrity Enhancement Feature previously described in ANSI SQL Addendum I. The standard has also been adopted by these organizations:

•	International Standards Organization (ISO) in the document ISO 9075-1989 "Database Language SQL with Integrity Enhancement"

•	United States Federal Government in the Federal Information Processing Standard Publication (FIPS PUB) 127

ANSI has also adopted a standard for Embedded SQL defined in the document ANSI X3.168-1989 "Database Language Embedded SQL".

All major relational database management systems support some form of SQL and most intend to comply with ANSI SQL89. For a description of ORACLE's compliance with these standards as well as ORACLE's extensions to standard SQL, see Appendix C "ORACLE and Standard SQL" of this Manual.

________________________________________

Benefits of SQL

This section describes many of the reasons for SQL's widespread acceptance by relational database vendors as well as end users. Its strengths benefit all ranges of users including application programmers, database administrators, management, and end users.

Non-procedural Language

SQL is a non-procedural language because it:

•	processes sets of records rather than just one at a time

•	provides automatic navigation to the data

SQL allows you to work with higher level data structures. Rather than manipulating single rows, you manage sets of rows. SQL commands accept sets or rows as input and return sets as output. The set property of SQL allows the results of one SQL statement to be used as input to another.

SQL does not require you to specify the access method to the data. This feature makes it easier for you to concentrate on obtaining the desired results. All SQL statements use the optimizer, a part of ORACLE that determines the fastest means of accessing the specified data. The optimizer knows what indexes exist and uses them appropriately. When accessing a table, you need not know about its indexes.

A Language for All Users

SQL is used for all types of database activities by all types of users including:

•	system administrators

•	database administrators

•	security administrators

•	application programmers

•	decision support system personnel

•	many other types of end users

SQL provides easy-to-learn commands that are both consistent and applicable for all users. The basic SQL commands can be learned in a few hours and even the most advanced commands can be mastered in a few days.

Unified Language

SQL provides commands for a variety of tasks including:

•	querying data

•	inserting, updating, and deleting rows in a table

•	creating, replacing, altering, and dropping objects

•	controlling access to the database and its objects

•	guaranteeing database consistency and integrity

Previous database management systems often used a separate language for each of the above categories. SQL unifies all these tasks in one consistent language.

Common Language for All Relational Databases

Because all major relational database management systems support SQL, you can transfer all the skills you have gained with SQL from one database to another. In addition, since all programs written in SQL are portable, they can often be moved from one database to another with very little modification.

________________________________________

Embedded SQL

Embedded SQL refers to the use of standard SQL commands embedded within a procedural programming language. Embedded SQL is a collection of these commands:

•	all SQL commands, such as SELECT and INSERT, available with SQL with interactive tools

•	flow control commands, such as PREPARE and OPEN, which integrate the standard SQL commands within a procedural programming language

Embedded SQL also includes extensions to some standard SQL commands. Chapter 4 "Commands" presents these commands in both standard form and embedded SQL form.

Embedded SQL is supported by the ORACLE Precompilers. The ORACLE Precompilers interpret embedded SQL statements and translate them into statements that can be understood by procedural language compilers.

Each of these ORACLE Precompilers translates embedded SQL programs into a different procedural language:

•	the Pro*Ada Precompiler

•	the Pro*C Precompiler

•	the Pro*COBOL Precompiler

•	the Pro*FORTRAN Precompiler

•	the Pro*Pascal Precompiler

•	the Pro*PL/I Precompiler

For a definition of the ORACLE Precompilers, see the Programmer's Guide to the ORACLE Precompilers.

Embedded SQL Terms

The following embedded SQL terms are used throughout this Manual:

:host_variable	is a language variable declared according to the rules of the procedural language and used in a SQL statement. A host variable can be a predefined type or a user-defined array and can include an associated indicator variable.

You can only use host variables in place of numeric or character expressions. You must precede each host variable by a colon (:) to distinguish it from a schema object name. You cannot use host variables in place of SQL keywords or schema object names.

This Manual also uses terms for host variables with specific datatypes, such as :host_integer and :host_string.

cursor	is an identifier for a cursor.

db_name	is an identifier for a non-default database.

db_string	is the database identification string for a SQL*Net database connection. For details, see the user's guide for your specific SQL*Net protocol.

statement_name block_name	designates an identifier for a SQL statement or PL/SQL block.

________________________________________

Lexical Conventions

The following lexical conventions for issuing SQL statements apply specifically to Oracle's implementation of SQL, but are generally acceptable in all other SQL implementations.

When you issue a SQL statement, you can include one or more tabs, carriage returns, spaces, or comments anywhere a space occurs within the definition of the command. Thus, ORACLE evaluates the following statements in the same manner:

SELECT ENAME,SAL*12,MONTHS_BETWEEN(HIREDATE,SYSDATE) FROM EMP

SELECT ENAME,

    SAL * 12,

    MONTHS_BETWEEN( HIREDATE, SYSDATE )

    FROM   EMP

Case is insignificant in reserved words, keywords, identifiers and parameters. However, case is significant in text literals and quoted names. See the syntax description of 'text' on page 2 - 17.

________________________________________

ORACLE Tools Support for SQL

Most ORACLE tools support all features of ORACLE's SQL language. However, not all tools support all features. This Manual describes the complete functionality of the SQL language. If the ORACLE tool that you are using does not support this complete functionality, you can find a discussion of the restrictions in the manual describing the tool, such as the PL/SQL User's Guide and Reference.


CHAPTER 2. ELEMENTS OF SQL

This chapter contains reference information on the basic elements of SQL that appear in SQL commands. Before using any of the commands described in Chapter 4 "Commands", you should familiarize yourself with the concepts covered in this chapter:

•	schema objects

•	rules and guidelines for naming objects

•	rules and guidelines for referring to objects

•	literals

•	datatypes

•	nulls

•	pseudocolumns

•	comments

________________________________________

Schema Objects

A schema is a collection of logical structures of data, or schema objects. A schema is owned by a database user and has the same name as that user. Each user owns a single schema. Schema objects can be created and manipulated with SQL and include the following types of objects:

•	clusters

•	database links

•	stand-alone stored functions*

•	indexes

•	packages*

•	stand-alone procedures*

•	sequences

•	snapshots*+

•	snapshot logs*

•	synonyms

•	tables

•	database triggers*

•	views

* These objects are available only with ORACLE's procedural option.

+ These objects are available only with ORACLE's distributed option.

Other types of objects are also stored in the database and can be created and manipulated with SQL, but are not contained in a schema:

•	profiles

•	roles

•	rollback segments

•	tablespaces

Most of these objects occupy space in the database.

In this Manual, each type of object is defined in Chapter 4 "Commands" in the section describing the command that creates it. These commands begin with the keyword "CREATE". For example, for the definition of a cluster, see the CREATE CLUSTER command.

You must provide names for most types of objects when you create them. These names must follow the rules listed in the following sections.

Parts of Objects

Some objects are made up of parts that you must also name, such as:

•	columns in a table or view

•	integrity constraints on a table

•	packaged procedures, packaged stored functions, and other objects stored within a package

________________________________________

Naming Objects and Parts

This section tells you how to name objects and their parts. It discusses these topics:

•	rules for naming objects

•	guidelines for naming objects

Certain words cannot or should not be used as object names because they have special meanings in SQL. This section also lists these words.

Object Naming Rules

This section lists rules for the names of objects and their parts.

1.	Names must be from 1 to 30 bytes long with these exceptions:

•	Names of databases are limited to 8 bytes.

•	Names of database links can be as long as 128 bytes.

2.	Names cannot contain quotation marks.

3.	Names are not case-sensitive.

4.	A name must begin with an alphabetic character from your database character set.

5.	Names can only contain alphanumeric characters from your database character set and the characters _, $, and #. Oracle Corporation discourages the use of $ and #.

If your database character set contains multi-byte characters, Oracle Corporation recommends that each name for a user or a role contain at least one single-byte character.

Names of database links can also contain the characters . and @ as shown on page 2 - 13.

6.	A name cannot be an ORACLE reserved word. The following list contains these reserved words. Words followed by an asterisk (*) are also ANSI reserved words.

Reserved words

ACCESS	FILE	NOAUDIT

ADD	FLOAT*	NOCOMPRESS

ALL*	FOR*	NOT*

ALTER	FROM*	NOWAIT

AND	NULL*

ANY*	GRANT*	NUMBER

AS*	GROUP*

ASC*	OF*

AUDIT	HAVING*	OFFLINE

ON*

BETWEEN*	IDENTIFIED	ONLINE

BY*	IMMEDIATE	OPTION*

IN*	OR*

CHAR*	INCREMENT	ORDER*

CHECK*	INDEX

CLUSTER	INITIAL	PCTREE

COLUMN	INSERT*	PRIOR

COMMENT	INTEGER*	PRIVILEGES*

COMPRESS	INTERSECT	PUBLIC*

CONNECT	INTO*

CREATE	IS*	RAW

CURRENT*	RENAME

LEVEL	RESOURCE

DATE	LIKE*	REVOKE

DECIMAL*	LOCK	ROW

DEFAULT*	LONG	ROWID

DELETE	ROWLABEL

DESC*	MAXEXTENTS	ROWNUM

DISTINCT*	MINUS	ROWS

DROP	MODE

MODIFY	SELECT*

ELSE	SESSION

EXCLUSIVE	SET*

EXISTS*	SHARE

SIZE

SMALLINT*	UID	WHENEVER*

START	UNION*	WHERE*

SUCCESSFUL	UNIQUE*	WITH*

SYNONYM	UPDATE*

SYSDATE	USER*

TABLE*	VALIDATE

THEN	VALUES*

TO*	VARCHAR

TRIGGER	VARCHAR2

VIEW*

Depending on the Oracle product you plan to use to access the object, names might be further restricted by other product-specific reserved words. For a list of a product's reserved words, see the manual for the specific product, such as the PL/SQL User's Guide and Reference.

7.	The word DUAL should not be used as a name for an object or part. DUAL is the name of a dummy table frequently accessed by SQL*Plus and SQL*Forms.

8.	The ORACLE SQL language contains other keywords that have special meanings. Because these keywords are not reserved, you can also use them as names for objects and object parts. However, using them as names may make your SQL statements more difficult for you to read.

The following list contains keywords. Keywords marked with asterisks (*) are also ANSI reserved words. For maximum portability to other implementations of SQL, do not use these words as object names.

Keywords

ADMIN	CONTINUE*	FETCH*

AFTER	CONTROLFILE	FLUSH

ALLOCATE	COUNT*	FREELIST

ANALYZE	CURSOR*	FREELISTS

ARCHIVE	CYCLE	FORCE

ARCHIVELOG	FOREIGN*

AUTHORIZATION*	DATABASE	FORTRAN*

AVG*	DATAFILE	FOUND*

DBA	FUNCTION

BACKUP	DEC*

BEGIN*	DECLARE*	GO*

BECOME	DISABLE	GOTO*

BEFORE	DISMOUNT	GROUPS

BLOCK	DOUBLE*

BODY	DUMP*	INCLUDING

INDICATOR*

CACHE	EACH	INITRANS

CANCEL	ENABLE	INSTANCE

CASCADE	END*	INT*

CHANGE	ESCAPE*

CHARACTER*	EVENTS	KEY*

CHECKPOINT	EXCEPT

CLOSE*	EXCEPTIONS	LANGUAGE*

COBOL*	EXEC*	LAYER

COMMIT*	EXPLAIN	LINK

COMPILE	EXECUTE	LISTS

CONSTRAINT	EXTENT	LOGFILE

CONSTRAINTS	EXTERNALLY

CONTENTS

MANAGE	PACKAGE

MANUAL 	PARALLEL	SORT

(continued)

MAX*	PASCAL*	SQLCODE*

MAXDATAFILES	PCTINCREASE	SQLERROR*

MAXINSTANCES	PCTUSED	STATEMENT_ID

MAXLOGFILES	PLAN	STATISTICS

MAXLOGHISTORY	PLI*	STOP

MAXLOGMEMBERS	PRECISION*	STORAGE

MAXTRANS	PRIMARY*	SUM*

MAXVALUE	PRIVATE	SWITCH

MIN*	PROCEDURE*	SYSTEM

MINEXTENTS	PROFILE

MINVALUE	TABLES

MODULE*	QUOTA	TABLESPACE

MOUNT	TEMPORARY

READ	THREAD

NEXT	REAL*	TIME

NEW	RECOVER	TRACING

NOARCHIVELOG	REFERENCES*	TRANSACTION

NOCACHE	REFERENCING	TRIGGERS

NOCYCLE	RESETLOGS	TRUNCATE

NOMAXVALUE	RESTRICTED

NOMINVALUE	REUSE	UNDER

NONE	ROLE	UNLIMITED

NOORDER	ROLES	UNTIL

NORESETLOGS	ROLLBACK*	USE

NORMAL	USING

NOSORT	SAVEPOINT

NUMERIC*	SCHEMA*	WHEN

SCN	WRITE

OFF	SECTION*	WORK*

OLD	SEGMENT

ONLY	SEQUENCE

(continued)

OPTIMAL	SHARED

OPEN*	SNAPSHOT

OWN	SOME*

9.	A name must be unique across its namespace. Objects in the same namespace must have different names.

Figure 2 - 1 shows the namespaces for schema objects. Objects in the same namespace are grouped by solid lines. Because tables and views are in the same namespace, a table and a view in the same schema cannot have the same name. However, because tables and indexes are in different namespaces, a table and an index in the same schema can have the same name.

Each schema in the database has its own namespaces for the objects it contains. This means, for example, that two tables in different schemas are in different namespaces and can have the same name.

Figure 2 - 2 shows the namespaces for other objects. Because the objects in these namespaces are not contained in schemas, these namespaces span the entire database.

Columns in the same table or view cannot have the same name. However, columns in different tables or views can have the same name.

Procedures or functions contained in the same package can have the same name, provided that their arguments are not of the same number and datatypes. Creating multiple procedures or functions with the same name in the same package with different arguments is called overloading the procedure or function.

10.	A name can be enclosed in double quotes. Such names can contain any combination of characters, ignoring rules 3 through 7 in this list. Such names can also include spaces. Once you have given an object a name enclosed in double quotes, you must use double quotes whenever you refer to the object.

You may want to enclose a name in double quotes for any of these reasons:

•	if you want it to contain spaces

•	if you want it to be case-sensitive

•	if you want it to begin with a character other than an alphabetic character, such as a numeric character

•	if you want it to contain characters other than alphanumeric characters and _, $, and #

•	if you want to use a reserved word as a name

By enclosing names in double quotes, you can give the following names to different objects in the same namespace:

emp

"emp"

"Emp"

"EMP "

However, ORACLE interprets these names as the same, so they cannot be used for different objects in the same namespace:

emp

EMP

"EMP"

If you give a user or password a quoted name, the name cannot contain lowercase letters.

Database link names cannot be quoted.

Examples	These are all examples of names:

ename

horse

scott.hiredate

"EVEN THIS & THAT!"

a_very_very_very_long_name

Although column aliases, table aliases, usernames, or passwords are not objects or parts of objects, they must also follow these naming rules with these exceptions

•	Column aliases and table aliases only exist for the execution of a single SQL statement and are not stored in the database, so rule 9 does not apply to them.

•	Passwords do not have namespaces, so rule 9 does not apply to apply to them.

•	Do not use quotes to make usernames and passwords case-sensitive. For additional rules for naming users and passwords, see the CREATE USER command.

Object Naming Guidelines

There are several helpful guidelines for naming objects and their parts:

•	Use full, descriptive, pronounceable names (or well-known abbreviations).

•	Use consistent naming rules.

•	Use the same name to describe the same entity or attribute across tables.

When naming objects, balance the objective of keeping names short and easy to use with the objective of making name as long and descriptive as possible. When in doubt, choose the more descriptive name because the objects in the database may be used by many people over a period of time. Your counterpart ten years from now may have difficulty understanding a database with names like PMDD instead of PAYMENT_DUE_DATE.

Using consistent naming rules helps users understand the part that each table plays in your application. One such rule might be to begin the names of all tables belonging to the FINANCE application with FIN_.

Use the same names to describe the same things across tables. For example, the department number columns of the EMP and DEPT tables are both named DEPTNO.

________________________________________

Referring to Objects and Parts

This section tells you how to refer to objects and their parts in the context of a SQL statement. This section shows you:

•	the general syntax for referring to an object

•	how ORACLE resolves a reference to an object

•	how to refer to objects in schemas other than your own

•	how to refer to objects in remote databases

This syntax diagram shows the general syntax for referring to an object or a part:

where:

object	is the name of the object.

schema	is the schema containing the object. The schema qualifier allows you to refer to an object in a schema other than your own. Note that you must be granted privileges to refer to objects in other schemas. If you omit this qualifier, ORACLE assumes that you are referring to an object in your own schema.

Only schema objects can be qualified with schema. Schema objects are shown in Figure 2 - 1 on page 2 - 8. Other objects, shown in Figure 2 - 2 on page 2 - 9, cannot be qualified with schema because they are not schema objects, except for public synonyms which can optionally be qualified with "PUBLIC" (quotes required).

part	is a part of the object. This identifer allows you to refer to a part of a schema object, such as a column of a table. Note that not all types of objects have parts.

dblink	is the name of the database containing the object. The dblink qualifier allows you to refer to an object in a database other than your local database. If you omit this qualifier, ORACLE assumes that you are referring to an object in your local database. Note that not all SQL statements allow you to access objects on remote databases.

You can include spaces around the periods separating the components of the reference to the object, but it is conventional to omit them.

How ORACLE Resolves Object References

When you refer to an object in a SQL statement, ORACLE considers the context of the SQL statement and locates the object in the appropriate namespace. After locating the object, ORACLE performs the statement's operation on the object. If the named object cannot be found in the appropriate namespace, ORACLE returns an error message.

This example illustrates how ORACLE resolves references to objects within SQL statements. Consider this statement that adds a row of data to a table identified by the name DEPT:

INSERT INTO dept

VALUES (50, 'SUPPORT', 'PARIS')

Based on the context of the statement, ORACLE determines that DEPT can be:

•	a table in your own schema

•	a view in your own schema

•	a private synonym for a table or view

•	a public synonym

ORACLE always attempts to resolve an object reference within the namespaces in your own schema before considering namespaces outside your schema. In this example, ORACLE attempts to resolve the name DEPT in these ways:

1.	ORACLE first attempts to locate the object in the namespace in your own schema containing tables, views, and private synonyms (see Figure 2 - 1 on page 2 - 8). If the object is a private synonym, ORACLE locates the object for which the synonym stands. This object could be in your own schema, another schema, or on another database. The object could also be another synonym, in which case ORACLE locates the object for which this synonym stands.

If the object is in the namespace, ORACLE attempts to perform the statement on the object. In this example, ORACLE attempts to add the row of data to DEPT. If the object is not of the correct type for the statement, ORACLE returns an error message. In this example, DEPT must be a table, view, or a private synonym resolving to a table or view. If DEPT is a sequence, ORACLE returns an error message.

2.	If the object is not in the namespace searched in Step 1, ORACLE searches the namespace containing public synonyms (see Figure 2 - 2 on page 2 - 9). If the object is in the namespace, ORACLE attempts to perform the statement on it. If the object is not of the correct type for the statement, ORACLE returns an error message. In this example, if DEPT is a public synonym for a sequence, ORACLE returns an error message.

Referring to Objects in Other Schemas

To refer to objects in schemas other than your own, prefix the object name with the schema name:

schema.object

For example, this statement drops the EMP table in the schema SCOTT:

DROP TABLE scott.emp

Referring to Objects in Remote Databases

To refer to objects in databases other than your local database, follow the object name with the name of the database linkto that database. A database link is a schema object that causes ORACLE to connect to a remotedatabase to access an object there. This section tells you:

•	how to create database links

•	how to use database links in your SQL statements

 Creating Database Links

You can create a database link with the CREATE DATABASE LINK command described in Chapter 4 "Commands" of this Manual. The command allows you to specify this information about the database link:

•	the name of the database link

•	the connect string to access the remote database

•	the username and password to connect to the remote database

ORACLE stores this information in the data dictionary.

Names     When you create a database link, you must specify its name. The name of a database link can be as long as 128 bytes and can contain periods (.) and the special character @. In these ways, database link names are different from names of other types of objects.

The name that you give to a database link must correspond to the name of the database to which the database link refers and the location of that database in the hierarchy of database names. This syntax diagram shows the form of the name of a database link:

where:

database	specifies the name of the remote database to which the database link connects. The name of the remote database is specified by its initialization parameter DB_NAME.

domain	specifies the domain of the remote database to which the database link connects. If you omit the domains from the name of a database link, ORACLE expands the name by qualifying database with the domain of your local database before storing it in the data dictionary. The domain of a database is specified by the value of its initialization parameter DB_DOMAIN.

connection_qualifier	allows you to further qualify a database link. Using connection qualifiers, you can create multiple database links to the same database. For example, you can use connection qualifiers to create multiple database links to different instances of the ORACLE Parallel Server that access the same database.

Username and Password     The username and password are used by ORACLE to connect to the remote database. The username and password for a database link are optional.

Database String     The database string is the specification used by SQL*Net to access the remote database. For information on writing database strings, see the SQL*Net User's Guide for your specific network protocol. The database string for a database link is optional.

 Referring to Database Links

When you issue a SQL statement that contains a database link, you can specify the database link name in one of these forms:

complete	is the complete database link name as stored in the data dictionary including the database, domain, and optional connection_qualifier components.

partial	contains the database and optional connection_qualifier components, but not the domain component.

ORACLE performs these tasks before connecting to the remote database:

1.	If the database link name specified in the statement is partial, ORACLE expands the name to contain the domain of the local database (specified by the initialization parameter DB_DOMAIN).

2.	ORACLE first searches for a private database link in your own schema with the same name as the database link in the statement, and then, if necessary, searches for a public database link with the same name.

2.1	ORACLE always determines the username and password from	the first matching database link (either private or public). If the	first matching database link has an associated username and password, ORACLE uses it. If it does not have an associated username and password, ORACLE uses your current username and password.

2.2	If the first matching database link has an associated database string, ORACLE uses it. If not, ORACLE searches for the next matching (public) database link. If there is no matching database link, or if no matching link has an associated database string, ORACLE returns an error message.

3.	ORACLE uses the database string to access the remote database. After accessing the remote database, ORACLE verifies that both of these conditions are true:

•	The name of the remote database (specified by its initialization parameter DB_NAME) must match the database component of the database link name.

•	The domain (specified by the initialization parameter DB_DOMAIN) of the remote database must match the domain component of the database link name.

If both of these conditions are true, ORACLE proceeds with the connection, using the username and password chosen in step 2a. If not, ORACLE returns an error message.

4.	If the connection using the database string, username, and password is successful, ORACLE attempts to access the specified object on the remote database using the rules for resolving object references and referring to objects in other schemas presented earlier in this section.

You can enable and disable ORACLE resolution of names for remote objects using the initialization parameter GLOBAL_NAMES and the GLOBAL_NAMES parameter of the ALTER SYSTEM and ALTER SESSION commands.

For more information on remote name resolution, see Chapter 15 "Managing Distributed Databases" of the ORACLE7 Server Administrator's Guide.

________________________________________

Literals

The terms literal and constant value are synonymous in this Manual and refer to a fixed data value. For example, 'JACK', 'BLUE ISLAND', and '101' are all character literals. 5001 is a numeric literal. Note that character literals are enclosed in single quotes. The quotes allow ORACLE to distinguish them from schema object names.

Many SQL statements and functions require you to specify character and numeric literal values. You can also specify literals as part of expressions and conditions. You can specify character literals with the 'text' notation and numeric literals with the integer or number notation, depending on the context of the literal. The syntactic forms of these notations appear in the following sections.

________________________________________

Text

Purpose

To specify a text or character literal. You must use this notation to specify values whenever 'text' or char appear in expressions, conditions, SQL functions, and SQL commands in other parts of this Manual.

Syntax

Keywords and Parameters

c	is any member of the user's character set, except a single quote (').

''	are two single quotes. Because a single quote is used to begin and end text literals, you must use two single quotes to represent one single quote within a literal.

Usage Notes

A text literal must be enclosed in single quotes. This Manual uses the terms text literal and character literal interchangeably.

Text literals have properties of both the CHAR and VARCHAR2 datatypes:

•	Within expressions and conditions, ORACLE treats text literals as though they have the datatype CHAR by comparing them using blank-padded comparison semantics.

•	A text literal can have a maximum length of 2000 bytes.

Examples	'Hello'

'ORACLE.dbs'

'Jackie''s raincoat'

'09-MAR-92'

Related Topics

The syntax description of expr on page NO TAG.

________________________________________

Integer

Purpose

To specify a positive integer. You must use this notation to specify values whenever integer appears in expressions, conditions, SQL functions, and SQL commands described in other parts of this Manual.

Syntax

Keywords and Parameters	digit	is one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

Usage Notes

 An integer can store a maximum of 38 digits of precision.

Examples	7

255

Related Topics

The syntax description of expr on page NO TAG.

________________________________________

Number

Purpose

To specify an integer or a real number. You must use this notation to specify values whenever number appears in expressions, conditions, SQL functions, and SQL commands in other parts of this Manual.

Syntax

Keywords and Parameters	+, -	indicates a positive or negative value. If you omit the sign, a positive value is the default.

digit	is one of 0,1,2,3,4,5,6,7,8 or 9.

e, E	indicates that the number is specified in scientific notation. The digits after the E specify the exponent. The exponent can range between -130 and 125.

Usage Notes

A number can store a maximum of 38 digits of precision.

If you have established a decimal character other than a period (.) with the initialization parameter NLS_NUMERIC_CHARACTERS, you must specify numeric literals with 'text' notation. In such cases, ORACLE automatically converts the text literal to a numeric value.

For more information on this parameter, see Appendix C "National Language Support" of the ORACLE7 Server Administrator's Guide.

Examples	25

+6.34

0.5

25e-03

-1

Related Topics

The syntax description of expr on page NO TAG.

________________________________________

Datatypes

Each literal or column value manipulated by ORACLE has a datatype. A value's datatype associates a fixed set of properties with the value. These properties cause ORACLE to treat values of one datatype differently from values of another. For example, you can add values of NUMBER datatype, but not values of RAW datatype.

When you create a table or cluster, you must specify an internal datatype for each of its columns. When you create a procedure or stored function, you must specify an internal datatype for each of its arguments. 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's datatype. For example, if you insert '01-JAN-92' into a DATE column, ORACLE treats the '01-JAN-92' character string as a DATE value after verifying that it translates to a valid date.

Table 2 - 1 summarizes ORACLE internal datatypes. The rest of this section describes these datatypes in detail.

Note: The ORACLE Precompilers recognize other datatypes in embedded SQL programs. These datatypes are called external dataypes and are associated with host variables. Do not confuse the internal datatypes with external datatypes. For information on external datatypes, including how ORACLE converts between internal and external datatypes, see the Programmer's Guide to the ORACLE Precompilers.

Code	Internal Datatype	Description

1	VARCHAR2(size)	Variable length char

acter string having

maximum length size

bytes. Maximum size

is 2000. You must

specify size for a

VARCHAR2.

2	NUMBER(p,s)	Number having pre

cision p and scale s.

The precision p can

range from 1 to 38.

The scale s can range

from -84 to 127.

8	LONG	Character data of

variable length up to

2 gigabytes, or 231 -1.

13	DATE	Valid date range from

January 1, 4712 BC to

December 31, 4712

AD.

23	RAW(size)	Raw binary data of

length size bytes.

Maximum size is 255

bytes. You must spec

ify size for a RAW.

24	LONG RAW	Raw binary data of

variable  length up to

2 gigabytes.

69	ROWID	Hexadecimal string

representing the

unique address of a

row in its table. This

datatype is primarily

for values returned

by the ROWID

pseudocolumn.

96	CHAR(size)	Fixed length charac

ter data of length size

bytes. Maximum size

is 255. Default size is 1

byte.

106	MLSLABEL	Binary format of an

operating system la

bel. This datatype is

used primarily with

Trusted Oracle.

Table 2 - 1.  Internal Datatype Summary

The codes listed for the datatypes are used internally by ORACLE. The datatype code of a column is returned when you use the DUMP function.

*The DESCRIBE embedded SQL command and the ODESCR call of the ORACLE Call Interfaces (OCIs) returns a code of 12 for the DATE datatype and a code of 11 for the ROWID datatype.

Character Datatypes

Character datatypes are used to manipulate words and free-form text. These datatypes are used to store character (alphanumeric) data in the database character set. They are less restrictive than other datatypes and consequently have fewer properties. For example, character columns can store all alphanumeric values, but NUMBER columns can only store numeric values.

Character data is stored in strings with byte values corresponding to the character set, such as 7-bit ASCII or EBCDIC Code Page 500, specified when the database was created. ORACLE supports both single-byte and multi-byte character sets.

These datatypes are used for character data:

•	CHAR

•	VARCHAR2

The character datatypes in ORACLE7 are different from those in ORACLE Version 6. For a summary of the differences and compatibility issues, see Appendix A "Summary of Changes to SQL in ORACLE7" of this Manual.

CHAR Datatype

The CHAR datatype specifies a fixed length character string. When you create a table with a CHAR column, you can supply the column length in bytes. ORACLE subsequently ensures that all values stored in that column have this length. If you insert a value that is shorter than the column length, ORACLE blank-pads the value to column length. If you try to insert a value that is too long for the column, ORACLE returns an error.

The default length for a CHAR column is 1 byte. The maximum length of CHAR data is 255 bytes. ORACLE compares CHAR values using blank-padded comparison semantics. For information on comparison semantics, see the section "Datatype Comparison Rules" on page 2 - 31.

 VARCHAR2 Datatype

The VARCHAR2 datatype specifies a variable length character string. When you create a VARCHAR2 column, you can supply the maximum number of bytes of data that it can hold. ORACLE subsequently stores each value in the column exactly as you specify it, provided it does not exceed the column's maximum length. If you try to insert a value that exceeds this length, ORACLE returns an error.

You must specify a maximum length for a VARCHAR2 column. The maximum length of VARCHAR2 data is 2000 bytes. ORACLE compares VARCHAR2 values using non-padded comparison semantics. For information on comparison semantics, see the section "Datatype Comparison Rules" on page 2 - 31.

 VARCHAR Datatype

The VARCHAR datatype is currently synonymous with the VARCHAR2 datatype. Oracle Corporation recommends that you use VARCHAR2 rather than VARCHAR. In a future version of ORACLE, VARCHAR might be a separate datatype used for variable length character strings compared with different comparison semantics.

NUMBER Datatype

The NUMBER datatype is used to store zero, positive and negative fixed and floating point numbers with magnitudes between 1.0 x 10-130 and 9.9...9 x 10125 (38 9s followed by 88 0s) with up to 38 digits of precision. If you specify an arithmetic expression whose value has a magnitude greater than or equal to 1.0 x 10126, ORACLE returns an error. You can specify a fixed point number datatype with this syntax:

NUMBER(p,s)

where:

p	is the precision, or the total number of digits. ORACLE guarantees the portability of numbers with precision ranging from 1 to 38.

s	is the scale, or the number of digits to the right of the decimal point. The scale can range from -84 to 127.

You can also use one of these alternate forms:

NUMBER(p)	is a fixed point number with precision p and scale 0.

NUMBER	is a floating point number with precision 38. Note that a scale value is not applicable for floating point numbers.

 Scale and Precision

Specify the scale and precision of a number column for extra integrity checking on input. Specifying scale and precision does not force all values to a fixed length. If a value exceeds the precision, ORACLE returns an error. If a value exceeds the scale, ORACLE rounds it.

These examples show how ORACLE stores data using different precisions and scales.

Actual Data	Specified As	Stored As

7456123.89	NUMBER	7456123.89

7456123.89	NUMBER (9)	7456124

7456123.89	NUMBER (9,2)	7456123.89

7456123.89	NUMBER (9,1)	7456123.9

7456123.8	NUMBER (6)	exceeds protection

7456123.8	NUMBER (15,1)	7456123.8

7456123.89	NUMBER (7,-2)	7456100

7456123.89	NUMBER (-7,2)	exceeds protection

 Negative Scale

If the scale is negative, the actual data is rounded to the specified number of places to the left of the decimal point. For example, a specification of (10,-2) means to round to hundreds.

 Scale Greater than Precision

You can specify a scale that is greater than precision, although it is uncommon. In this case, the precision specifies the maximum number of digits to the right of the decimal point. As with all number datatypes, if the value exceeds the precision, ORACLE returns an error message. If the value exceeds the scale, ORACLE rounds the value. For example, a column defined as NUMBER(4,5) requires a zero for the first digit after the decimal point and rounds all values past the fifth digit after the decimal point. The following examples show the effects of a scale greater than precision:

Actual Data	Specified As	Stored As

.01234	NUMBER(4,5)	.01234

.00012	NUMBER(4,5)	.00012

.000127	NUMBER(4,5)	.00013

.0000012	NUMBER(2,7)	.0000012

.00000123	NUMBER(2,7)	.0000012

 Floating Point Numbers

ORACLE also allows you to specify floating point numbers. A floating point value either can have a decimal point anywhere from the first to the last digit or can omit the decimal point altogether. A scale value is not applicable to floating point numbers because there is no restriction on the number of digits that can appear after the decimal point.

You can specify floating point numbers with the appropriate forms of the NUMBER datatype discussed in the section "NUMBER Datatype" on page 2 - 24. ORACLE also supports the ANSI datatype FLOAT. You can specify this datatype using one of these syntactic forms:

FLOAT	specifies a floating point number with decimal precision 38, or a binary precision of 126.

FLOAT(b)	specifies a floating point number with binary precision b. The precision b can range from 1 to 126.

To convert from binary to decimal precision, multiply b by 0.30103. To convert from decimal to binary precision, multiply the decimal precision by 3.32193. The maximum of 126 digits of binary precision is roughly equivalent to 38 digits of decimal precision.

LONG Datatype

LONG columns store variable length character strings containing up to 2 gigabytes, or 231-1 bytes. LONG columns have many of the characteristics of VARCHAR2 columns. You can use LONG columns to store long text strings. ORACLE uses LONG columns in the data dictionary to store the text of view definitions. The length of LONG values may also be limited by the memory available on your computer.

You can reference LONG columns in SQL statements in these places:

•	SELECT lists

•	SET clauses of UPDATE statements

•	VALUES clauses of INSERT statements

The use of LONG values are subject to some restrictions:

•	A table cannot contain more than one LONG column.

•	LONG columns cannot appear in integrity constraints (except for NULL and NOT NULL constraints).

•	LONG columns cannot be indexed.

•	A procedure or stored function cannot accept a LONG argument.

•	A stored function cannot return a LONG value.

•	Within a single SQL statement, all LONG columns, updated tables, and locked tables must be located on the same database.

Also, LONG columns cannot appear in certain parts of SQL statements:

•	WHERE, GROUP BY, ORDER BY, or CONNECT BY clauses or with the DISTINCT operator in SELECT statements

•	SQL functions (such as SUBSTR or INSTR)

•	expressions or conditions

•	select lists of queries containing GROUP BY clauses

•	select lists of subqueries or queries combined by set operators

•	select lists of CREATE TABLE AS SELECT statements

You can use the ORACLE Call Interfaces to retrieve a portion of a LONG value from the database. See the Programmer's Guide to the ORACLE Call Interfaces.

DATE Datatype

The DATE datatype is used to store date and time information. Although date and time information can be represented in both CHAR and NUMBER datatypes, the DATE datatype has special associated properties.

For each DATE value the following information is stored:

•	century

•	year

•	month

•	day

•	hour

•	minute

•	second

You cannot specify a date literal. To specify a date value, you must convert a character or numeric value to a data value with the TO_DATE function. ORACLE automatically converts character values that are in the default date format into date values when they are used in date expressions. The default date format is specified by the initialization parameter NLS_DATE_FORMAT and is a string such as 'DD-MON-YY'. This example date format includes two-digit number for the day of the month, an abbreviation of the month name, and the last two digits of the year.

If you specify a date value without a time component, the default time is 12:00:00a.m. (midnight). If you specify a date value without a date, the default date is the first day of the current month.

The date function SYSDATE returns the current date and time. For information on the SYSDATE and TO_DATE functions and the default date format, see Chapter 3 "Operators, Functions, Expressions, Conditions" of this Manual.

 Date Arithmetic

You can add and subtract number constants as well as other dates from dates. ORACLE interprets number constants in arithmetic date expressions as numbers of days. For example, SYSDATE + 1 is tomorrow. SYSDATE - 7 is one week ago. SYSDATE + (10/1440) is ten minutes from now. Subtracting the HIREDATE column of the EMP table from SYSDATE returns the number of days since each employee was hired. You cannot multiply or divide DATE values.

ORACLE provides functions for many of the common date operations. For example, the ADD_MONTHS function allows you to add or subtract months from a date. The MONTHS_BETWEEN function returns the number of months between two dates. The fractional portion of the result represents that portion of a 31-day month. For more information on date functions, see the section "Date Functions" on page NO TAG.

Because each date contains a time component, most results of date operations include a fraction. This fraction means a portion of one day. For example, 1.5 days is 36 hours.

 Using Julian Dates

A Julian date is the number of days since Jan 1, 4712 BC. Julian dates allow continuous dating from a common reference. You can use the date format model "J" with date functions TO_DATE and TO_CHAR to convert between ORACLE DATE values and their Julian equivalents.

Example	This statement returns the Julian equivalent of January 1, 1992:

SELECT TO_CHAR(TO_DATE('01-01-1992', 'MM-DD-YYYY'),'J')

    FROM DUAL

TO_CHAR(TO_DATE('01-01-1992','MM-DD-YYYY),'J')

----------------------------------------------

2448623

RAW and LONG RAW Datatypes

The RAW and LONG RAW datatypes are used for byte-oriented data (for example, binary data or byte strings) to store character strings, floating point data, and binary data such as graphics images and digitized sound. ORACLE returns RAW values as hexadecimal character values. RAW data can only be stored and retrieved. You cannot perform string manipulation on RAW data.

RAW is equivalent to VARCHAR2 and LONG RAW to LONG except that there is no conversion between database and session character set. While CHAR, VARCHAR2, and LONG data is automatically converted between the database character set and the user-side character set for the session, there is no such conversion for RAW and LONG RAW data. LONG RAW data is subject to the same restrictions as LONG data.

ROWID Datatype

Each row in the database has an address. You can examine a row's address by querying the pseudocolumn ROWID. Values of this pseudocolumn are hexadecimal strings representing the address of each row. These string have the datatype ROWID. For more information on the ROWID pseudocolumn, see the section "Pseudocolumns" on page 2 - 37. You can also create tables and clusters that contain actual columns having the ROWID datatype. ORACLE does not guarantee that the values of such columns are valid ROWIDs.

Character values representing ROWIDs:

block.row.file

where:

block	is a hexadecimal string identifying the data block of the data file containing the row. The length of this string may vary depending on your operating system.

row	is a four-digit hexadecimal string identifying the row in the data block. The first row in the block has the number 0.

file	is a hexadecimal string identifying the database file containing the row. The first data file has the number 1. The length of this string may vary depending on your operating system.

Example	Consider this ROWID value:

0000000F.0000.0002

The row corresponding to this ROWID is the first row (0000) in the fifteenth data block (0000000F) of the second data file (0002).

MLSLABEL Datatype

The MLSLABEL datatype is used to store the binary format a label used on a secure operating system. Labels are used by Trusted ORACLE to mediate access to information. You can also define columns with this datatype if you are the standard ORACLE Server. For more information on Trusted ORACLE, including this datatype and labels, see the Trusted ORACLE7 Server Administrator's Guide

ANSI, DB2, and SQL/DS Datatypes

SQL commands that create tables and clusters also accept both ANSI datatypes and datatypes from IBM's products SQL/DS and DB2. ORACLE creates columns with ORACLE datatypes based on the conversions defined in Table 2 - 2 and Table 2 - 3.

ANSI SQL Datatype	ORACLE Datatype

CHARACTER(n), CHAR(n)	CHAR(n)

CHARACTER VARYING(n), 	VARCHAR(n)

CHAR VARYING(n)

NUMERIC(p,s), DEC	NUMBER(p,s)

IMAL(p,s), DEC(p,s)

INTEGER, INT, SMALLINT	NUMBER(38)

FLOAT(b) 2, DOUBLE PRECI	NUMBER

SION 3, REAL 4

Table 2 - 2.  ANSI Datatypes Converted to ORACLE Datatypes

SQL/DS or DB2 Datatype	ORACLE Datatype

CHARACTER(n)	CHAR(n)

VARCHAR(n)	VARCHAR(n)

LONG VARCHAR(n)	LONG

DECIMAL(p,s) 1	NUMBER(p,s)

INTEGER, SMALLINT	NUMBER(38)

FLOAT(b) 2	NUMBER

Table 2 - 3.  SQL/DS and DB2 Datatypes Converted to

ORACLE Datatypes

1 The NUMERIC, DECIMAL, and DEC datatypes can specify only fixed point numbers. For these datatypes, s defaults to 0.

2 The FLOAT datatype is a floating point number with a binary precision b. This default precision for this datatype is 126 binary, or 38 decimal.

3 The DOUBLE PRECISION datatype is a floating point number with binary precision 126.

4 The REAL datatype is a floating point number with a binary precision of 63, or 18 decimal.

Do not define columns with these SQL/DS and DB2 datatypes because they have no corresponding ORACLE datatype:

•	GRAPHIC

•	LONG VARGRAPHIC

•	VARGRAPHIC

•	TIME

•	TIMESTAMP

Note that data of type TIME and TIMESTAMP can also be expressed as ORACLE DATE data.

Datatype Comparison Rules

This section describes how ORACLE compares values of each datatype.

 Number Values

A larger value is considered greater than a smaller one. All negative numbers are less than all positive numbers. Thus, -1 is less than 100; -100 is less than -1.

 Date Values

A later date is considered greater than an earlier one. For example, the date equivalent of '29-MAR-1991' is less than that of '05-JAN-1992' and '05-JAN-1992 1:35pm' is greater than '05-JAN-1992 10:09am'.

 Character String Values

Character values are compared using one of these comparison rules:

•	blank-padded comparison semantics

•	non-padded comparison semantics

The following sections explain these comparison semantics. The results of comparing two character values using different comparison semantics may be different. Table 2 - 4 shows the results of comparing five pairs of character values using each comparison semantic. The last comparison in the table illustrates the differences between the blank-padded and non-padded comparison semantics.

Blank-Padded Comparison Semantics     If the two values have different lengths, ORACLE first adds blanks to the end of the shorter one so their lengths are equal. ORACLE then compares the values character by character up to the first character that differs. The value with the greater character in the first differing position is considered greater. If two values have no differing characters, then they are considered equal. This rule means that two values are equal if they differ only in the number of trailing blanks. ORACLE uses blank-padded comparison semantics only when both values in the comparison are either expressions of datatype CHAR, text literals, or values returned by the USER function.

Non-Padded Comparison Semantics     ORACLE compares two values character by character up to the first character that differs. The value with the greater character in that position is considered greater. If two values of different length are identical up to the end of the shorter one, the longer value is considered greater. If two values of equal length have no differing characters, then the values are considered equal. ORACLE uses non-padded comparison semantics whenever one or both values in the comparison have the datatype VARCHAR2.

Blank-Padded	Non-Padded

'ab' > 'aa'	'ab' > 'aa'

'ab' > 'a '	'ab' > 'a '

'ab' > 'a'	'ab' > 'a'

'ab' = 'ab'	'ab' = 'ab'

'a ' = 'a'	'a ' = 'a'

Table 2 - 4.  Results of Comparisons with

Blank-Padded and Non-Padded Comparison

Semantics

 Single Characters

ORACLE compares single characters according to their numeric values in the database character set. One character is greater than another if it has a greater numeric value than the other in the character set.

These are some common character sets:

•	7-bit ASCII (American Standard Code for Information Interchange)

•	EBCDIC (Extended Binary Coded Decimal Interchange Code) Code Page 500

•	ISO 8859/1 (International Standards Organization)

•	JEUC Japan Extended UNIX

•	SJIS Japan Shift JIS

Portions of the ASCII and EBCDIC character sets appear in Table 2 - 5 and Table 2 - 6. Note that uppercase and lowercase letters are not equivelant. Also, note that the numeric values for the characters of a character set may not match the linguistic sequence for a particular language.

ASCII Character Set

Table 2 - 5 lists the 7-bit ASCII character set.

Decimal value	Symbol	Decimal value	Symbol

32	blank	59	;

33	!	60	<

34	"	61	=

35	#	62	>

36	$	63	?

37	%	64	@

38	&	65-90	A-Z

39	'	91	[

40	(	92	\

41	)	93	]

42	*	94	^^

43	+	95	_

44	,	96	`

45	-	97-122	a-z

46	.	123	{

47	/	124	|

48-57	0-9	125	}

58	:	126	~

Table 2 - 5.  ASCII Character Set

EBCDIC Character Set

Table 2 - 6 lists a common portion of the EBCDIC character set.

Decimal value	Symbol	Decimal value	Symbol

64	blank	108	%

74	¢ 	109	_

75	.	110	>

76	<	111	?

77	(	122	:

78	+	123	#

79	|	124	@

80	&	125	'

90	!	126	=

91	$	127	"

92	*	129-137	a-i

93	)	145-153	j-r

94	;	162-169	s-z

95	`	193-201	A-I

96	-	209-217	J-R

97	/	226-233	S-Z

Table 2 - 6.  EBCDIC  Character Set

Data Conversion

Generally an expression cannot contain values of different datatypes. For example, an expression cannot multiply 5 by 10 and then add 'JAMES'. However, ORACLE supports both implicit and explicit conversion of values from one datatype to another.

 Implicit Data Conversion

ORACLE automatically converts a value from one datatype to another when such a conversion makes sense. ORACLE performs datatype conversions in these cases:

•	When an INSERT or UPDATE statement assigns a value of one datatype to a column of another, ORACLE converts the value to the datatype of the column.

•	When you use a SQL function or operator with an argument with a datatype other than the one it accepts, ORACLE converts the argument to the accepted datatype.

•	When you use a comparison operator on values of different datatypes, ORACLE converts one of the expressions to the datatype of the other.

Table 2 - 7 shows the implicit datatype conversions ORACLE performs.

Note: Note that this table does not show conversions from LONG and LONG RAW values because it is impossible to specify LONG and LONG RAW values in cases in which ORACLE can perform implicit datatype conversion. For example, LONG and LONG RAW values cannot appear in expressions with functions or operators. For information on the limitations on LONG and LONG RAW datatypes, see the section "LONG Datatype" on page 2 - 26.

Example I	The text literal '10' has datatype CHAR. ORACLE implicitly converts it to the NUMBER datatype if it appears in a numeric expression as in this statement:

SELECT sal + '10'

    FROM emp

Example II	When a condition compares a character value and a NUMBER value, ORACLE implicitly converts the character value to a NUMBER value, rather than converting the NUMBER value to a character value. In this statement, ORACLE implicitly converts '7936' to 7936:

SELECT ename

    FROM emp

WHERE empno = '7936'

Example III	In this statement, ORACLE implicitly converts '12-MAR-1993' to a DATE value using the default date format 'DD-MON-YYYY':

SELECT ename

    FROM emp

WHERE hiredate = '12-MAR-1993'

Example IV	In this statement, ORACLE implicitly converts the text literal '00002514.0001.0001' to a ROWID value:

SELECT ename

    FROM emp

WHERE ROWID = '00002514.0001.0001'

 Explicit Data Conversion

You can also explicitly specify datatype conversions using SQL conversion functions. Table 2 - 7 shows SQL functions that explicitly convert a value from one datatype to another.

          TO

FROM

          TO	CHAR	NUMBER	DATE	RAW	ROWID

FROM

CHAR

      unecessary	  TO_NUMBER	     TO_DATE	   HEXTORAW	 CHARTOROWID

NUMBER

    TO_CHAR	     unecessary	    TO_DATE

  (number, 'J')

DATE

     TO_CHAR	    TO_CHAR	    unecessary

    (date, 'J')

RAW

    RAWTOHEX	    unecessary

ROWID

 ROWIDTOCHAR	      unecessary

Table 2 - 7.  SQL Functions for Datatype Conversion

For information on these functions, see the section "Conversion Functions" on page NO TAG.

 Implicit vs. Explicit Data Conversion

Oracle Corporation recommends that you specify explicit conversions rather than rely on implicit or automatic conversions for these reasons:

•	SQL statements are easier to understand when you use explicit datatype conversions functions.

•	Automatic datatype conversion can have a negative impact on performance, especially if the datatype of a column value is converted to that of a constant rather than the other way around.

•	Implicit conversion depends on the context in which it occurs and may not work the same way in every case.

•	Algorithms for implicit conversion are subject to change across software releases and among ORACLE products. Behavior of explicit conversions is more predictable.

________________________________________

Nulls

If a row lacks a value for a particular column, that column is said to be null, or to contain a null. Nulls can appear in columns of any datatype that are not restricted by NOT NULL or PRIMARY KEY integrity constraints. Use a null when the actual value is unknown or when a value would not be meaningful.

ORACLE currently treats a character value with a length of zero as null. However, this may not continue to be true in future versions of ORACLE.

Do not use null to represent a value of zero, because they are not equivalent. Any arithmetic expression containing a null always evaluates to null. For example, null added to 10 is null. In fact, all operators (except concatenation) return null when given a null operand.

Nulls in SQL Functions

All scalar functions (except NVL and TRANSLATE) return null when given a null argument. The NVL function can be used to return a value when a null occurs. For example, the expression NVL(COMM,0) returns 0 if COMM is null or the value of COMM if it is not null.

Most group functions ignore nulls. For example, consider a query that averages the five values 1000, null, null, null, and 2000. Such a query ignores the nulls and calculates the average to be (1000+2000)/2 = 1500.

Nulls with Comparison Operators

To test for nulls, only use the comparison operators IS NULL and IS NOT NULL. If you use any other operator with nulls and the result depends on the value of the null, the result is unknown. Because null represents a lack of data, a null cannot be equal or unequal to any value or to another null. However, note that ORACLE considers two nulls to be equal when evaluating a DECODE expression. For information on the DECODE syntax, see the section "Expr" on page NO TAG.

Nulls in Conditions

ORACLE treats conditions evaluating to unknown values as FALSE. For example, since the condition COMM = NULL is always unknown, a SELECT statement with this condition in its WHERE clause returns no rows. Note that ORACLE returns no error message in this case.

Table 2 - 8 on page 2 - 36 summarizes results of conditions using nulls.

If A is:	Condition	Evaluates to:

10	a IS NULL	FALSE

10	a IS NOT NULL	TRUE

NULL	a IS NULL	TRUE

NULL	a IS NOT NULL	FALSE

10	a = NULL	Unknown

10	a != NULL	Unknown

NULL	a = NULL	Unknown

NULL	a != NULL	Unknown

Table 2 - 8.  Conditions Containing Nulls

For the truth tables showing the results of logical expressions containing nulls, see Tables Table 3 - 6, Table 3 - 7, and Table 3 - 8 on page 3 - 10.

________________________________________

Pseudocolumns

A pseudocolumn behaves like a table column, but is not actually stored in the table. You can select from pseudocolumns, but you cannot insert, update, or delete their values. This section describes these pseudocolumns:

•	CURRVAL

•	NEXTVAL

•	LEVEL

•	ROWID

•	ROWNUM

CURRVAL and NEXTVAL

A sequence is a schema object that can generate unique sequential values. These values are often used for primary and unique keys. 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:

sequence.CURRVAL

sequence.NEXTVAL

To refer to the current or next value of a sequence in the schema of another user, you must have been granted either SELECT object privilege on the sequence or SELECT ANY SEQUENCE system privilege and you must qualify the sequence with the schema containing it:

schema.sequence.CURRVAL

schema.sequence.NEXTVAL

To refer to the value of a sequence on a remote database, you must qualify the sequence with a complete or partial name of a database link:

schema.sequence.CURRVAL@dblink

schema.sequence.NEXTVAL@dblink

For more information on referring to database links, see the section "Referring to Objects in Remote Databases" on page 2 - 13.

If you are using Trusted ORACLE in DBMS MAC mode, you can only refer to a sequence if your DBMS label dominates the sequence's creation label or if one of these criteria is satisfied:

•	If the sequence's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the sequence's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the sequence's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

If you are using Trusted ORACLE in OS MAC mode, you cannot refer to a sequence with a lower creation label than your DBMS label.

 Using Sequence Values

You can use CURRVAL and NEXTVAL in these places:

•	the SELECT list of a SELECT statement

•	the VALUES clause of an INSERT statement

•	the SET clause of an UPDATE statement

You cannot use CURRVAL and NEXTVAL in these places:

•	a subquery

•	a view's query or snapshot's query

•	a SELECT statement with the DISTINCT operator

•	a SELECT statement with a GROUP BY or ORDER BY clause

•	a SELECT statement that is combined with another SELECT statement with the UNION, INTERSECT, or MINUS set operator

•	the WHERE clause of a SELECT statement

•	DEFAULT value of a column in a CREATE TABLE or ALTER TABLE statement

•	the condition of a CHECK constraint

Also, within a single SQL statement, all referenced LONG columns, updated tables, and locked tables must be located on the same database.

When you create a sequence, you can define its initial value and the increment between its values. The first reference to NEXTVAL returns the sequence's initial value. Subsequent references to NEXTVAL increment the sequence value by the defined increment and return the new value. Any reference to CURRVAL always returns the sequence's current value, which is the value returned by the last reference to NEXTVAL. Note that before you use CURRVAL for a sequence in your session, you must first increment the sequence with NEXTVAL.

You can only increment a sequence once in a single SQL statement. If a statement contains more than one reference to NEXTVAL for a sequence, ORACLE increments the sequence once and returns the same value for all occurrences of NEXTVAL. If a statement contains references to both CURRVAL and NEXTVAL, ORACLE increments the sequence and returns the same value for both CURRVAL and NEXTVAL regardless of their order within the statement.

A sequence can be accessed by many users concurrently with no waiting or locking. For information on sequences, see the CREATE SEQUENCE command in Chapter 4 "Commands" of this Manual.

Example I	This example selects the current value of the employee sequence:

SELECT empseq.currval

    FROM DUAL

Example II	This example increments the employee sequence and uses its value for a new employee inserted into the employee table:

INSERT INTO emp

    VALUES (empseq.nextval, 'LEWIS', 'CLERK',

            7902, SYSDATE, 1200, NULL, 20)

Example III	This example adds a new order with the next order number to the master order table and then adds suborders with this number to the detail order table:

INSERT INTO master_order(orderno, customer, orderdate)

    VALUES (orderseq.nextval, 'Al''s Auto Shop', SYSDATE)

INSERT INTO detail_order (orderno, part, quantity)

    VALUES (orderseq.currval, 'SPARKPLUG', 4)

INSERT INTO detail_order (orderno, part, quantity)

    VALUES (orderseq.currval, 'FUEL PUMP', 1)

INSERT INTO detail_order (orderno, part, quantity)

    VALUES (orderseq.currval, 'TAILPIPE', 2)

LEVEL

For each row returned by a hierarchical query, the LEVEL pseudocolumn returns 1 for a root node, 2 for a child of a root, and so on. A root node is the highest node within an inverted tree. A child node is any non-root node. A parent node is any row that has children. A leaf node is any row without children. Figure 2 - 3 shows the nodes of an inverted tree with their LEVEL values.

To define a hierarchical relationship in a query, you must use the START WITH and CONNECT BY clauses. For more information on using the LEVEL pseudocolumn, see the SELECT command in Chapter 4 "Commands" of this Manual.

ROWID

For each row in the database, the ROWID pseudocolumn returns a row's address. ROWID values contain information necessary to locate a row:

•	which data block in the data file

•	which row in the data block (first row is 0)

•	which data file (first file is 1)

Usually, a ROWID value uniquely identifies a row in the database. However, rows in different tables that are stored together in the same cluster can have the same ROWID.

Values of the ROWID pseudocolumn have the datatype ROWID. For information on the ROWID datatype, see the section "ROWID Datatype" on page 2 - 28.

ROWID values have several important uses:

•	They are the fastest means of accessing a single row.

•	They can show you how a table's rows are stored.

•	They are unique identifiers for rows in a table.

A ROWID does not change during the lifetime of its row. However, you should not use ROWID as a table's primary key. If you delete and reinsert a row with the Import and Export utilities, for example, its ROWID may change. If you delete a row, ORACLE may reassign its ROWID to a new row inserted later.

Although you can use the ROWID pseudocolumn in the SELECT and WHERE clauses of a query, these pseudocolumn values are not actually stored in the database. You cannot insert, update, or delete a value of the ROWID pseudocolumn.

Example	This statement selects the address of all rows that contain data for employees in department 20:

SELECT ROWID, ename

    FROM emp

    WHERE deptno = 20

ROWID              ENAME

------------------ ----------

0000000F.0000.0002 SMITH

0000000F.0003.0002 JONES

0000000F.0007.0002 SCOTT

0000000F.000A.0002 ADAMS

0000000F.000C.0002 FORD

ROWNUM

For each row returned by a query, the ROWNUM pseudocolumn returns a number indicating the order in which ORACLE selects the row from a table or set of joined rows. The first row selected has a ROWNUM of 1, the second has 2, and so on.

You can use ROWNUM to limit the number of rows returned by a query, as in this example:

SELECT *

    FROM emp

    WHERE ROWNUM < 10

You can also use ROWNUM to assign unique values to each row of a table, as in this example:

UPDATE tabx

    SET col1 = ROWNUM

ORACLE assigns a ROWNUM value to each row as it is retrieved, before rows are sorted for an ORDER BY clause, so an ORDER BY clause normally does not affect the ROWNUM of each row. However, if an ORDER BY clause causes ORACLE to use an index to access the data, ORACLE may retrieve the rows in a different order than without the index, so the ROWNUMs may be different than without the ORDER BY clause.

Note that conditions testing for ROWNUM values greater than a positive integer are always false. For example, this query returns no rows:

SELECT * FROM emp

    WHERE ROWNUM > 1

The first row fetched is assigned a ROWNUM of 1 and makes the condition false. The second row to be fetched is now the first row and is also assigned a ROWNUM of 1 and makes the condition false. All rows subsequently fail to satisfy the condition, so no rows are returned.

________________________________________

Comments

You can associate comments with SQL statements and schema objects.

Comments Within SQL Statements

Comments within SQL statements do not affect the statement execution, but they may make your application easier for you to read and maintain. You may want to include a comment in a statement that describes the statement's purpose within your application.

A comment can appear between any keywords, parameters or punctuation marks in a statement. You can include a comment in a statement using either of these means:

•	Begin the comment with /*. Proceed with the text of the comment. This text can span multiple lines. End the comment with */. The opening and terminating characters need not be separated from the text by a space or a line break.

•	Begin the comment with -- (two hyphens). Proceed with the text of the comment. This text cannot extend to a new line. End the comment with a line break.

A SQL statement can contain multiple comments of both styles. The text of a comment can contain any printable characters in your database character set.

You can use comments in a SQL statement to pass instructions, or hints, to the ORACLE optimizer. The optimizer uses these hints to choose an execution plan for the statement. For more information on hints, see Chapter 5 "Tuning SQL Statements" of the ORACLE7 Server Application Developer's Guide.

Note that you cannot use these styles of comments between SQL statements in a SQL script. You can use the SQL*DBA or SQL*Plus REMARK command for this purpose. For information on these commands, see the ORACLE7 Server Utilities Guide or the SQL*Plus User's Guide and Reference Manual.

Example	These statements contain many comments:

SELECT ename, sal + NVL(comm, 0), job, loc

/* Select all employees whose compensation is

greater than that of Jones.*/

FROM emp, dept

 /*The DEPT table is used to get the department name.*/

WHERE emp.deptno = dept.deptno

  AND sal + NVL(comm,0) >	 /* Subquery:	   */

   (SELECT sal + NLV(comm,0)

   /* total compensation is sal + comm */

FROM emp

WHERE ename = 'JONES')

SELECT ename,	-- select the name

sal + NVL(comm, 0)	-- total compensation

job	-- job

loc	-- and city containing the office

FROM emp,	-- of all employees

     dept

WHERE emp.deptno = dept.deptno

  AND sal + NVL(comm, 0) >	-- whose compensation

-- is greater than

    (SELECT sal + NVL(comm,0)	-- the compensation

FROM emp

WHERE ename = 'JONES') 	-- of Jones.

Comments on Schema Objects

You can associate a comment with a table, view, snapshot, or column using the COMMENT command described in Chapter 4 "Commands" of this Manual. Comments associated with schema objects are stored in the data dictionary.


CHAPTER 3. OPERATORS, FUNCTIONS, EXPRESSIONS, CONDITIONS

This chapter describes methods of manipulating individual data items. For example, standard arithmetic operators such as addition and subtraction are discussed as well as less common functions such as absolute value or string length. Topics include:

•	operators

•	functions

•	format models

•	expressions

•	conditions

________________________________________

Operators

An operator is used to manipulate individual data items and return a result. These items are called operands or arguments. Operators are represented by special characters or by keywords. For example, the multiplication operator is represented by an asterisk (*) and the operator that tests for nulls is represented by the keywords IS NULL. The tables in the following sections of this chapter list SQL operators.

Unary and Binary Operators

There are two general classes of operators:

unary	A unary operator operates on only one operand. A unary operator typically appears with its operand in this format:

operator operand

binary	A binary operator operates on two operands. A binary operator appears with its operands in this format:

operand1 operator operand2

Other operators with special formats accept more than two operands. If an operator is given a null operator, the result is always null. The only operator that does not follow this rule is concatenation (||).

Precedence

An important property of an operator is its precedence. Precedence is the order in which ORACLE evaluates different operators in the same expression. When evaluating an expression containing multiple operators, ORACLE evaluates operators with higher precedence before evaluating those with lower precedence. ORACLE evaluates operators with equal precedence from left to right within an expression.

Table 3 - 1 lists the levels of precedence among SQL operators from high to low. Operators listed on the same line have the same precedence.

Highest Precedence

Unary +- arithmetic operators     	PRIOR Operator

*/ arithmetic operators

Binary =- arithmetic operators   	|| character operators

All comparison operators

NOT logical operator

AND logical operator

OR logical operator

Lowest Precedence

Table 3 - 1.  SQL  Operator Precedence

You can use parentheses in an expression to override operator precedence. ORACLE evaluates expressions inside parentheses before evaluating those outside.

SQL also supports set operators (UNION, UNION ALL, INTERSECT, and MINUS) which combine sets of rows returned by queries, rather than individual data items. All set operators have equal precedence.

Example	Consider this expression:

1+2*3

Because multiplication has a higher precedence than addition, ORACLE first multiplies 2 by 3 and then adds the result to 1.

Arithmetic Operators

You can use an arithmetic operator in an expression to negate, add, subtract, multiply, and divide numeric values. The result of the operation is also a numeric value. Some of these operators are also used in date arithmetic. Table 3 - 2 lists arithmetic operators.

Operator	Purpose	Example

+ -	Denotes a positive or 	SELECT *

negative espression. These 	FROM orders

are unary operators.	WHERE qtysold = -1

SELECT *

FROM emp

WHERE -sal <0

* /	Multiplies, divides. These 	UPDATE emp

are binary operators.	SET sal = sal * 1.1

+ -	Adds, subtracts. These are 	SELECT sal + comm FROM emp

binary operators.	WHERE sysdate - hiredate

> 365

Table 3 - 2.  Arithmetic Operators

Do not use consecutive minus signs with no separation (--) in arithmetic expressions to indicate double negation or the subtraction of a negative value. The characters -- are used to begin comments within SQL statements. You should separate consecutive minus signs with a space or a parenthesis. For more information on comments within SQL statements, see the section "Comments" on page 2 - 42.

Character Operators

Character operators are used in expressions to manipulate character strings. Table 3 - 3 lists the single character operator.

||	Concatenates character 	SELECT 'Name is ' || ename

strings.	FROM emp

Table 3 - 3.  Character Operators

The result of concatenating two character strings is another character string. If both character strings are of datatype CHAR, the result has datatype CHAR and is limited to 255 characters. If either string is of datatype VARCHAR2, the result has datatype VARCHAR2 and is limited to 2000 characters. Trailing blanks in character strings are preserved by concatenation, regardless of the strings' datatypes. For more information on the differences between the CHAR and VARCHAR2 datatypes, see the section "Character Datatypes" on page 2 - 23.

On most platforms, the concatenation operator is two solid vertical bars, as shown in Table 3 - 3. However, some IBM platforms use broken vertical bars for this operator. Also, you can concatenate character strings with the CONCAT character function.

Although ORACLE treats zero-length character strings as nulls, concatenating a zero-length character string with another operand always results in the other operand, rather than a null. However, this may not continue to be true in future versions of ORACLE. To concatenate an expression that might be null, use the NVL function to explicitly convert the expression to a zero-length string.

Example	This example creates a table with both CHAR and VARCHAR2 columns, inserts values both with and without trailing blanks, and then selects these values, concatenating them. Note that for both CHAR and VARCHAR2 columns, the trailing blanks are preserved.

CREATE TABLE tab1 (col1 VARCHAR2(6), col2 CHAR(6),        	      	 col3 VARCHAR2(6), col4 CHAR(6) )

INSERT INTO tab1(col1,  col2,     col3,     col4)          	     VALUES ('abc', 'def   ', 'ghi   ', 'jkl')

SELECT col1||col2||col3||col4 "Concatenation" 	FROM tab1

Concatenation

------------------

abcdef   ghi   jkl

Comparison Operators

Comparison operators are used in conditions that compare one expression to another. The result of comparing one expression to another can be TRUE, FALSE, or unknown. For information on conditions, see the section "Condition" on page NO TAG. Table 3 - 4 lists comparison operators.

Operator	Purpose	Example

=	Equality test.	SELECT *

FROM emp

WHERE sal = 1500

!=, ^=, `+, <>	Inequality test. All 	SELECT *

forms of the inequality 	FROM emp

operator may not be 	WHERE sal != 1500

available on all

platforms.

>	"Greater than" and 	SELECT *

"less than" tests.	FROM emp

WHERE sal > 1500

<	SELECT *

FROM emp

WHERE sal > 1500

>=	"Greater than or equal 	SELECT *

<=	to" and "less than or 	FROM emp

equal to" tests.	WHERE sal >= 1500

SELECT *

FROM emp

WHERE sal >= 1500

NOT IN	Equivalent to "!=ALL". 	SELECT *

Evaluates to FALSE if 	FROM emp

any menber of the set is 	WHERE sal NOT IN

NULL.	(SELECT sal

FROM emp

WHERE deptno = 30)

SELECT *

FROM emp

WHERE job NOT IN

('CLERK', ANALYST')

ANY, SOME	Compares a value to 	SELECT *

each value in a list or 	FROM emp

returned by a query. 	WHERE sal = ANY

Must be preceded by =, 	(SELECT sal FROM emp

!=, >, <, <=, >=. 	WHERE deptno = 30)

Evaluates to FALSE if

the query returns no

rows.

ALL	Compares a value to 	SELECT *

every value in a list or 	FROM emp

returned by a query. 	WHERE sal >=

Must be preceded by =, 	ALL ( 1400, 3000)

!=, >, <, <=, >=.

Evaluates to TRUE if

the query returns no

rows.

[NOT] BETWEEN 	[Not] greater than or 	SELECT *

x AND y	equal to x and less than 	FROM emp

or equal to y.	WHERE sal

BETWEEN 2000

    AND 3000)

EXISTS	TRUE if a subquery 	SELECT dname, deptno

returns at least one row.	FROM dept

WHERE EXISTS

(SELECT *

FROM emp

WHERE dept.deptno =

emp.deptno)

x [NOT] LIKE 	TRUE if x does [not] 	See the section "LIKE

y 	match the pattern y. 	Operator" beginning on

[ESCAPE z]	Within y, the character 	page XXX [ADD X-REF.]

"%" matches any string

of zero or more charac

ters except null. The

character "_" matches

any single character.

IS [NOT] NULL	Tests for nulls. This is 	SELECT dname, deptno

the only operator that 	FROM emp

should be used to test 	WHERE comm IS NULL

for nulls. See the sec

tion "Nulls" on page

[INSERT X-REF].

Table 3 - 4.  Comparison Operators

 NOT IN Operator

All rows evaluate to false (and no rows are returned) if any item in the list following a NOT IN operation is null. For example, this statement returns 'TRUE':

SELECT 'TRUE'

FROM emp

WHERE deptno NOT IN (5,15)

However, this statement returns no rows:

SELECT 'TRUE'

FROM emp

WHERE deptno NOT IN (5,15,null)

This example returns no rows because the WHERE clause condition evaluates to:

deptno != 5 AND deptno != 15 AND deptno != null

Because all conditions that compare a null result in null, the entire expression results in a null. This behavior can easily be overlooked, especially when the NOT IN operator references a subquery.

LIKE Operator

The LIKE operator is used in character string comparisons with pattern matching. The syntax for a condition using the LIKE operator is shown in this diagram:

where:

char1	is a value to be compared with a pattern. This value can have datatype CHAR or VARCHAR2.

NOT	logically inverts the result of the condition, returning FALSE if the condition evaluates to TRUE and TRUE if it evaluates to FALSE.

char2	is the pattern to which char1 is compared. The pattern is a value of datatype CHAR or VARCHAR2 and can contain the special pattern matching characters % and _.

ESCAPE	identifies a single character as the escape character. The escape character can be used to cause ORACLE to interpret % or _ literally, rather than as a special character, in the pattern.

While the equal (=) operator exactly matches one character value to another, the LIKE operator matches a portion of one character value to another by searching the first value for the pattern specified by the second.

With the LIKE operator, you can compare a value to a pattern rather than to a constant. The pattern can only appear after the LIKE keyword. For example, you can issue the following query to find the salaries of all employees with names beginning with 'SM':

SELECT sal

FROM emp

WHERE ename LIKE 'SM%'

The following query uses the = operator, rather than the LIKE operator, to find the salaries of all employees with the name 'SM%':

SELECT sal

FROM emp

WHERE ename = 'SM%'

The following query finds the salaries of all employees with the name 'SM%'. ORACLE interprets 'SM%' as a text literal, rather than as a pattern, because it precedes the LIKE operator:

SELECT sal

FROM emp

WHERE 'SM%' LIKE ename

Patterns usually use special characters that ORACLE matches with different characters in the value:

•	An underscore (_) in the pattern matches exactly one character (as opposed to one byte in a multi-byte character set) in the value.

•	A percent sign (%) in the pattern can match zero or more characters (as opposed to bytes in a multi-byte character set) in the value.  Note that the pattern '%' cannot match a null.

Case Sensitivity and Pattern Matching      Case is significant in all conditions comparing character expressions including the LIKE and equality (=) operators. You can use the UPPER() function to perform a case insensitive match, as in this condition:

UPPER(ename) LIKE 'SM%'

Example I	This condition is true for all ENAME values beginning with "MA":

ename LIKE 'MA%'

All of these ENAME values make the condition TRUE:

MARTIN, MA, MARK, MARY

Since case is significant, ENAME values beginning with  "Ma", "ma", and "mA" make the condition FALSE.

Example II	Consider this condition:

ename LIKE 'SMITH_'

This condition is true for these ENAME values:

SMITHE, SMITHY, SMITHS

This condition is false for 'SMITH', since the special character "_" must match exactly one character of the ENAME value.

ESCAPE Option      You can include the actual characters "%" or "_" in the pattern by using the ESCAPE option. The ESCAPE option identifies the escape character. If the escape character appears in the pattern before the character "%" or "_", ORACLE interprets this character literally in the pattern, rather than as a special pattern matching character.

Example III	To search for any employees with the pattern 'A_B' in their name:

SELECT ename

FROM emp

WHERE ename LIKE '%A\_B%' ESCAPE '\'

The ESCAPE option identifies the backslash (\) as the escape character. In the pattern, the escape character precedes the underscore (_). This causes ORACLE to interpret the underscore literally, rather than as a special pattern matching character.

Patterns Without %      If a pattern does not contain the "%" character, the condition can only be TRUE if both operands have the same length.

Example IV	Consider the definition of this table and the values inserted into it:

CREATE TABLE freds (f CHAR(6), v VARCHAR2(6))

INSERT INTO freds VALUES ('FRED', 'FRED')

Because ORACLE blank-pads CHAR values, the value of F is blank-padded to 6 bytes. V is not blank-padded and has length 4. Table 3 - 5 shows conditions that evaluate to TRUE and FALSE.

Pattern Matching on Indexed Columns      When LIKE is used to search an indexed column for a pattern, ORACLE can use the index to improve the statement's performance if the leading character in the pattern is not "%" or "_". In this case, ORACLE can scan the index by this leading character. If the first character in the pattern is "%"  or "_", the index cannot improve the query's performance because ORACLE cannot scan the index.

Logical Operators

A logical operator is used to combine the results of two component conditions to produce a single result based on them or to invert the result of a single condition.  Table 3 - 5 lists logical operators.

Operator	Function	Example

NOT	Returns TRUE if the 	SELECT *

following condition is 	FROM emp

FALSE; otherwise 	WHERE NOT (job IS NULL)

returns FALSE.

SELECT *

FROM emp

WHERE NOT

(sal BETWEEN 1000 AND 2000)

AND	Returns TRUE if both 	SELECT *

component conditions 	FROM emp

are TRUE; otherwise 	WHERE job = 'CLERK'

returns FALSE.	AND deptno = 10

OR	Returns TRUE if ei	SELECT *

ther component 	FROM emp

conditions are either 	WHERE job = 'CLERK'

TRUE or 	OR deptno = 10

unknown; otherwise

returns FALSE.

Table 3 - 5.  Logical Operators

For example, in the WHERE clause of the following SELECT statement, the AND logical operator is used to ensure that only those hired before 1984 and also earning more than $1000 a month are returned:

SELECT *

FROM emp

WHERE hiredate < TO_DATE('01-JAN-1984', 'DD-MON-YYYY')

  AND sal > 1000

 NOT Operator

Table 3 - 6 shows the result of applying the NOT operator to an expression.

NOT	TRUE	FALSE	NULL

FALSE	TRUE	NULL

Table 3 - 6.  NOT Truth Table

 AND Operator

Table 3 - 7 shows the results of combining two expressions with AND.

AND	TRUE	FALSE	NULL

TRUE	TRUE	FALSE	NULL

FALSE	FALSE	FALSE	FALSE

NULL	NULL	FALSE	NULL

Table 3 - 7.  AND Truth Table

 OR Operator

Table 3 - 8 shows the results of combining two expressions with OR.

OR	TRUE	FALSE	NULL

TRUE	TRUE	TRUE	TRUE

FALSE	TRUE	FALSE	FALSE

NULL	TRUE	TRUE	NULL

Table 3 - 8.  OR Truth Table

Set operators combines the results of two component queries into a single result. Queries containing set operators are called compound queries.  lists SQL set operators.

Set operators combines the results of two component queries into a single result. Queries containing set operators are called compound queries. Table 3 - 9 lists SQL set operators.

Operator	Returns

UNION	All rows selected by either query.

UNION ALL	All rows selected by either query,

including all duplicates.

INTERSECT	All distinct rows selected by both

queries.

MINUS	All distinct rows selected by the

first query but not the second.

Table 3 - 9.  Set Operators

 All set operators have equal precedence. If a SQL statement contains multiple set operators, ORACLE evaluates them from the left to right if no parentheses explicitly specify another order. To comply with emerging SQL standards, a future version of ORACLE will give the INTERSECT operator greater precedence than the other set operators, so you should use parentheses to explicitly specify order of evaluation in queries that use the INTERSECT operator with other set operators.

The cooresponding expressions in the select lists of the component queries of a compound query must match in number and datatype. If component queries select character data, the datatype of the return values are determined as follows:

•	If both queries select values of datatype CHAR, the returned values have datatype CHAR.

•	If either or both of the queries select values of datatype VARCHAR2, the returned values have datatype VARCHAR2.

 Examples

Consider these two queries and their results:

SELECT part

FROM orders_list1

PART

----------

SPARKPLUG

FUEL PUMP

FUEL PUMP TAILPIPE

SELECT part

FROM orders_list2

PART

----------

CRANKSHAFT

TAILPIPE

TAILPIPE

The following examples combine the two query results with each of the set operators.

UNION

Example	This statement combines the results with the UNION operator, which eliminates duplicate selected rows:

SELECT part FROM orders_list1

UNION SELECT part FROM orders_list2

PART

----------

SPARKPLUG

FUEL PUMP

TAILPIPE CRANKSHAFT

UNION ALL

Example	This statement combines the results with the UNION ALL operator which does not eliminate duplicate selected rows:

SELECT part FROM orders_list1

UNION ALL

SELECT part FROM orders_list2

PART

----------

SPARKPLUG

FUEL PUMP

FUEL PUMP

TAILPIPE

CRANKSHAFT

TAILPIPE

TAILPIPE

Note that the UNION operator returns only distinct rows that appear in either result, while the UNION ALL operator returns all rows. A PART value that appears multiple times in either or both queries (such as 'FUEL PUMP') is returned only once by the UNION operator, but multiple times by the UNION ALL operator.

INTERSECT

Example 	This statement combines the results with the INTERSECT operator which returns only those rows returned by both queries:

SELECT part FROM orders_list1

INTERSECT

SELECT part FROM orders_list2

PART

----------

TAILPIPE

MINUS

Example	This statement combines the results with the MINUS operator which returns only those rows returned by the first query but not in the second:

SELECT part FROM orders_list1

MINUS

SELECT part FROM orders_list2

PART

----------

SPARKPLUG FUEL PUMP

Other Operators

Table 3 - 10 lists other SQL operators.

Operator	Purpose	Example

(+)	Indicates that the preceding 	SELECT ename, dname

column is the outer join col	FROM emp, dept

umn in a join. See the sec	WHERE dept.deptno =

tion "Outer Joins" on page 	emp.deptno (+)

XXX (X-REF HERE)

PRIOR	Evaluates the following ex	SELECT empno, ename, mgr

pression for the parent row 	FROM emp

of the current row in a hier	CONNECT BY

archical, or tree-structured, 	PRIOR empno = mgr

query. In such a query, you

must use this operator in

the CONNECT BY clause

to define the relationship

between parent and child

rows. You can also use this

operator in other parts of a

SELECT statement that per

forms a hierarchical query.

The PRIOR operator is a

unary operator and has the

same precedence as the

unary + and - arithmetic

operators. See the section

"Hierarchical Queries" on

page (X-REF HERE).

Table 3 - 10.  Other SQL Operators

________________________________________

Functions

A function is similar to an operator in that it manipulates data items and returns a result. Functions differ from operators in the format in which they appear with their arguments. This format allows them to operate on zero, one, two, or more arguments:

function(argument, argument, ...)

If you call a function with an argument of a datatype other than the datatype expected by the function, ORACLE implicitly converts the argument to the expected datatype before performing the function. See the section "Data Conversion" on page 2 - 34.

If you call a function with a null argument, the function automatically returns null. The only functions that do not follow this rule are CONCAT, REPLACE, DUMP and NVL.

Do not design your applications to rely on ORACLE either to evaluate or to not evaluate all arguments to a function.

In the syntax diagrams for functions, arguments are indicated with their datatypes following the conventions described in the Preface of this Manual.

Note: Do not confuse the SQL functions listed in this section with stored PL/SQL functions. SQL functions can only appear in SQL commands, while stored PL/SQL functions can only appear in procedural PL/SQL statements. For information on stored PL/SQL functions, see the CREATE FUNCTION command in Chapter 4  of this Manual.

Functions are of these general types:

•	single row (or scalar) functions

•	group functions (or aggregate) functions

These functions differ in the number of rows upon which they act. A single row function returns a single result row for every row of a queried table or view, while a group function returns a single result row for a group of queried rows.

Single row functions can appear in select lists (provided the SELECT statement does not contain a GROUP BY clause), WHERE clauses, START WITH clauses, and CONNECT BY clauses.

Group functions can appear in select lists and HAVING clauses. If you use the GROUP BY clause in a SELECT statement, ORACLE divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause, all elements of the select list must be either expressions from the GROUP BY clause, expressions containing group functions, or constants. ORACLE applies the group functions in the select list to each group of rows and returns a single result row for each group. If you omit the GROUP BY clause, ORACLE applies group functions in the select list to all the rows in the queried table or view. You can also use group functions in a HAVING clause in the statement to restrict the result rows returned. For more information on the GROUP BY and HAVING clauses, see the section "GROUP BY Clause" on page 8 - 344 and the section "HAVING Clause" on page 8 - 345.

This section is divided into many parts, each of which lists functions of different types. NO TAG directs you to the page where each part begins.

Type of Function	Page Reference

Single Row Functions	NO TAG

Number Functions	NO TAG

Character Functions	NO TAG

returning Character Values	NO TAG

retunring Number Values	NO TAG

Date Functions	NO TAG

Conversion Functions	NO TAG

Other Functions	NO TAG

Group Functions	NO TAG

Table 3 - 11.  Types of Functions

Single Row Functions

The following functions are single row functions grouped together by the datatypes of their arguments and return values.

Number Functions

Number functions accept numeric input and return numeric values. This section lists the SQL number functions. Most of these functions return values that are accurate to 38 decimal digits. The transcendental functions (COS, COSH, EXP, LN, LOG, SIN, SINH, SQRT, TAN, TANH) are accurate to 36 decimal digits.

 ABS

Syntax	ABS(n)

Purpose	Returns the absolute value of n

Example	SELECT ABS(-15) "Absolute" FROM DUAL Absolute

--------

      15

 CEIL

Syntax	CEIL(n)

Purpose	Returns smallest integer greater than or equal to n.

Example	SELECT CEIL(15.7) "Ceiling" FROM DUAL

Ceiling

-------

     16

 COS

Syntax	COS(n)

Purpose	Returns the cosine of n (an angle expressed in radians).

Example	SELECT COS(180 * 3.14159265359/180)

"Cosine of 180 degrees" FROM DUAL Cosine of 180 degrees

---------------------

                    -1

 COSH

Syntax	COSH(n)

Purpose	Returns the hyperbolic cosine of n.

Example	SELECT COSH(0) "Hyperbolic cosine of 0" FROM DUAL

Hyperbolic cosine of 0

----------------------

                     1

 EXP

Syntax	EXP(n)

Purpose	Returns e raised to the nth power;  e = 2.71828183 ...

Example	SELECT EXP(4) "e to the 4th power" FROM DUAL

e to the 4th power

------------------

          54.59815

 FLOOR

Syntax	FLOOR(n)

Purpose	Returns largest integer equal to or less than n.

Example	SELECT FLOOR(15.7) "Floor" FROM DUAL

Floor

-----

    15

 LN

Syntax	LN(n)

Purpose	Returns the natural logarithm of n, where n is greater than 0.

Example	SELECT LN(95) "Natural log of 95" FROM DUAL

Natural log of 95

-----------------

       4.55387689

 LOG

Syntax	LOG(m,n)

Purpose	Returns the logarithm, base m, of n. The base m can be any positive number other than 0 or 1 and n can be any positive number.

Example	SELECT LOG(10,100) "Log base 10 of 100"

      FROM DUAL

Log base 10 of 100

------------------

                 2

 MOD

Syntax	MOD(m,n)

Purpose	Returns remainder of m divided by n. Returns m if n is 0.

Example	SELECT MOD(11,4) "Modulus" FROM DUAL Modulus

-------

      3

Note	This function behaves differently from the classical mathematical modulus function when m is negative. The classical modulus can be expressed in terms of the MOD function with this formula:

m - n * FLOOR(m/n)

Example	This statement illustrates the difference between the MOD function and the classical modulus:

SELECT m, n, MOD(m,n),

m - n * FLOOR(m/n) "Classical Modulus"

      FROM test_mod_table

  M   N MOD (M,N) Classical Modulus

--- ---- -------- --------- -------

 11   4        3

-11   4       -3                  1

 11  -4        3                 -1

-11  -4       -3                 -3

 POWER

Syntax	POWER(m,n)

Purpose	Returns m raised to the nth power. The base m and the exponent n can be any numbers, but if m is negative, n must be an integer.

Example	SELECT POWER(3,2) "Raised" FROM DUAL Raised

------

      9

 ROUND

Syntax	ROUND(n[,m])

Purpose	Returns n rounded to m places right of the decimal point; if m is omitted, to 0 places. m can be negative to round off digits left of the decimal point. m must be an integer.

Example	SELECT ROUND(15.193,1) "Round" FROM DUAL

Round

-----

15.2

 SIGN

Syntax	SIGN(n)

Purpose	If n<0, the function returns -1; if n=0, the function returns 0; if n>0, the function returns 1.

Example	SELECT SIGN(-15) "Sign" FROM DUAL

Sign

----

    -1

 SIN

Syntax	SIN(n)

Purpose	Returns the sine of n (an angle expressed in radians).

Example	SELECT SIN(30 * 3.14159265359/180)

 "Sine of 30 degrees"

      FROM DUAL

Sine of 30 degrees

 ----------------

                          .5

 SINH

Syntax	SINH(n)

Purpose	Returns the hyperbolic sine of n.

Example	SELECT SINH(1) "Hyperbolic sine of 1"

FROM DUAL

Hyperbolic sine of 1

 ------------------

                1.17520119

 SQRT

Syntax	SQRT(n)

Purpose	Returns square root of n. The value n cannot be negative. SQRT returns a "real" result.

Example	SELECT SQRT(26) "Square root"

FROM DUAL

Square root

----------

 5.09901951

 TAN

Syntax	TAN(n)

Purpose	Returns the tangent of n (an angle expressed in radians).

Example	SELECT TAN(135 * 3.14159265359/180)

"Tangent of 135 degrees"

      FROM DUAL

Tangent of 135 degrees

 --------------------

                                -1

 TANH

Syntax	TANH(n)

Purpose	Returns the hyperbolic tangent of n.

Example	SELECT TANH(.5) "Hyperbolic tangent of .5"

FROM DUAL

Hyperbolic tangent of .5

----------------------

                      .462117157

 TRUNC

Syntax	TRUNC(n[,m])

Purpose	Returns n truncated to m decimal places; if m is omitted, to 0 places. m can be negative to truncate (make zero) m digits left of the decimal point.

Examples	SELECT TRUNC(15.79,1) "Truncate" FROM DUAL

Truncate

--------

    15.7

SELECT TRUNC(15.79,-1) "Truncate"

      FROM DUAL

Truncate

--------

      10

Character Functions

Single row character functions accept character input and can return both character and number values.

This section lists character functions that return character values. Unless otherwise noted, these functions all return values with the datatype VARCHAR2 and are limited in length to 2000 bytes. Functions that return values of datatype CHAR are limited in length to 255 bytes. If the length of the return value exceeds the limit, ORACLE truncates it and returns the result without an error message.

This section lists character functions that return character values. Unless otherwise noted, these functions all return values with the datatype VARCHAR2 and are limited in length to 2000 bytes. Functions that return values of datatype CHAR are limited in length to 255 bytes. If the length of the return value exceeds the limit, ORACLE truncates it and returns the result without an error message.

 CHR

Syntax	CHR(n)

Purpose	Returns the character having the binary equivalent to n in the database character set.

Example	SELECT CHR(75) "Character" FROM DUAL Character

---------

K

 CONCAT

Syntax	CONCAT(char1, char2)

Purpose	Returns char1 concatenated with char2. This function is equivalent to the concatenation operator (||). For information on this operator, see the section "Character  on page 3 - 3.

Example	This example uses nesting to concatenate three character strings:

SELECT CONCAT( CONCAT(ename, ' is a '), job) "Job"

      FROM emp

      WHERE empno = 7900

Job

-------------------------

JAMES is a CLERK

 INITCAP

Syntax	INITCAP(char)

Purpose	Returns char, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by white space or characters that are not alphanumeric.

Example	SELECT INITCAP('the soap') "Capitalized" FROM DUAL

Capitalized

--------------------

The Soap

 LOWER

Syntax	LOWER(char)

Purpose	Returns char, with all letters lowercase. The return value has the same datatype as the argument char (CHAR or VARCHAR2).

Example	SELECT LOWER('MR. SAMUEL HILLHOUSE') "Lowercase"

      FROM DUAL

Lowercase

--------------------

mr. samuel hillhouse

 LPAD

Syntax	LPAD(char1,n [,char2])

Purpose	Returns char1, left-padded to length n with the sequence of characters in char2; char2 defaults to ' ', a single blank. If char1 is longer than n, this function returns the portion of char1 that fits in n.

The argument n is the total length of the return value as it is displayed on your terminal screen. In most character sets, this is also the number of characters in the return value. However, in some multi-byte character sets, the display length of a character string can differ from the number of characters in the string.

Example	SELECT LPAD('Page 1',15,'*.') "LPAD example"

      FROM DUAL

LPAD example

---------------

*.*.*.*.*Page 1

 LTRIM

Syntax	LPAD(char1,n [,char2])

Purpose	Removes characters from the left of char, with all the left-most characters that appear in set removed; set defaults to ' ', a single blank. ORACLE begins scanning char from its first character and removes all characters that appear in set until reaching a character not in set and then returns the result.

Example	SELECT LTRIM('xyxXxyLAST WORD','xy')

 "Left trim example"

      FROM DUAL

Left trim example

 -----------------

XxyLAST WORD

 NLS_INITCAP

Syntax	NLS_INITCAP(char [, 'nlsparams'] )

Purpose	Returns char, with the first letter of each word in uppercase, all other letters in lowercase. Words are delimited by white space or characters that are not alphanumeric. The value of 'nlsparams' can have this form:

'NLS_SORT = sort'

where sort is either a linguistic sort sequence or BINARY. The linguistic sort sequence handles special linguistic requirements for case conversions. Note that these requirements can result in a return value of a different length than the char. If you omit 'nlsparams', this function uses the default sort sequence for your session. For information on sort sequences, see Appendix A "National Language Support"  of the ORACLE7 Server Concepts Manual.

Example	SELECT NLS_INITCAP('ijsland', 'NLS_SORT = XDutch') "Capitalized"

      FROM DUAL

Capitalized

--------------------

IJsland

 NLS_LOWER

Syntax	NLS_LOWER(char [, 'nlsparams'] )

Purpose	Returns char, with all letters lowercase. The 'nlsparams' can have the same form and serve the same purpose as in the NLS_INITCAP function.

Example	SELECT NLS_LOWER('CITTA''', 'NLS_SORT = XItalian') "Lowercase"

      FROM DUAL

Lowercase

-----------------

città

 NLS_UPPER

Syntax	NLS_UPPER(char [, 'nlsparams'] )

Purpose	Returns char, with all letters uppercase. The 'nlsparams' can have the same form and serve the same purpose as in the NLS_INITCAP function.

Example	SELECT NLS_UPPER('gro', 'NLS_SORT = XGerman') "Uppercase"

      FROM DUAL

Uppercase

 ---------

GROSS

 REPLACE

Syntax	REPLACE(char, search_string[,replacement_string])

Syntax

Purpose	Returns char with every occurrence of search_string replaced with replacement_string. If replacement_string is omitted or null, all occurrences of search_string are removed. If search_string is null, char is returned. This function provides a superset of the functionality provided by the TRANSLATE function. TRANSLATE provides single character, one to one, substitution. REPLACE allows you to substitute one string for another as well as to remove character strings.

Example	SELECT REPLACE('JACK and JUE','J','BL') "Changes"

       FROM DUAL

Changes

------------

BLACK and BLUE

 RPAD

Syntax	RPAD(char1, n [,char2])

Purpose	Returns char1, right-padded to length n with char2, replicated as many times as necessary; char2 defaults to ' ', a single blank. If char1 is longer than n, this function returns the portion of char1 that fits in n.

The argument n is the total length of the return value as it is displayed on your terminal screen. In most character sets, this is also the number of characters in the return value. However, in some multi-byte character sets, the display length of a character string can differ from the number of characters in the string.

Example	SELECT RPAD(ename,11,'ab') "RPAD example"

      FROM emp

      WHERE ename = 'TURNER'

RPAD example

------------

TURNERababa

 RTRIM

Syntax	RTRIM(char [,set]

Purpose	Returns char, with all the right-most characters that appear in set removed; set defaults to ' ', a single blank. RTRIM works similarly to LTRIM.

Example	SELECT RTRIM('TURNERyxXxy','xy')

"Right trim example" FROM DUAL

Right trim example

------------------

TURNERyxX

 SOUNDEX

Syntax	SOUNDEX(char )

Purpose	Returns a character string containing the phonetic representation of char. This function allows you to compare words that are spelled differently, but sound alike in English.

The phonetic representation is defined in The Art of Computer Programming, Volume 3: Sorting and Searching, by Donald E. Knuth.

Example	SELECT ename

      FROM emp

      WHERE SOUNDEX(ename) =

                   SOUNDEX('SMYTHE')

ENAME

----------

SMITH

 SUBSTR

Syntax	SUBSTR(char,m [,n])

Purpose	Returns a portion of char, beginning at character m, n characters long. If m is positive, ORACLE counts from the beginning of char to find the first character. If m is negative, ORACLE counts backwards from the end of char. The value m cannot be 0. If n is omitted, ORACLE returns all characters to the end of char. The value n cannot be less than 1.

Example	SELECT SUBSTR('ABCDEFG',3,2) "Substring" FROM DUAL

Substring

----------

CD SELECT SUBSTR('ABCDEFG',-3,2) "Reversed Substring"

      FROM DUAL

Reversed Substring

------------------

EF

 SUBSTRB

Syntax	SUBSTRB(char,m [,n])

Purpose	The same as SUBSTR, except that the arguments m and n are expressed in bytes, rather than in characters. For a single-byte database character set, SUBSTRB is equivalent to SUBSTR.

Example	Assume a double-byte database character set:

SELECT SUBSTRB('ABCDEFG',5,4) "Substring with bytes"

      FROM DUAL

Substring with bytes

 --------------------

CD

 TRANSLATE

Syntax	TRANSLATE(char,from,to)

Purpose	Returns char with all occurrences of each character in from replaced by its corresponding character in to. Characters in char that are not in from are not replaced. The argument from can contain more characters than to. In this case, the extra characters at the end of from have no corresponding characters in to. If these extra characters appear in char, they are removed from the return value. You cannot use empty string for to in order to remove all characters in from from the return value. ORACLE interprets the empty string as null, and if this function has a null argument, it returns null.

Examples	This statement translates a license number. All letters 'ABC...Z' are translated to 'X' and all digits '012...9' are translated to '9':

SELECT TRANSLATE('2KRW229', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '9999999999XXXXXXXXXXXXXXXXXXXXXXXXXX')

"Translate example"

      FROM DUAL

Translate example

-----------------

9XXX999

This statement returns a license number with the characters removed and the digits remaining:

SELECT TRANSLATE('2KRW229', '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '0123456789')

"Translate example"

      FROM DUAL

Translate example

-----------------

2229

 UPPER

Syntax	UPPER(char)

Purpose	Returns char, with all letters uppercase. The return value has the same datatype as the argument char .

Example	SELECT UPPER('Large') "Uppercase" FROM DUAL

Uppercase

---------

LARGE

 Character Functions Returning Number Values

This section lists character functions that return number values.

 ASCII

Syntax	ASCII(char)

Purpose	Returns the decimal representation in the database character set of the first byte of char. If your database character set is 7-bit ASCII, this function returns an ASCII value. If your database character set is EBCDIC Code Page 500, this function returns an EBCDIC value. Note that there is not a similar EBCDIC character function.

Example	SELECT ASCII('Q') FROM DUAL

ASCII('Q')

----------

        81

 INSTR

Syntax	INSTR(char1,char2[,n[,m]])

Purpose	Searches char1 beginning with its nth character for the mth occurrence of char2 and returns the position of the character in char1 that is the first character of this occurrence. If n is negative, ORACLE counts and searches backward from the end of char1. The value of m must be positive. The default values of both n and m are 1, meaning ORACLE begins searching at the first character of char1 for the first occurrence of char2. The return value is relative to the beginning of char1, regardless of the value of n, and is expressed in characters. If the search is unsuccessful (if char2 does not appear m times after the nth character of char1) the return value is 0.

Examples	SELECT INSTR('CORPORATE FLOOR','OR', 3, 2)

"Instring" FROM DUAL

Instring

 ---------

        14

SELECT INSTR('CORPORATE FLOOR','OR', -3, 2)

"Reversed Instring" FROM DUAL Reversed Instring

-----------------

                 2

 INSTRB

Syntax	INSTRB(char1,char2[,n[,m]])

Purpose	The same as INSTR, except that n and the return value are expressed in bytes, rather than in characters. For a single-byte database character set, INSTRB is equivalent to INSTR.

Example	SELECT INSTRB('CORPORATE FLOOR','OR',5,2)

"Instring in bytes" FROM DUAL

Instring in bytes

-----------------

               27

 LENGTH

Syntax	LENGTH(char)

Purpose	Returns the length of char in characters. If char has datatype CHAR, the length includes all trailing blanks. If char is null, this function returns null.

Example	SELECT LENGTH('CANDIDE') "Length in characters"

      FROM DUAL

Length in characters

--------------------

                    7

 LENGTHB

Syntax	LENGTHB(char)

Purpose	Returns the length of char in bytes. If char is null, this function returns null. For a single-byte database character set, LENGTHB is equivalent to LENGTH.

Example	Assume a double-byte database character set:

SELECT LENGTH('CANDIDE') "Length in bytes"

      FROM DUAL

Length in bytes

---------------

             14

 NLSSORT

Syntax	NLSSORT(char [, 'nlsparams'])

Purpose	Returns the string of bytes used to sort char. The value of 'nlsparams' can have the form

Example	'NLS_SORT = sort'

where sort is a linguistic sort sequence or BINARY. If you omit 'nlsparams', this function uses the default sort sequence for your session. If you specify BINARY, this function returns char.

For information on sort sequences, see Appendix A "National Language Support" of the ORACLE7 Server Concepts Manual.

Example	This function can be used to specify comparisons based on a linguistic sort sequence rather on the binary value of a string:

SELECT * FROM emp

      WHERE NLSSORT(ename, 'NLS_SORT = German') >

            NLSSORT('B',   'NLS_SORT = German')

Date Functions

Date functions operate on values of the DATE datatype. All date functions return a value of DATE datatype, except the MONTHS_BETWEEN function, which returns a number.

 ADD_MONTHS

Syntax	ADD_MONTHS(d,n)

Purpose	Returns the date d plus n months. The argument n can be any integer. If d is the last day of the month or if the resulting month has fewer days than the day component of d, then the result is the last day of the resulting month. Otherwise, the result has the same day component as d .

Example	SELECT TO_CHAR(ADD_MONTHS(hiredate,1),

                'DD-MON-YYYY') "Next month"

      FROM emp WHERE ename = 'SMITH' Next month

-----------

17-JAN-1981

 LAST_DAY

Syntax	LAST_DAY(d)

Purpose	Returns the date of the last day of the month that contains d. You might use this function to determine how many days are left in the current month.

Example	SELECT SYSDATE,

LAST_DAY(SYSDATE) "Last", LAST_DAY(SYSDATE) - SYSDATE "Days Left"

      FROM DUAL SYSDATE    Last       Days Left ---------  ---------  --------- 18-NOV-92  30-NOV-92         12

SELECT TO_CHAR(ADD_MONTHS(LAST_DAY(hiredate),5),

                'DD-MON-YYYY') "Five months"

      FROM emp WHERE ename = 'MARTIN' Five months

-----------

28-FEB-1992SELECT TO_CHAR(ADD_MONTHS(hiredate,1),

                'DD-MON-YYYY') "Next month"

      FROM emp WHERE ename = 'SMITH' Next month

-----------

17-JAN-1981

 MONTHS_BETWEEN

Syntax	MONTHS_BETWEEN(d1,d2)

Purpose	Returns number of months between dates d1 and d2. If d1 is later than d2, result is positive; if earlier, negative. If d1 and d2 are either the same days of the month or both last days of months, the result is always an integer; otherwise ORACLE calculates the fractional portion of the result based on a 31-day month and also considers the difference in time components of d1 and d2.

Example	SELECT MONTHS_BETWEEN(TO_DATE('02-02-1992',

                               'MM-DD-YYYY'),

                       TO_DATE('01-01-1992',

                               'MM-DD-YYYY') ) "Months" FROM DUAL Months

 ----------1.03225806

 NEW_TIME

Syntax	NEW_TIME(d,z1,z2)

Purpose	Returns the date and time in time zone z2 when date and time in time zone z1 are d. The arguments z1 and z2 can be any of these text strings:

'AST' or 'ADT' Atlantic Standard or Daylight Time

'BST' or 'BDT' Bering Standard or Daylight Time

'CST' or 'CDT' Central Standard or Daylight Time

'EST' or 'EDT' Eastern Standard or Daylight Time

'GMT' Greenwich Mean Time

'HST' or 'HDT' Alaska-Hawaii Standard Time or Daylight Time.

'MST' or 'MDT' Mountain Standard or Daylight Time

'NST' Newfoundland Standard Time

'PST' or 'PDT' Pacific Standard or Daylight Time

'YST' or 'YDT' Yukon Standard or Daylight Time

 NEXT_DAY

Syntax	NEXT_DAY(d,char)

Purpose	Returns the date of the first weekday named by char that is later than the date d. The argument char must be a day of the week in your session's date language. The return value has the same hours, minutes, and seconds component as the argument d.

SELECT NEXT_DAY('15-MAR-92','TUESDAY') "NEXT DAY"

      FROM DUAL

NEXT DAY

---------

17-MAR-92

 ROUND

Syntax	ROUND(d[,fmt])

Purpose	Returns d rounded to the unit specified by the format model fmt. If you omit fmt, d is rounded to the nearest day.

For details on ROUND and TRUNC, see the section "ROUND and TRUNC" on page NO TAG.

Example	SELECT ROUND(TO_DATE('27-OCT-92'),'YEAR') "FIRST OF THE YEAR" FROM DUAL

FIRST OF THE YEAR

-----------------

01-JAN-93

 SYSDATE

Syntax	SYSDATE

Purpose	Returns the current date and time. Requires no arguments. In distributed SQL statements, this function returns the date and time on your local database. You cannot use this function in the condition of a CHECK constraint.

Example	SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS')

 NOW

       FROM DUAL

NOW

-------------------

10-29-1993 20:27:11.

 TRUNC

Syntax	TRUNC(d,[fmt])

Purpose	Returns d with the time portion of the day truncated to the unit specified by the format model fmt. If you omit fmt, d is truncated to the nearest day. See the next section "ROUND and TRUNC".

Example	SELECT TRUNC(TO_DATE('27-OCT-92', 'DD-MON-YY'),

              'YEAR')

"First Of The Year"

      FROM DUAL

FIRST OF THE YEAR

-----------------

01-JAN-92

 lists the format models to be used with the ROUND and TRUNC date functions and the units to which they round and truncate dates. The default model, 'DD', returns the date rounded or truncated to the day with a time of midnight.

NO TAG lists the format models to be used with the ROUND and TRUNC date functions and the units to which they round and truncate dates. The default model, 'DD', returns the date rounded or truncated to the day with a time of midnight.

CC, SCC	Century

SYYYY, YYYY, YEAR, 	Year (rounds up on July 1)

SYEAR, YYY, YY, Y

IYYY, IY, IY, I	ISO Year

Q	Quarter (rounds up on the sixteenth day of

the second month of the quarter)

MONTH, MON, MM, 	Month (rounds up on the sixteenth day)

RM

WW	Same day of the week as the first day of the

year.

IW	Same day of the week as the first day of the

ISO year.

W	Same day of the week as the first day of the

month.

DDD, DD, J	Day

DAY, DY, D	Starting day of the week

HH, HH12, HH24	Hour

MI	Minute

Table 3 - 12.  Date Format Models for the

ROUND and TRUNC Date Functions

The starting day of the week used by the format models DAY, DY, and D is specified implicitly by the initialization parameter

For information on this parameter, see Appendix C "National Language Support" of the ORACLE7 Server Administrator's Guide.

Conversion Functions

Conversion functions convert a value from one datatype to another. Generally, the form of the function names follows the convention datatype TO datatype. The first datatype is the input datatype; the last datatype is the output datatype. This section lists the SQL conversion functions.

 CHARTOROWID

Syntax	CHARTOROWID(char)

Purpose	Converts a value from CHAR or VARCHAR2 datatype to ROWID datatype.

Example	SELECT ename

      FROM emp

      WHERE ROWID = CHARTOROWID('0000000F.0003.0002') ENAME

-----

SMITH

 CONVERT

Syntax	CONVERT(char, dest_char_set [,source_char_set] )

Purpose	Converts a character string from one character set to another.

The char argument is the value to be converted.

The dest_char_set argument is the name of the character set to which char is converted.

The source_char_set argument is the name of the character set in which char is stored in the database. The default value is the database character set.

Both the destination and source character set arguments can be either literals or columns containing the name of the character set.

For complete correspondence in character conversion, it is essential that the destination character set contains a representation of all the characters defined in the source character set. Where a character does not exist in the destination character set, a replacement character appears. Replacement characters can be defined as part of a character set definition.

Common character sets include:

US7ASCII	US 7-bit ASCII character set

WE8DEC	DEC West European 8-bit character set

WE8HP	HP West European Laserjet 8-bit character set

F7DEC	DEC French 7-bit character set

WE8EBCDIC500	IBM West European EBCDIC Code Page 500

WE8PC850	IBM PC Code Page 850

WE8ISO8859P1	ISO 8859-1 West European 8-bit character set

Example	SELECT CONVERT('Grob','WE8HP','WE8DEC') "Conversion"

      FROM DUAL

Conversion

----------

Groß

 HEXTORAW

Syntax	HEXTORAW(char)

Purpose	Converts char containing hexadecimal digits to a raw value.

Example	INSERT INTO graphics (raw_column)

      SELECT HEXTORAW('7D')

      FROM DUAL

 RAWTOHEX

Syntax	RAWTOHEX(raw)

Purpose	Converts raw to a character value containing its hexadecimal equivalent.

Example	SELECT RAWTOHEX(raw_column) "Graphics"

      FROM graphics

Graphics

--------

7D

 ROWIDTOCHAR

Syntax	ROWIDTOCHAR(rowid)

Purpose	Converts a ROWID value to VARCHAR2 datatype. The result of this conversion is always 18 characters long.

Example	SELECT ROWID FROM graphics

      WHERE ROWIDTOCHAR(ROWID) LIKE '%F38%'

ROWID

------------------

00000F38.0001.0001

 TO_CHAR, date conversion

Syntax	TO_CHAR(d [, fmt [, 'nlsparams'] ])

Purpose	Converts d of DATE datatype to a value of VARCHAR2 datatype in the format specified by the date format fmt. If you omit fmt, d is converted to a VARCHAR2 value in the default date format. For information on date formats, see the section "Format Models" on page NO TAG.

The 'nlsparams' specifies the language in which month and day names and abbreviations are returned. This argument can have this form:

'NLS_DATE_LANGUAGE = language'

If you omit nlsparams, this function uses the default date language for your session.

Example	SELECT TO_CHAR(HIREDATE,'Month DD, YYYY')

"New date format"

      FROM emp

      WHERE ename = 'SMITH'

New date format

-------------------------------

December 17, 1980

 TO_CHAR, label conversion

Syntax	TO_CHAR(label [, fmt])

Purpose	Converts label of MLSLABEL datatype to a value of VARCHAR2 datatype, using the optional label format fmt. If you omit fmt, label is converted to a VARCHAR2 value in the default label format.

For more information on this function, see the Trusted ORACLE7 Server .

 TO_CHAR, number conversion

Syntax	TO_CHAR(n [, fmt [, 'nlsparams'] ])

Purpose	Converts n of NUMBER datatype to a value of VARCHAR2 datatype, using the optional number format fmt. If you omit fmt, n is converted to a VARCHAR2 value exactly long enough to hold its significant digits. For information on number formats, see the section "Format Models" on page NO TAG.

The 'nlsparams' specifies these characters that are returned by number format elements:

•	decimal character

•	group separator

•	local currency symbol

•	international currency symbol

This argument can have this form:

'NLS_NUMERIC_CHARACTERS = ''dg''

NLS_CURRENCY = ''text''

NLS_ISO_CURRENCY = territory '

The characters d and g represent the decimal character and group separator, respectively. They must be different single-byte characters. Note that within the quoted string, you must use two single-quotes to represent one around the parameter values.

If you omit 'nlsparams' or any one of the parameters, this function uses the default parameter values for your session.

Example	SELECT TO_CHAR(17145,'L099G999',

                'NLS_NUMERIC_CHARACTERS = ''.,''

                 NLS_CURRENCY = ''AUD'' ') "Char"

FROM DUAL

Char

------------------

        AUD017,145

 TO_DATE

Syntax	TO_DATE(char [, fmt [, 'nlsparams'] ])

Purpose	Converts char of CHAR or VARCHAR2 datatype to a value of DATE datatype. The fmt is a date format specifying the format of char. If you omit fmt, char must be in the default date format. If fmt is 'J', for Julian, then char must be a number. For information on date formats, see the section "Format Models" on page NO TAG.

The 'nlsparams' has the same purpose in this function as in the TO_CHAR function for date conversion.

Do not use the TO_DATE function with a DATE value for the char argument. The returned DATE value can have a different century value than the original char, depending on fmt or the default date format.

Example	INSERT INTO bonus (bonus_date)

      SELECT TO_DATE('January 15, 1989, 11:00 A.M.',

                     'Month dd, YYYY, HH:MI A.M.',

                     'NLS_DATE_LANGUAGE = American')

           FROM DUAL

 TO_LABEL

Syntax	TO_LABEL(char [,fmt])

Purpose	Converts char, a value of datatype CHAR or VARCHAR2 containing a label in the format specified by the optional parameter fmt, to a value of MLSLABEL datatype. If you omit fmt, char must be in the default label format. For more information on this function, see the Trusted ORACLE7 Server Administrator's Guide.

 TO_MULTI_BYTE

Syntax	TO_MULTI_BYTE(char)

Purpose	Returns char with all of its single-byte characters converted to their corresponding multi-byte characters. Any single-byte characters in char that have no multi-byte equivalents appear in the output string as single-byte characters. This function is only useful if your database character set contains both single-byte and multi-byte characters.

 TO_NUMBER

Syntax	TO_NUMBER(char [,fmt [, 'nlsparams'] ])

Purpose	Converts char, a value of CHAR or VARCHAR2 datatype containing a number in the format specified by the optional format model fmt, to a value of NUMBER datatype.

The 'nlsparams' has the same purpose in this function as in the TO_CHAR function for number conversion.

Example	UPDATE emp

      SET sal = sal +

      TO_NUMBER('AUD100.00', 'L999D99',

                   'NLS_NUMERIC_CHARACTERS = ''.,''

                    NLS_CURRENCY = ''AUD'' ')

      WHERE ename = 'BLAKE'

 TO_SINGLE_BYTE

Syntax	TO_SINGLE_BYTE(char)

Purpose	Returns char with all of its multi-byte characters converted to their corresponding single-byte characters. Any multi-byte characters in char that have no single-byte equivalents appear in the output as multi-byte characters. This function is only useful if your database character set contains both single-byte and multi-byte characters.

Example	SELECT

TO_CHAR( NEW_TIME(TO_DATE('17:47','hh24:mi'),

                   'PST','GMT'),

          'hh24:mi') "GREENWICH TIME"

      FROM DUAL

GREENWICH TIME

-------------

01:47

Other Functions

 DUMP

Syntax	DUMP(expr [,return_format

     [, start_position [, length]] ] )

Purpose	Returns a VARCHAR2 value containing the datatype code, length in bytes, and internal representation of expr. The argument return_format specifies the format of the return value and can have any of these values:

8	returns result in octal notation.

10	returns result in decimal notation.

16	returns result in hexadecimal notation.

17	returns result as single characters.

The arguments start_position and length combine to determine which portion of the internal representation to return. The default is to return the entire internal representation in decimal notation.

If expr is null, this function returns 'NULL'.

For the datatype corresponding to each code, see  Table 2 - 1 on page 2 - 22.

Examples	SELECT DUMP(ename, 8, 3, 2) "OCTAL" FROM emp

      WHERE ename = 'SCOTT' OCTAL

---------------------------------

Type=1 Len=5: 117,124

SELECT DUMP(ename, 10, 3, 2) "ASCII" FROM emp

      WHERE ename = 'SCOTT' ASCII

----------------------------

Type=1 Len=5: 79,84

SELECT DUMP(ename, 16, 3, 2) "HEX" FROM emp

      WHERE ename = 'SCOTT' HEX

----------------------------

Type=1 Len=5: 4f,54

SELECT DUMP(ename, 17, 3, 2) "CHAR" FROM emp

      WHERE ename = 'SCOTT' CHAR

-----------------------

Type=1 Len=5: O,T

 GREATEST

Syntax	GREATEST(expr [,expr] ...)

Purpose	Returns the greatest of the list of exprs. All exprs after the first are implicitly converted to the datatype of the first prior to the comparison. ORACLE compares the exprs using non-padded comparison semantics. Character comparison is based on the value of the character in the database character set. One character is greater than another if it has a higher value. If the value returned by this function is character data, its datatype is always VARCHAR2.

Example	SELECT GREATEST('HARRY','HARRIOT','HAROLD') "GREATEST"

      FROM DUAL

GREATEST

--------

HARRY

 GREATEST_LB

Syntax	GREATEST_LB(label [,label] ...)

Purpose	Returns the greatest lower bound of the list of labels. Each label must either have datatype MLSLABEL or RAW MLSLABEL or be a quoted literal in the default label format. The return value has datatype RAW MLSLABEL.

For the definition of greatest lower bound and examples of this function, see the Trusted ORACLE7 Server .

 LEAST

Syntax	LEAST(expr [,expr] ...)

Purpose	Returns the least of the list of exprs. All exprs after the first are implicitly converted to the datatype of the first prior to the comparison. ORACLE compares the exprs using non-padded comparison semantics. If the value returned by this function is character data, its datatype is always VARCHAR2.

Example	SELECT LEAST('HARRY','HARRIOT','HAROLD')

"LEAST"

      FROM DUAL

LEAST

------

HAROLD

 LEAST_UB

Syntax	LEAST_UB(label [,label] ...)

Purpose	Returns the least upper bound of the list of labels. Each label must have datatype MLSLABEL or be a quoted literal in the default label format. The return value has datatype RAW MLSLABEL. For the definition of least upper bound and

 NVL

Syntax	NVL(expr1, expr2)

Purpose	If expr1 is null, returns expr2; if expr1 is not null, returns expr1. The arguments expr1 and expr2 can have any datatype. If their datatypes are different, ORACLE converts expr2 to the datatype of expr1 before comparing them. The datatype of the return value is always the same as the datatype of expr1, unless expr1 is character data in which case the return value's datatype is VARCHAR2.

Example	SELECT ename, NVL(TO_CHAR(COMM),'NOT APPLICABLE') "COMMISSION"

FROM emp

WHERE deptno = 30

ENAME     COMMISSION

--------- -----------

ALLEN     300

WARD      500

MARTIN    1400

BLAKE     NOT APPLICABLE

TURNER    0

JAMES     NOT APPLICABLE

 UID

Syntax	UID

Purpose	Returns an integer that uniquely identifies the current user.

 USER

Syntax	USER

Purpose	Returns the current ORACLE user with the datatype VARCHAR2. ORACLE compares values of this function with blank-padded comparison semantics.

In a distributed SQL statement, the UID and USER functions identify the user on your local database. You cannot use these functions in the condition of a CHECK constraint.

Example	SELECT USER, UID FROM DUAL

USER          UID

--------- -------

OPS$KING        9

 USERENV

Syntax	USERENV(option)

Purpose	Returns information of VARCHAR2 datatype about the current session. This information can be useful for writing an application-specific audit trail table or for determining the language-specific characters currently used by your session. You cannot use this function in the condition of a CHECK constraint. The argument option can have any of these values:

'ENTRYID'	returns available auditing entry identifier. You cannot use this option in distributed SQL statements.

'ISDBA'	returns 'TRUE' if you currently have the OSDBA role enabled and 'FALSE' if you do not.

'LABEL'	returns your current session label. This option is only applicable for Trusted ORACLE. For more information on this option, see the Trusted ORACLE7 Server Administrator's Guide.

'LANGUAGE'	returns the language and territory currently used by your session along with the database character set in this form:

'SESSIONID'	returns your auditing session identifier. You cannot use this option in distributed SQL statements.

'TERMINAL'	returns the operating system identifier for your current session's terminal. In distributed SQL statements, this option returns the identifier for your local session.

Example	SELECT USERENV('LANGUAGE') "Language" FROM DUAL; Language

--------------------------

AMERICAN_AMERICA.US7ASCII

 VSIZE

Syntax	VSIZE(expr)

Purpose	Returns the number of bytes in the internal representation of expr. If expr is null, this function returns null.

Example	SELECT ename, VSIZE(ename) "BYTES" FROM emp

      WHERE deptno = 10

ENAME          BYTES

---------- ---------

CLARK              5

KING               4

MILLER             6

Group Functions

Group functions return results based on groups of rows, rather than on single rows. In this way, group functions are different from single row functions. For a discussion of the differences between group functions and single-row functions, see the section "Functions" on page NO TAG.

Many group functions accept these options:

DISTINCT	This option causes a group function to consider only distinct values of the argument expression.

ALL	This option causes a group function to consider all values including all duplicates.

For example, the DISTINCT average of 1, 1, 1, and 3 is 2; the ALL average is 1.5. If neither option is specified, the default is ALL.

If you use the DISTINCT option with a group function, the size of the function's argument is limited to the size of a data block minus some overhead. This size is specified by the initialization parameter DB_BLOCK_SIZE.

All group functions except COUNT(*) ignore nulls. You can use the NVL in the argument to a group function to substitute a value for a null.

If a query with a group function returns no rows or only rows with nulls for the argument to the group function, the group function returns null.

 AVG

Syntax	AVG([DISTINCT|!!under!!ALL] n)

Purpose	Returns average value of n.

Example	SELECT AVG(sal) "Average"

      FROM emp

    Average

----------

2073.21429

 COUNT

Syntax	COUNT({* | [DISTINCT|!!under!!ALL] expr})

Purpose	Returns the number of rows in the query.

If you specify expr, this function returns rows where expr is not null. You can count either all rows, or only distinct values of expr.

If you specify the asterisk (*), this function returns all rows, including duplicates and nulls.

Examples	SELECT COUNT(*) "Total" FROM emp

Total

-----

   14

SELECT COUNT(job) "Count" FROM emp Count

-----

  14

SELECT COUNT(DISTINCT job) "Jobs" FROM emp Jobs

----

  5

 GLB

Syntax	GLB([DISTINCT|!!under!!ALL] label)

Purpose	Returns the greatest lower bound of label.

 LUB

Syntax	LUB([DISTINCT|!!under!!ALL] label)

Purpose	Returns the least upper bound of label.

The return values have datatype MLSLABEL. For the definitions of greatest lower bound and least upper bound and examples using these functions, see the Trusted ORACLE7 Server Administrator's Guide.

 MAX

Syntax	MAX([DISTINCT|!!under!!ALL] expr)

Purpose	Returns maximum value of expr.

Example	SELECT MAX(sal) "Maximum"

      FROM emp

Maximum

-------

5000

 MIN

Syntax	MIN([DISTINCT|!!under!!ALL] expr)

Purpose	Returns minimum value of expr.

Example	SELECT MIN(hiredate) "Minimum Date"

      FROM emp

Minimum Date

------------

17-DEC-80

Note	The DISTINCT and ALL options have no effect on the MAX and MIN functions.

 STDDEV

Syntax	STDDEV([DISTINCT|!!under!!ALL] x)

Purpose	Returns standard deviation of x, a number. ORACLE calculates the standard deviation as the square root of the variance defined for the VARIANCE group function.

Example	SELECT STDDEV(sal) "Deviation" FROM emp

Deviation

----------

1182.50322

 SUM

Syntax	SUM([DISTINCT|!!under!!ALL] n)

Purpose	Returns sum of values of n.

Example	SELECT SUM(sal) "Total" FROM emp

Total

-----

29025

 VARIANCE

Syntax	VARIANCE([DISTINCT|!!under!!ALL]x)

Purpose	Returns variance of x, a number. ORACLE calculates the variance of x using this formula:

where:

xi	is one of the elements of x.

n	is the number of elements in the set x. If n is 1, the variance is defined to be 0.

Example	SELECT VARIANCE(sal) "Variance" FROM emp

Variance

----------

1389313.87

________________________________________

Format Models

A format model is a character literal that describes the format of DATE or NUMBER data stored in a character string. You can use a format model as an argument of the TO_CHAR or TO_DATE function for these purposes:

•	to specify the format for ORACLE to use to return a value from the database to you

•	to specify the format for a value you have specified for ORACLE to store in the database

Note that a format model does not change the internal representation of the value in the database.

This section describes how to use format models, as well as each type of format model:

•	number format models

•	date format models

Changing the Return Format

 You can use a format model to specify the format for ORACLE to use to return values from the database to you.

Example I	This statement selects the commission values of the employees in department 30 and uses the TO_CHAR function to convert these commissions into character values with the format specified by the number format model '$9,990.99':

SELECT ename employee, TO_CHAR(comm,'$9,990.99') commission

FROM emp

WHERE deptno = 30

EMPLOYEE    COMMISSION

----------  ----------

ALLEN          $300.00

WARD           $500.00

MARTIN       $1,400.00

BLAKE

TURNER           $0.00

JAMES

Because of this format model, ORACLE returns the commissions with leading dollar signs, commas every three digits, and two decimal places. Note that the TO_CHAR function returns null for all employees with null in the COMM column.

Example II	This statement selects the dates that each employee from department 20 was hired and uses the TO_CHAR function to convert these dates to character strings with the format specified by the date format model 'fmMonth DD, YYYY':

SELECT ename, TO_CHAR(Hiredate,'fmMonth DD, YYYY') hiredate

FROM emp

WHERE deptno = 20

"Functions", "SQL  functions">ENAME      HIREDATE

---------- --------------------

SMITH      December 17, 1980

JONES      April 2, 1981

SCOTT      April 19, 1987

ADAMS      May 23, 1987

FORD       December 3, 1981

With this format model, ORACLE returns the hire dates with the month spelled out, two digits for the day, and the century included in the year.

Supplying the Correct Format

You can use format models to specify the format of a value that you are converting from one datatype to another datatype required for a column. When you insert or update a column value, the datatype of the value that you specify must correspond to the column's datatype. For example, a value that you insert into a DATE column must be a value of the DATE datatype or a character string in the default date format (ORACLE implicitly converts character strings in the default date format to the DATE datatype). If the value is in another format, you must use the TO_DATE function to convert the value to the DATE datatype. You must also use a format model to specify the format of the character string.

Example III	This statement updates JONES' hire date using the TO_DATE function with the format mask 'YYYY MM DD' to convert the character string '1992 05 20' to a DATE value:

UPDATE emp

SET hiredate = TO_DATE('1992 05 20','YYYY MM DD')

WHERE ename = 'JONES'

Number Format Models

You can use number format models in these places:

•	in the TO_CHAR function to translate a value of NUMBER datatype to VARCHAR2 datatype

•	in the TO_NUMBER function to translate a value of CHAR or VARCHAR2 datatype to NUMBER datatype

All number format models cause the number to be rounded to the specified number of significant digits. If a value has more significant digits to the left of the decimal place than are specified in the format, pound signs (#) replace the value.

 Number Format Elements

A number format model is composed of one or more number format elements.

 NO TAG      lists the elements of a number format model.

Element	Example	Description

9	9999	Number of "9"s specifies number of

significant digits returned. Blanks are

returned for leading zeros and for a

value of zero.

0	0999	Returns a leading zero or a value of

9990	zero in this position as a 0, rather

than as a blank.

$	$9999	Prefixes value with dollar sign.

B	B9999	Returns zero value as blank, regard

less of "0"s in the format model.

MI	9999MI	Returns "-" after negative values.

For positive values, a trailing space is

returned.

S	S9999	Returns "+" for positive values and

"-" for negative values in this posi

tion.

PR	9999PR	Returns negative values in <angle

brackets>. For positive values, a

leading and trailing space is re

turned.

D	99D99	Returns the decimal character in this

position, separating the integral and

fractional parts of a number.

G	9G999	Returns the group separator in this

position.

C	C999	Returns the ISO currency symbol in

this position.

L	L999	Returns the local currency symbol in

this position.

, (comma)	9,999	Returns a comma in this position.

. (period)	99.99	Returns a period in this position, sep

arating the integral and fractional

parts of a number.

V	999V99	Multiplies value by 10n, where nis

the number of "9"s after the "V".

EEEE	9.999EEEE	Returns value in scientific notation.

RN	RN	Returns upper- or lower-case Ro

rn	man numerals. Value can be an inte

ger between 1 and 3999.

Table 3 - 13.  Number Format Elements

If a number format model does not contain the MI, S, or PR format elements, negative return values automatically contain a leading negative sign and positive values automatically contain a leading space.

A number format model can contain only a single decimal character (D) or period (.), but it can contain multiple group separators (G) or commas (,). A group separator or comma cannot appear to the right of a decimal character or period in a number format model.

The characters returned by some of these format elements are specified by initialization parameters. NO TAG lists these elements and parameters.

Element	Description	Initialization Parameter

D	Decimal character	NLS_NUMERIC_CHARACTER

G	Group separator	NLS_NUMERIC_CHARACTER

C	ISO currency symbol	NLS_ISO_CURRENCY

L	Local currency symbol	NLS_CURRENCY

Table 3 - 14.  Number Format element Values

Determined by Initialization Parameters

The characters returned by these format elements can also be implicitly specified by the initialization parameter NLS_TERRITORY.

You can also change the characters returned by these format elements for your session with the ALTER SESSION command. For information on this command, see Chapter 4  of this Manual.

Date Format Models

You can use date format models in these places:

•	in the TO_CHAR function to translate a DATE value that is in a format other than the default date format

•	in the TO_DATE function to translate a character value that is in a format other than the default date format

 Default Date Format

The default date format is specified either explicitly with the initialization parameter NLS_DATE_FORMAT or implicitly with the initialization parameter NLS_TERRITORY.

For information on these parameters, see Appendix C "National Language Support" of the ORACLE7 Server Administrator's Guide.  You can also change the default date format for your session with the ALTER SESSION command. For information on this command, see Chapter 4 "Commands"of this Manual.

 Date Format Elements

A date format model is composed of one or more date format elements. NO TAG lists the date format model elements.

Element	Meaning

SCC or CC	Century; "S" prefixes BC dates with "-".

YYYY or SYYYY	4-digit year; "S" prefixes BC dates with "-".

IYYY	4-digit year based on the ISO standard.

YYY or YY or Y	Last 3, 2, or 1 digit(s) of year.

IYY or IY or I	Last 3, 2, or 1 digit(s) of ISO year.

Y, YYY	Year with comma in this position.

SYEAR or YEAR	Year, spelled out; "S" prefixes BC dates with "-".

RR	Last 2 digits of year; for years in other countries.

BC or AD	BC/AD indicator.

B.C. or A.D.	BC/AD indicator with periods.

Q	Quarter of year (1, 2, 3, 4; JAN-MAR = 1)

MM	Month (01-12; JAN = 01)

RM	Roman numeral month (I-XII; JAN = I).

MONTH	Name of month, padded with blanks to length of

9 characters.

MON	Abbreviated name of month.

WW	Week of year (1-53) where week 1 starts on the

first day of the year and continues to the seventh

day of the year.

IW	Week of year (1-52 or 1-53) based on the ISO

standard.

W	Week of month (1-5) where week 1 starts on the

first day of the month and ends on the seventh.

DDD	Day of year (1-366).

DD	Day of month (1-31).

D	Day of week (1-7).

DAY	Name of day, padded with blanks to length of 9

characters.

DY	Abbreviated name of day.

J	Julian day; the number of days since January 1,

4712 BC. Number specified with 'J' must be inte

gers.

AM or PM	Meridian indicator.

A.M. or P.M.	Meridian indicator with periods.

HH or HH12	Hour of day (1-12).

HH24	Hour of day (0-23).

MI	Minute (0-59).

SS	Second (0-59).

SSSSS	Seconds past midnight (0-86399).

-/,.;: "text"	Punctuation and quoted text is reproduced in the

result.

Table 3 - 15.  Date Format Elements

 Date Format Elements and National Language Support

The functionality of some date format elements depends on the country and language in which you are using ORACLE. For example, these date format elements return spelled values:

•	MONTH

•	MON

•	DAY

•	DY

•	BC or AD or B.C. or A.D.

•	AM or PM or A.M. or P.M.

The language in which these values are returned is specified either explicitly with the initialization parameter NLS_DATE_LANGUAGE or implicitly with the initialization parameter NLS_LANGUAGE. The values returned by the YEAR and SYEAR date format elements are always in English.

The date format element D returns the number of the day of the week (1-7). The day of the week that is numbered 1 is specified implicitly by the initialization parameter NLS_TERRITORY.

For information on these initialization parameters, see Appendix C "National Language Support" of the ORACLE7 Server Administrator's Guide.

 ISO Standard Date Format Elements

ORACLE calculates the values returned by the date format elements IYYY, IYY, IY, I, and IW according to the ISO standard. For information on the differences between these values and those returned by the date format elements YYYY, YYY, YY, Y, and WW, see Appendix A "National Language Support" of the ORACLE7 Server Administrator's Guide.

 The RR Date Format Element

The RR date format element is similar to the YY date format element, but it provides additional flexibility for storing date values in other centuries. The RR date format element allows you to store twenty-first century dates in the twentieth century by specifying only the last two digits of the year. It will also allow you to store twentieth century dates in the twenty-first century in the same way if necessary.

If you use the TO_DATE function with the YY date format element, the date value returned is always in the current century. If you use the RR date format element instead, the century of the return value varies according to the specified two-digit year and the last two digits of the current year. NO TAG summarizes the behavior of the RR date format element.

If the specified two-digit year is

0 - 49	50 - 99

If the 	0 	The return date is in the

last two 	 - 	The return date is in the 	century before the

digits 	49	current century.	current one.

of the

current

year

are:

If the 	50

last two 	 - 	The return date is in the 	The return date is in the

digits 	99	century after the current 	current century.

of the 	one.

current

year

are:

Table 3 - 16.  The RR Date Element Format

The following example demonstrates the behavior of the RR date format element.

Example IV	Assume these queries are issued prior to the year 2000:

SELECT TO_CHAR(TO_DATE('27-OCT-95', 'DD-MON-RR') ,'YYYY')

"4-digit year" 	FROM DUAL

4-digit year

------------         1995

SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR') ,'YYYY')

"4-digit year"

FROM DUAL

4-digit year

------------

        2017

Assume these queries are issued in the year 2000 or after:

SELECT TO_CHAR(TO_DATE('27-OCT-95', 'DD-MON-RR') ,'YYYY')

"4-digit year"

FROM DUAL

4-digit year

------------

        1995

SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR') ,'YYYY')

"4-digit year" 	FROM DUAL

4-digit year

------------

        2017

Note that the queries return the same values regardless of whether they are issued before or after the year 2000. The RR date format element allows you to write SQL statements that will return the same values after the turn of the century.

Table XXX lists suffixes that can be added to date format elements:

When you add one of these suffixes to a date format element, the return value is always in English.

 Date Format Element Suffixes

Table XXX lists suffixes that can be added to date format elements:

Example	Example

Suffix	Meaning	Element	Value

TH	Ordinal Number	DDTH	4TH

SP	Spelled Number	DDSP	FOUR

SPTH or THSP	Spelled, ordinal number	DDSPTH	FOURTH

Table 3 - 17.  Date Format Element Suffixes

When you add one of these suffixes to a date format element, the return value is always in English.

 Capitalization of Date Format Elements

Capitalization in a spelled-out word, abbreviation, or Roman numeral follows capitalization in the corresponding format element. For example, the date format model 'DAY' produces capitalized words like 'MONDAY'; 'Day' produces 'Monday'; and 'day' produces 'monday'.

 Punctuation and Character Literals in Date Format Models

You can also include these characters in a date format model:

•	punctuation such as hyphens, slashes, commas, periods, and colons

•	character literals

These characters appear in the return value in the same location as they appear in the format model. Note that character literals must be enclosed in quotation marks (double quotes).

Format Model Modifiers

You can use the FM and FX modifiers in format models for the TO_CHAR function to control blank padding and exact format checking.

A modifier can appear in a format model more than once. In such case, each subsequent occurrence toggles the effects of the modifier. Its effects are enabled for the portion of the model following its first occurrence, and then disabled for the portion following its second, and then re-enabled for the portion following its third, and so on.

FM      "Fill mode". This modifier suppresses blank padding in the return value of the TO_CHAR function:

•	In a date format element of a TO_CHAR function, this modifier suppresses blanks in subsequent character elements (such as MONTH) and suppresses leading zeroes for subsequent number elements (such as MI) in a date format model. Since there is no blank padding, the length of the return value may vary.  Without FM, the result of a character element is always right padded with blanks to a fixed length and the leading zero are always returned for a number element.

•	In a number format element of a TO_CHAR function, this modifier suppresses blanks added to the left of the number in the result to right-justify it in the output buffer. Without FM, the result is always right-justified in the buffer, resulting in blank-padding to the left of the number.

Example V	NO TAG shows the results of the following query for different values of number and 'fmt' using FM:

<SELECT TO_CHAR(number, 'fmt')

FROM dual

(Table here)

number	'fmt'	Result

123.456	999.999	'123.456'

123.456	9.9EEEE	' 1.2E+02'

1E+123	9.9EEEE	'1.0E+123'

123.456	FM9.9EEEE	'1.2E+02'

123.456	FM999.009	'123.456'

123.45	FM999.009	'123.45'

123.0	FM999.009	'123.00'

123.45	L999.99	'	$123.45'

123.45	FML99.99	'$123.45'

Table 3 - 18.  Results of Number Conversions Using

FM Format Model Modifier

Example VI	This statement uses a date format model to return a character expression that contains the character literal "the" and a comma.

SELECT TO_CHAR(SYSDATE, 'fmDDTH "of" Month, YYYY') Ides

FROM DUAL

Ides

------------------

3RD of April, 1992

Note that this statement also uses the FM modifier. If FM is omitted, the month is blank-padded to nine characters:

SELECT TO_CHAR(SYSDATE, 'DDTH "of" Month, YYYY') Ides

FROM DUAL

Ides

-----------------------

03RD of April    , 1992

You can include a single quote in the return value by placing two consecutive single quotes in the format model.

Example VII	This statement places a single quote in the return value by using a date format model that includes two consecutive single quotes:

SELECT TO_CHAR(SYSDATE, 'fmDay''"s Special"') Menu

FROM DUAL

Menu

-----------------

Tuesday's Special

Two consecutive single quotes can also be used for the same purpose within a character literal in a format model.

FX      "Format exact". This modifier specifies exact matching for the character argument and date format model of a TO_DATE function:

•	Punctuation and quoted text in the character argument must exactly match (except for case) the corresponding parts of the format model. Without FX, punctuation and quoted text in the character argument need only match the length and position of the corresponding parts of the format model.

•	The character argument cannot have extra blanks. Without FX, ORACLE ignores extra blanks.

•	Numeric data in the character argument must have the same number of digits as the corresponding element in the format model. Without FX, numbers in the character argument can omit leading zeroes.

When FX is enabled, you can disable this check for leading zeroes by using the FM modifier as well.

If any portion of the character argument violates any of these conditions, ORACLE returns an error message.

Example VIII	NO TAG shows whether the following statement meets the matching conditions for different values of char and 'fmt' using FX:

UPDATE table

SET date_column = TO_DATE(char, 'fmt');

char	'fmt'	Match or Error?

'15/ JAN /1993'	'DD-MON-YYYY'	Match

' 15! JAN % /1993'	'DD-MON-YYYY'	Match

'15/JAN/1993'	'FXDD-MON-YYYY'	Error

'15-JAN-1993'	'FXDD-MON-YYYY'	Match

'1-JAN-1993'	'FXDD-MON-YYYY'	Error

'01-JAN-1993'	'FXDD-MON-YYYY'	Error

'1-JAN-1993'	'FXFMDD-MON-YYYY'	Match

Table 3 - 19.   Matching Character Data and Format Models with the

FX Format Model Modifier

________________________________________

Expr

Purpose

To specify an expression of any datatype. You must use this notation whenever expr appears in conditions, SQL functions, or SQL commands in other parts of this Manual.

Syntax

Expressions have several forms. ORACLE does not accept all forms of expressions in all parts of all SQL commands. The description of each command in Chapter 4 "Commands" of this Manual documents the restrictions on the expressions in the command.

 Form I

A column, pseudocolumn, constant, sequence number, or NULL.

In addition to the schema of a user, schema can also be "PUBLIC" (quotes required), in which case it must qualify a public synonym for a table, view, or snapshot. Qualifying a public synonym with "PUBLIC" is only supported in Data Manipulation Language commands, not Data Definition Language commands.

The pseudocolumn can be either LEVEL, ROWID, or ROWNUM. You can only use a pseudocolumn with a table, rather than with a view or snapshot. For more information on pseudocolumns, see the section "Pseudocolumns" on page 2 - 37.

ROWLABEL is a column automatically created by Trusted ORACLE in every table in the database. If you are using Trusted ORACLE, the expression ROWLABEL returns the row's label. If you are not using Trusted ORACLE, the expression ROWLABEL always returns NULL. For information on using labels and ROWLABEL, see the  Trusted ORACLE7 Server Administrator's Guide.

Examples

emp.ename

'this is a text string'

10

 Form II

A host variable with an optional indicator variable. Note that this form of expression can only appear in embedded SQL statements or SQL statements processed in an ORACLE Call Interfaces program.

Examples

:employee_name INDICATOR :employee_name_indicator_var

:department_location

 Form III

A call to a SQL function.

For information on SQL functions, see the section "Functions" on page NO TAG.

Examples

LENGTH('BLAKE')

ROUND(1234.567*43)

SYSDATE

 Form IV

A combination of other expressions.

Examples

('CLARK' || 'SMITH')

LENGTH('MOOSE') * 57

SQRT(144) + 72

 Decoded Expression

An expression using the special DECODE syntax:

To evaluate this expression, ORACLE compares expr to each search value one by one. If expr is equal to a search, ORACLE returns the corresponding result. If no match is found, ORACLE returns default, or, if default is omitted, returns null. If expr and search contain character data, ORACLE compares them using non-padded comparison semantics. For information on these semantics, see the section "Datatype Comparison Rules" on page 2 - 31.

ORACLE evaluates each search value only before comparing it to expr,  rather than evaluating all search values before comparing any of them with expr. Consequently, ORACLE never evaluates a search if a previous search is equal to expr.

ORACLE automatically converts expr and each search value to the datatype of the first search value before comparing. ORACLE automatically converts the return value to the same datatype as the first result. If the first result has the datatype CHAR or if the first result is null, then ORACLE converts the return value to the datatype VARCHAR2. For information on datatype conversion, see the section "Data Conversion" on page 2 - 34.

In a DECODE expression, ORACLE considers two nulls to be equivalent. If expr is null, ORACLE returns the result of the first search that is also null.

The maximum number of components in the DECODE expression, including expr, searches, results, and default is 255.

Example

This expression decodes the value DEPTNO. If DEPTNO is 10, the expression evaluates to 'ACCOUNTING'; if DEPTNO is 20, it evaluates to 'RESEARCH'; etc. If DEPTNO is not 10, 20, 30, or 40, the expression returns 'NONE'.

DECODE (deptno, 10, 'ACCOUNTING',

20, 'RESEARCH',

30, 'SALES',

40, 'OPERATION',

'NONE')

 List of Expressions

A parenthesized list of expressions.

An expression list can contain up to 254 expressions.

Examples

(10, 20, 40)

('SCOTT', 'BLAKE', 'TAYLOR')

(LENGTH('MOOSE') * 57, -SQRT(144) + 72, 69)

Usage Notes

An expression is a combination of one or more values, operators, and SQL functions that evaluates to a value. An expression generally assumesthe datatype of its components.

This simple expression evaluates to 4 and has datatype NUMBER (the same datatype as its components):

2*2

This is an example of a more complex expression that uses both functions and operators. This expression adds seven days to the current date, removes the time component from the sum, and converts the result to CHAR datatype:

TO_CHAR(TRUNC(SYSDATE+7))

You can use expressions in any of these places:

•	the select list of the SELECT command

•	a condition of the WHERE and HAVING clauses

•	the CONNECT BY, START WITH, and ORDER BY clauses

•	the VALUES clause of the INSERT command

•	the SET clause of the UPDATE command

For example, you could use an expression in place of the quoted string 'smith' in this UPDATE statement SET clause:

SET ename = 'smith'

This SET clause has the expression LOWER(ENAME) instead of the quoted string 'smith':

SET ename = LOWER(ename)

Related Topics

The section "Functions" on page NO TAG, the syntax description of 'text' on page 2 - 17, and the syntax description of number on page 2 - 19.

________________________________________

Condition

Purpose

To specify a combination of one or more expressions and logical operatorsthat evaluates to either TRUE, FALSE, or unknown. You must use this syntax whenever condition appears in SQL commands in Chapter 4 "Commands"of this Manual.

Syntax

Conditions can have several forms. The description of each command in Chapter 4 "Commands" of this Manual documents the restrictions on the conditions in the command.

 Form I

A comparison with expressions or subquery results.

For information on comparison operators, see the section  "Comparison Operators" on page 3 - 4.

 Form II

A comparison with any or all members in a list or subquery.

 Form III

A test for membership in a list or subquery.

 Form IV

A test for inclusion in a range.

 Form V

A test for nulls.

 Form VI

A test for existence of rows in a subquery.

 Form VII

A test involving pattern matching.

 Form VIII

A combination of other conditions.

Usage Notes

You can a condition in the WHERE clause of these statements:

•	DELETE

•	SELECT

•	UPDATE

You can use a condition in any of these other SELECT command clauses:

•	WHERE

•	START WITH

•	CONNECT BY

•	HAVING

A condition could be said to be of the "logical" datatype, although ORACLE does not formally support such a datatype.

This is a simple condition that always evaluates to TRUE:

1 = 1

This is a more complex condition that adds the SAL value to the COMM value (substituting the value 0 for null) and determines whether the sum is greater than the number constant 2500:

NVL(sal, 0) + NVL(comm, 0) > 2500

Logical operators can combine multiple conditions into a single condition. For example, you can use the AND operator to combine two conditions:

(1 = 1) AND (5 < 7)

For more information on how to evaluate conditions with logical operators, see the section "Logical  beginning on page 3 - 10.

Examples

ename = 'SMITH'

emp.deptno = dept.deptno

hiredate > '01-JAN-88'

job IN ('PRESIDENT', 'CLERK', 'ANALYST')

sal BETWEEN 500 AND 1000

comm IS NULL AND sal = 2000

Related Topics

SELECT, UPDATE, and DELETE commands in Chapter  4 "Commands" of this Manual.


CHAPTER 4. COMMANDS - SUMMARY OF COMMANDS TO COMMENT

This chapter contains descriptions of all SQL commands and some large clauses. Commands and clauses appear alphabetically. The description of each command or clause contains these sections:

Purpose	describes the basic uses of the command.

Prerequisites	lists privileges you must have and steps that you must take before using the command. In addition to the prerequisites listed, most commands also require that the database be open by your instance. Those commands and options for which this is not true are noted.

Syntax	shows the keywords and parameters that make up the command. The syntax diagrams used in this chapter are explained in the Preface of this Manual.

Keywords and Parameters	describes the purpose of each keyword and parameter. The conventions for keywords and parameters used in this chapter are also explained in the Preface of this Manual.

Usage Notes	discusses how and when to use the command.

Examples	shows example statements based on the command.

Related Topics	lists related commands, clauses, and sections of this and other manuals.

________________________________________

Summary of SQL Commands

The tables in the following sections provide a functional summary of SQL commands. The SQL commands are divided into these categories:

•	Data Definition Language commands

•	Data Manipulation Language commands

•	Transaction Control commands

•	Session Control commands

•	System Control commands

•	Embedded SQL commands

Data Definition Language Commands

Data Definition Language (DDL) commands allow you to perform these tasks:

•	create, alter, and drop objects

•	grant and revoke privileges and roles

•	establish auditing options

•	add comments to the data dictionary

ORACLE implicitly commits the current transaction before and after every Data Definition Language statement.

Many Data Definition Language statements may cause ORACLE to recompile or reauthorize schema objects. For information on how ORACLE recompiles and reauthorizes schema objects and the circumstances under which a Data Definition Language statement would cause this, see Chapter 16 "Dependencies Among  of the ORACLE7 Server Concepts Manual.

Data Definition Language commands are not supported by PL/SQL.

Table 4 - 1 shows the Data Definition Language Commands.

ALTER CLUSTER	To change the storage characteris

tics or to allocate an extent for a

cluster.

ALTER DATABASE	To open/mount the database, to

choose archivelog/noarchivelog

mode, to perform media recov

ery, to add/drop redo log file

groups members, to rename a

data file/redo log file member, to

backup the current control file, to

create a new data file, to take a

data file online/offline, ot en

able/disable a thread of redo log

file groups, to change the data

base's global name, to change the

MAC mode, or to set the

DBHIGH or DBLOW labels.

ALTER FUNCTION	To recompile a stored function.

ALTER INDEX	To redefine an index's future stor

age allocation.

ALTER PACKAGE	To recompile a stored package.

ALTER PROCEDURE	To recompile a stored procedure.

ALTER PROFILE	To add or remove a resource limit

to or from a profile.

ALTER RESOURCE COST	To specify a formula to calculate

the total cost of resources used by

a session.

ALTER ROLE	To change the authorization

needed to access a role.

ALTER ROLLBACK SEGMENT	To change a rollback segment's

storage characteristics or to bring

it online/offline.

ALTER SEQUENCE	To redefine value generation for a

sequence.

ALTER SNAPSHOT	To change a snapshot's storage

characteristics, automatic refresh

time, or automatic refresh mode.

ALTER SHAPSHOT LOG	To change a snapshot log's stor

age characteristics.

ALTER TABLE	To add a column/integrity

constraint to a table, to redefine a

column, to change a table's stor

age characteristics, to enable/dis

able/drop an integrity constraint,

to enable/disable all triggers on a

table, or to allocate an extent for

the table.

ALTER TABLESPACE	To add/rename data files, to

change storage characteristics, to

take a tablespace online/offline,

or to begin/end a backup.

ALTER TRIGGER	To enable/disable a database trig

ger.

ALTER USER	To change a user's password, de

fault tablespace, temporary table

space, tablespace quotas, profile,

or default roles.

ALTER VIEW	To recompile a view.

ANALYZE	To collect performance statistics,

validate structure, or identify

chained rows for a table, cluster,

or index.

AUDIT	To choose auditing for specified

SQL commands or operations on

schema objects.

COMMENT	To add a comment about a table,

view, shapshot, or column to the

data dictionary.

CREATE CLUSTER	To create a cluster that can con

tain one or more tables.

CREATE CONTROLFILE	To recreate a control file.

CREATE DATABASE	To create a database.

CREATE DATABASE LINK	To create a link to a remote data

base.

CREATE FUNCTION	To create a stored function.

CREATE INDEX	To create an index for a table or

cluster.

CREATE PACKAGE	To create the specification of a

stored package.

CREATE PACKAGE BODY	To create the body of a stored

package

CREATE PROCEDURE	To create a stored procedure.

CREATE PROFILE	To create a profile and specify its

resource limits.

CREATE ROLE	To create a role.

CREATE ROLLBACK SEGMENT	To create a rollback segment.

CREATE SCHEMA	To issue multiple CREATE

TABLE, CREATE VIEW, and

GRANT statements in a single

transaction.

CREATE SEQUENCE	To create a sequence for generat

ing sequential values.

CREATE  SHAPSHOT	To create a snapshot of data from

one or more remote master

tables.

CREATE SNAPSHOT LOG	To create a snapshot log contain

ing changes made to the master

table of a snapshot.

CREATE SYNONYM	To create a synonym for a schema

object.

CREATE TABLE	To create a table, defining its col

umns, integrity constraints, and

storage allocation.

CREATE TABLESPACE	To create a place in the database

for storage of schema objects,

rollback segments, and tempo

rary segments, naming the data

files to comprise the tablespace.

CREATE TRIGGER	To create a database trigger.

CREATE USER	To create a database user.

CREATE VIEW	To define a view of one or more

tables or views.

DROP CLUSTER	To remove a cluster from the da

tabase.

DROP DATABASE LINK	To remove a database link.

DROP FUNCTION	To remove a shared function from

the database.

DROP INDEX	To remove an index from the da

tabase.

DROP PACKAGE	To remove a stored package from

the database.

DROP PROCEDURE	To remove a stored procedure

from the database.

DROP PROFILE	To remove a profile from the da

tabase.

DROP ROLE	To remove a role from the data

base.

DROP ROLLBACK SEGMENT	To remove a rollback segment

from the database.

DROP SEQUENCE	To remove a sequence from the

database.

DROP SNAPSHOT	To remove a snapshot from the

database.

DROP SNAPSHOT LOG	To remove a snapshot log from

the database.

DROP SYNONYM	To remove a synonym from the

database.

DROP TABLE	To remove a table from the data

base.

DROP TABLESPACE	To remove a tablespace from the

database.

DROP TRIGGER	To remove a trigger from the da

tabase.

DROP USER	To remove a user and the objects

in the user's schema from the da

tabase.

DROP VIEW	To remove a view from the data

base.

GRANT	To grant system privileges, roles

and object privileges to users and

roles.

NOAUDIT	To disable auditing by reversing,

partially or completely, the effect

of a prior AUDIT statement.

RENAME	To change the name of a schema

object.

REVOKE	To revoke system privileges,

roles, and object privlieges from

users and roles.

TRUNCATE	To remove all rows from a table

or cluster and free the space that

the rows used.

Table 4 - 1.   Data Definition Language Commands

Data Manipulation Language Commands

Data Manipulation Language (DML) commands query and manipulatedata in existing schema objects. These commands do not implicitly commit the current transaction.

Command	Purpose

DELETE	To remove rows from a table.

EXPLAIN PLAN	To return the execution plan for a

SQL statement.

INSERT	To add new rows to a table.

LOCK TABLE	To lock a table or view, limiting

access to it by other users.

SELECT	To select data in rows and col

umns from one or more tables.

UPDATE	To change data in a table.

Table 4 - 2.  Data Manipulation Language Commands

All Data Manipulation Language commands except the EXPLAIN PLAN command are supported in PL/SQL.

Transaction Control Commands

Transaction Control commands manage changes made by Data Manipulation Language commands.

Command	Purpose

COMMIT	To make permanent the changes

made by statements issued and

the beginning of a transaction.

ROLLBACK	To undo all changes since the be

ginning of a transaction or since a

savepoint.

SAVEPOINT	To establish a point back to which

you may roll.

SET TRANSACTION	To establish properties for the

current transaction.

Table 4 - 3.  Transaction Control Commands

All Transaction Control commands except certain forms of the COMMIT and ROLLBACK commands are supported in PL/SQL. For information on the restrictions, see the COMMIT and ROLLBACK commands later in this chapter.

Session Control Commands

Session Control commands dynamically manage the properties of a user session. These commands do not implicitly commit the current transaction.

Command	Purpose

ALTER SESSION	To alter the current session by

preforming a specialized func

tion.

SET ROLE	To enable/disable roles for the

current session.

Table 4 - 4.  Session Control Commands

System Control Commands

System Control commands dynamically manage the properties of an ORACLE instance. This command does not implicitly commit the current transaction.

This command is not supported in PL/SQL.

Command	Purpose

ALTER SYSTEM	To alter the ORACLE instance by

performing a specialized func

tion.

Table 4 - 5.  System Control Commands

Embedded SQL Commands

Embedded SQL commands place Data Definition Language, Data Manipulation Language, and Transaction Control statements within a procedural language program. Embedded SQL is supported by the ORACLE Precompilers.

Command	Purpose

CLOSE	To disable a cursor, releasing the

resources it holds.

CONNECT	To log on to ORACLE.

DECLARE CURSOR	To declare a cursor, associating it

with a query.

DECLARE DATABASE	To declare the name of a remote

database.

DECLARE STATEMENT	To assign a SQL variable name to

a SQL statement.

DECLARE TABLE	To declare the structure of a table

for semantic checking of em

bedded SQL statements by the

ORACLE Precompiler.

DESCRIBE	To initialize a descriptor, a struc

ture holding host variable de

scriptions.

EXECUTE	To execute a prepared SQL state

ment or PL/SQL block or to

execute an anonymous PL/SQL

block.

EXECUTE IMMEDIATE	To prepare and execute a SQL

statement containing no host

variables.

FETCH	To retrieve rows selected by a

query.

OPEN	To execute the query associated

with a cursor.

PREPARE	To parse a SQL statement.

TYPE	To perform user-defined equiva

lencing.

VAR	To perform host variable equiva

lencing.

WHENEVER	To specify handling for error and

warning conditions.

Table 4 - 6.  Embedded SQL Commands

________________________________________

ALTER CLUSTER

Purpose

To redefine future storage allocations or to allocate an extent for a cluster.

Prerequisites

The cluster must be in your own schema or you must have ALTER ANY CLUSTER system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the cluster's creation label or you must satisfy one of these criteria:

•	If the cluster's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the cluster's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the cluster's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the cluster. If you omit schema, ORACLE assumes the cluster is in your own schema.

cluster	is the name of the cluster to be altered.

SIZE	determines how many cluster keys will be stored in data blocks allocated to the cluster. You can only change the SIZE parameter for an indexed cluster, not for a hash cluster. For a description of the SIZE parameter, see the CREATE CLUSTER command later in this chapter.

PCTUSED PCTFREE INITRANS MAXTRANS	changes the values of these parameters for the cluster. See the PCTUSED, PCTFREE, INITRANS, and MAXTRANS parameters of the CREATE TABLE command later in this chapter.

STORAGE	changes the storage characteristics for the cluster. See the STORAGE clause on page 8 - 371.

ALLOCATE

EXTENT	explicitly allocates a new extent for the cluster.

SIZE	specifies the size of the extent in bytes. You can use K or M to specify the extent size in kilobytes or megabytes. If you omit this parameter, ORACLE determines the size based on the values of the cluster's STORAGE parameters.

DATAFILE	specifies one of the data files in the cluster's tablespace to contain the new extent. If you omit this parameter, ORACLE chooses the data file.

INSTANCE	makes the new extent available to the specified instance. An instance is identified by the value of its initialization parameter INSTANCE_NUMBER. If you omit this parameter, the extent is available to all instances. Only use this parameter if you are using ORACLE with the Parallel Server option in parallel mode.

Explicitly allocating an extent with this clause does not cause ORACLE to evaluate the cluster's storage parameters and determine a new size for the next extent to be allocated. You can only allocate a new extent for an indexed cluster, not a hash cluster.

Usage Notes

 You can perform these tasks with the ALTER CLUSTER command:

•	change the MAXTRANS parameter value for data blocks in the cluster

•	change the SIZE, PCTUSED, PCTFREE,  and INITRANS parameter values for future data blocks in the cluster

•	change future storage characteristics with the STORAGE characteristics NEXT, PCTINCREASE, and MAXEXTENTS

•	explicitly allocate an extent

You cannot perform these tasks with the ALTER CLUSTER command:

•	change the number or the name of columns in the cluster key

•	change the values of the STORAGE parameters INITIAL and MINEXTENTS

•	change the tablespace in which the cluster is stored

•	remove tables from a cluster (see the DROP CLUSTER and DROP TABLE commands)

Example	This statement alters the CUSTOMER cluster in the schema SCOTT:

ALTER CLUSTER scott.customer

SIZE 512

STORAGE (MAXEXTENTS 25)

ORACLE now allocates 512 bytes for each cluster key value. Assuming a data block size of 2 kilobytes, future data blocks within this cluster contain 4 cluster keys per data block, or 2 kilobytes divided by 512 bytes.

The cluster can have a maximum of 25 extents.

Related Topics

CREATE CLUSTER and CREATE TABLE commands; STORAGE clause.

________________________________________

ALTER DATABASE

Purpose

To alter an existing database in one of these ways:

•	mount the database

•	convert an ORACLE Version 6 data dictionary when migrating to ORACLE7

•	open the database

•	choose archivelog or noarchivelog mode for redo log file groups

•	perform media recovery

•	add or drop a redo log file group or a member of a redo log file group

•	rename a redo log file member or a data file

•	backup the current control file

•	create a new data file in place of an old one for recovery purposes

•	take a data file online or offline

•	enable or disable a thread of redo log file groups

•	change the database's global name

•	prepare to downgrade to an earlier release of ORACLE

•	change the MAC mode

•	equate the predefined label DBHIGH or DBLOW with an operating system label

Prerequisites

You must have ALTER DATABASE system privilege.

Syntax

Keywords and Parameters

database	identifies the database to be altered. If you omit database, ORACLE alters the database identified by the value of the initialization parameter DB_NAME. You can only alter the database whose control files are specified by the initialization parameter CONTROL_FILES. Note that the database identifier is not related to the SQL*Net database specification.

You can only use the following options when the database is not mounted by your instance:

MOUNT	mounts the database.

EXCLUSIVE	mounts the database in exclusive mode. This mode allows the database to be mounted by only one instance at a time. You cannot use this option if another instance has already mounted the database.

PARALLEL	mounts the database in parallel mode. This mode allows the database to be mounted by multiple instances concurrently. You can only use this option if you are using ORACLE with the Parallel Server option. You cannot use this option if another option has mounted the database in exclusive mode.

The default is EXCLUSIVE.

CONVERT	completes the conversion of the ORACLE Version 6 data dictionary. After you use this option, the Version 6 data dictionary no longer exists in the ORACLE7 database. Only use this option when you are migrating to ORACLE7. For more information on using this option, see the ORACLE7 Server Migration Guide.

You can only use the following option when your instance has the database mounted, but not open:

OPEN	opens the database, making it available for normal use. You must mount the database before you can open it.

RESETLOGS	resets the current log sequence number to 1 and invalidates all redo entries in the online and archived redo log files. You must use this option to open the database after performing media recovery with a backup controlfile. After opening the database with this option, you should perform a complete database backup.

NORESETLOGS	leaves the log sequence number and redo log files in their current state.

You can only specify these options after performing incomplete media recovery. In any other case, ORACLE uses the NORESETLOGS automatically.

You can only use the following options when your instance has the database mounted in exclusive mode, but not open:

ARCHIVELOG	establishes archivelog mode for redo log file groups. In this mode, the contents of a redo log file group must be archived before the group can be reused. This option prepares for the possibility of media recovery. You can only use this option after shutting down your instance normally or immediately with no errors and then restarting it, mounting the database in exclusive mode.

NOARCHIVE

LOG	establishes noarchivelog mode for redo log files. In this mode, the contents of a redo log file group need not be archived so that the group can be reused. This mode does not prepare for recovery after media failure.

You can only use the following option when your instance has the database mounted in exclusive mode:

RECOVER	performs media recovery. See the RECOVER clause on page 7 - 313. You only recover the entire database when the database is closed. You can recover tablespaces or data files when the database is open or closed, provided the tablespaces or data files to be recovered are not being used. You cannot perform media recovery if you are connected to ORACLE through the multi-threaded server architecture. You can also perform media recovery with the RECOVER SQL*DBA command.

You can use any of the following options when your instance has the database mounted, open or closed, and the files involved are not in use:

ADD LOGFILE	adds one or more redo log file groups to the specified thread, making them available to the instance assigned the thread. If you omit the THREAD parameter, the redo log file group is added to the thread assigned to your instance. You need only use the THREAD parameter if you are using ORACLE with the Parallel Server option in parallel mode.

Each filespec specifies a redo log file group containing one or more members, or copies. See the syntax description of filespec  on page 7 - 279.

You can choose the value of the GROUP parameter for each redo log file group. Each value uniquely identifies the redo log file group among all groups in all threads and can range from 1 to the MAXLOGFILES value. You cannot add multiple redo log file groups having the same GROUP value. If you omit this parameter, ORACLE generates its value automatically. You can examine the GROUP value for a redo log file group through the dynamic performance table V$LOG.

ADD LOGFILE MEMBER	adds new members to existing redo log file groups. Each new member is specified by 'filename'. If the file already exists, it must be the same size as the other group members and you must specify the REUSE option. If the file does not exist, ORACLE creates a file of the correct size. You cannot add a member to a group if all of the group's members have been lost through media failure.

You can specify an existing redo log file group in one of these ways:

GROUP parameter	You can specify the value of the GROUP parameter that identifies the redo log file group.

list of  filenames	You can list all members of the redo log file group. You must fully specify each filename according to the conventions for your operating system.

DROP LOGFILE	drops all members of a redo log file group. You can specify a redo log file group in the same manners as the ADD LOGFILE MEMBER clause. You cannot drop a redo log file group if all of its members have been lost through media failure.

DROP LOGFILE MEMBER	drops one or more redo log file members. Each 'filename' must fully specify a member using the conventions for filenames on your operating system.

You cannot use this clause to drop all members of a redo log file group that contain valid data. To perform this operation, use the DROP LOGFILE clause.

RENAME FILE	renames data files or redo log file members. This clause only renames files in the control file, it does not actually rename them on your

BACKUP CONTROLFILE	backs up the current control file.

'filename'	specifes the file to which the control file is backed up. You must fully specify the 'filename' using the conventions for your operating system. If the specified file already exists, you must specify the REUSE option.

TRACE	writes SQL statements that recreate the current control file to the database's trace file. You can use the trace file output as a SQL script for recovery if all copies of the control file are lost. The RESETLOGS and NORESETLOGS options specify how the resulting SQL script opens the database.

CREATE DATAFILE	creates a new data file in place of an old one. You can use this option to recreate a data file that was lost with no backup. The 'filename' must identify a file that is or was once part of the database. The filespec specifies the name and size of the new data file. If you omit the AS clause, ORACLE creates the new file with the same name and size as the file specified by 'filename'.

ORACLE creates the new file in the same state as the old file when it was created. You must perform media recovery on the new file to return it to the state of the old file at the time it was lost.

You cannot create a new file based on the first data file of the SYSTEM tablespace unless the database was created in archivelog mode.

DATAFILE	takes a data file online or offline. If any other instance has the database open, your instance must also have the database open:

ONLINE	brings the data file online.

OFFLINE	takes the data file offline.

DROP	takes a data file offline when the database is in noarchivelog mode.

You can only use the following options when your instance has the database open:

ENABLE	enables the specified thread of redo log file groups. The thread must have at least two redo log file groups before you can enable it.

PUBLIC	makes the enabled thread available to any instance that does not explicitly request a specific thread with the initialization parameter THREAD.

If you omit the PUBLIC option, the thread is only available to the instance that explicitly requests it with the initialization parameter THREAD.

DISABLE	disables the specified thread, making it unavailable to all instances. You cannot disable a thread if an instance using it has the database mounted.

RENAME GLOBAL_NAME	changes the global name of the database. The database is the new database name and can be as long as eight bytes. The optional domains specifies where the database is effectively located in the network hierarchy. Renaming your database automatically clears all data from the shared pool in the SGA. However, renaming your database does not change global references to your database from existing database links, synonyms, and stored procedures and functions on remote databases. Changing such references is the responsibility of the administrator of the remote databases.

For more information on global names, see Chapter 20 "Distributed Databases" of the ORACLE7 Server Concepts Manual.

SET	changes one of the following for your database:

DBMAC	changes the mode in which Trusted ORACLE is configured:

ON	configures Trusted ORACLE in DBMS MAC mode.

OFF	configures Trusted ORACLE in OS MAC mode.

DBHIGH	equates the predefined label DBHIGH to the operating system label specified by 'text'.

DBLOW	equates the predefined label DBLOW to the operating system label specified by 'text'.

You must specify labels in the default label format for your session. Changes made by this option take effect when you next start your instance. You can only use this clause if you are using Trusted ORACLE.  For more information on this clause, see the Trusted ORACLE7 Server Administrator's Guide.

Usage Notes

For more information on using the ALTER DATABASE commandfor database maintenance, see Chapter 3  of the ORACLE7 Server Administrator's Guide.

Example I	This statement mounts the database named STOCKS exclusively:

ALTER DATABASE stocks

MOUNT EXCLUSIVE

Example II	This statement adds a redo log file group with two members and identifies it with a GROUP parameter value of 3:

ALTER DATABASE stocks

ADD LOGFILE GROUP 3 ('diska:log3.log' , 'diskb:log3.log') SIZE 50K

Example III	This statement adds a member to the redo log file group added in the previous example:

ALTER DATABASE stocks

ADD LOGFILE MEMBER 'diskc:log3.log'

TO GROUP 3

Example IV	This statement drops the redo log file member added in the previous example:

ALTER DATABASE stocks

 	DROP LOGFILE MEMBER 'diskc:log3.log'

Example V	This statement renames a redo log file member:

ALTER DATABASE stocks 	RENAME FILE 'diskb:log3.log' TO 'diskd:log3.log'

This statement only changes the member of the redo log group from one file to another. This statement does not actually change the name of the file 'DISKB:LOG3.LOG' to 'DISKD:LOG3.LOG'. You must perform this operation through your operating system.

Example VI	This statement drops all members of the redo log file group 3:

ALTER DATABASE stocks DROP LOGFILE GROUP 3

Example VII	This statement adds a redo log file group containing three members to thread 5 and assigns it a GROUP parameter value of 4:

ALTER DATABASE stocks

ADD LOGFILE THREAD 5 GROUP 4 ('diska:log4.log',

     'diskb:log4:log', 	      	       'diskc:log4.log' )

Example VIII	This statement disables thread 5:

ALTER DATABASE stocks

DISABLE THREAD 5

Example IX	This statement enables thread 5, making it available to any ORACLE instance that does not explicitly request a specific thread:

ALTER DATABASE stocks

ENABLE PUBLIC THREAD 5

Example X	This statement creates the data file 'DISKX:DB1.DAT' based on the file 'DISKY:DB1.DAT':

ALTER DATABASE

CREATE DATAFILE 'diskx:db1.dat' AS 'disky:db1.dat'

Example XI	This statement changes the global name of the database and includes both the database name and domain:

ALTER DATABASE

RENAME GLOBAL_NAME TO sales.australia.acme.com

For examples of performing media recovery, see the RECOVER clause on page 7 - 313.

Related Topics

CREATE DATABASE command; RECOVER, STARTUP, and SHUTDOWN SQL*DBA commands in the ORACLE7 Server Utilities User's Guide.

________________________________________

ALTER FUNCTION

Purpose

To recompile a stand-alone stored function.

Prerequisites

The function must be in your own schema or you must have ALTER ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the function's creation label or you must satisfy one of these criteria:

•	If the function's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the function's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the function's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the function. If you omit schema, ORACLE assumes the function is in your own schema.

function	is the name of the function to be recompiled.

COMPILE	causes ORACLE to recompile the function. The COMPILE keyword is required.

Usage Notes

 You can use the ALTER FUNCTION command to explicitly recompile a functionthat is invalid. Explicit recompilation eliminates the need for implicitruntime recompilation and prevents associated runtime compilation errors and performance overhead.

The ALTER FUNCTION command is similar to the ALTER PROCEDURE command. For more information on these commands, see the ALTER PROCEDURE command later in this chapter. For information on how

 ORACLE recompiles functions and procedures, see Chapter 16 "Dependencies Among Schema Objects" of the ORACLE7 Server Concepts Manual.

Note: This command does not change the declaration or definition of an existing function. To redeclare or redefine a function, you must use the CREATE FUNCTION command with the OR REPLACE option.

Example	To explicitly recompile the function GET_BAL owned by the user MERRIWEATHER, issue this statement:

ALTER FUNCTION merriweather.get_bal

 	COMPILE

If ORACLE encounters no compilation errors while recompiling GET_BAL, GET_BAL becomes valid. ORACLE can subsequently execute it without recompiling it at runtime. If recompiling GET_BAL results in compilation errors, ORACLE returns an error message and GET_BAL remains invalid.

ORACLE also invalidates all objects that depend upon GET_BAL. If you subsequently reference one of these objects without explicitly recompiling it first, ORACLE recompiles it implicitly at runtime.

Related Topics

ALTER PROCEDURE and CREATE FUNCTION commands.

________________________________________

ALTER INDEX

Purpose

To change future storage allocation for data blocks in an index.

Prerequisites

The index must be in your own schema or you must have ALTER ANY INDEX system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the index's creation label or you must satisfy one of these criteria:

•	If the index's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the index's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the index's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the index. If you omit schema, ORACLE assumes the index is in your own schema.

STORAGE	is the name of the index to be altered.

INITRANS MAXTRANS	changes the values of these parameters for the index. See the INITRANS and MAXTRANS parameters of the CREATE TABLE command later in this chapter.

STORAGE	changes the storage parameters for the index. See the STORAGE clause on page 8 - 371.

Usage Notes

 The INITRANS and MAXTRANS parameters and the STORAGE clause all havethe same function as in the CREATE TABLE command.

Example	This statement alters SCOTT'S CUSTOMER index so that future data blocks within this index use 5 initial transaction entries and an incremental extent of 100 kilobytes:

ALTER INDEX scott.customer

INITRANS 5

STORAGE (NEXT 100K)

Related Topics

CREATE INDEX and CREATE TABLE commands; STORAGE clause.

________________________________________

ALTER PACKAGE

Purpose

To recompile a stored package.

Prerequisites

The package must be in your own schema or you must have ALTER ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the package's creation label or you must satisfy one of these criteria:

•	If the package's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the package's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the package's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the package. If you omit schema, ORACLE assumes the package is in your own schema.

 package	is the name of the package to be recompiled.

COMPILE	recompiles the package specification or body. The COMPILE keyword is required.

PACKAGE	recompiles the package body and specification.

BODY	recompiles only the package body.

The default option is PACKAGE.

Usage Notes

You can use the ALTER PACKAGE command to explicitly recompile eithera package specification and body or only a package body. Explicitrecompilation eliminates the need for implicit runtime recompilation and prevents associated runtime compilation errors and performance overhead.

Because all objects in a package are stored as a unit, the ALTER PACKAGE command recompiles all package objects together. You cannot use the ALTER PROCEDURE or ALTER FUNCTION command to individually recompile a procedure or function that is part of a package.

Note: This command does not change the declaration or definition of an existing package. To redeclare or redefine a package, you must use the CREATE PACKAGE or the CREATE PACKAGE BODY command with the OR REPLACE option.

 Recompiling Package Specifications

You might want to recompile a package specification to check for compilation errors after modifying the specification. When you issue an ALTER PACKAGE statement with the COMPILE PACKAGE option, ORACLE recompiles the package specification and body regardless of whether it is invalid. When you recompile a package specification, ORACLE invalidates any local objects that depend on the specification, such as procedures that call procedures or functions in the package. Note that the body of a package also depends on its specification. If you subsequently reference one of these dependent objects without first explicitly recompiling it, ORACLE recompiles it implicitly at runtime.

 Recompiling Package Bodies

You might want to recompile a package body after modifying it. When you issue an ALTER PACKAGE statement with the COMPILE BODY option, ORACLE recompiles the package body regardless of whether it is invalid. When you recompile a package body, ORACLE first recompiles the objects on which the body depends, if any of these objects are invalid. If ORACLE recompiles the body successfully, the body becomes valid. If recompiling the body results in compilation errors, ORACLE returns an error and the body remains invalid. You can then debug the body using the predefined package DBMS_OUTPUT. Note that recompiling a package body does not invalidate objects that depend upon the package specification.

For more information on debugging packages, see Chapter 7 "Using Procedures and Packages" of the ORACLE7 Server Application Developer's Guide. For information on how ORACLE maintains dependencies among schema objects, including remote objects, see Chapter 16 "Dependencies Among Schema Objects" of the ORACLE7 Server Concepts Manual.

Example I	This statement explicitly recompiles the specification and body of the ACCOUNTING package in the schema BLAIR:

ALTER PACKAGE blair.accounting

COMPILE PACKAGE

If ORACLE encounters no compilation errors while recompiling the ACCOUNTING specification and body, ACCOUNTING becomes valid. BLAIR can subsequently call or reference all package objects declared in the specification of ACCOUNTING without runtime recompilation. If recompiling ACCOUNTING results in compilation errors, ORACLE returns an error message and ACCOUNTING remains invalid.

ORACLE also invalidates all objects that depend upon ACCOUNTING. If you subsequently reference one of these objects without explicitly recompiling it first, ORACLE recompiles it implicitly at runtime.

Example II	To recompile the body of the ACCOUNTING package in the schema BLAIR, issue this statement:

ALTER PACKAGE blair.accounting

COMPILE BODY

If ORACLE encounters no compilation errors while recompiling the package body, the body becomes valid. BLAIR can subsequently call or reference all package objects declared in the specification of ACCOUNTING without runtime recompilation. If recompiling the body results in compilation errors, ORACLE returns an error message and the body remains invalid.

Because this statement recompiles the body and not the specification of ACCOUNTING, ORACLE does not invalidate dependent objects.

Related Topics

CREATE PACKAGE and CREATE PACKAGE BODY commands.

________________________________________

ALTER PROCEDURE

Purpose

To recompile a stand-alone stored procedure.

Prerequisites

The procedure must be in your own schema or you must have ALTER ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the procedure's creation label or you must satisfy one of these criteria:

•	If the procedure's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the procedure's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the procedure's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the procedure. If you omit schema, ORACLE assumes the procedure is in your own schema.

procedure	is the name of the procedure to be recompiled.

COMPILE	causes ORACLE to recompile the procedure. The COMPILE keyword is required.

Usage Notes

The ALTER PROCEDURE command and the ALTER FUNCTION command are quitesimilar. The following discussion of explicitly recompiling proceduresalso applies to functions.

You can use the ALTER PROCEDURE command to explicitly recompile a procedure that is invalid. Explicit recompilation eliminates the need for implicit runtime recompilation and prevents associated runtime compilation errors and performance overhead.

When you issue an ALTER PROCEDURE statement, ORACLE recompiles the procedure regardless of whether it is valid or invalid.

You can only use the ALTER PROCEDURE command to recompile a stand-alone procedure. To recompile a procedure that is part of a package, you must recompile the entire package using the ALTER PACKAGE command.

When you recompile a procedure, ORACLE first recompiles objects upon which the procedure depends, if any of these objects are invalid. ORACLE also invalidates any local objects that depend upon the procedure, such as procedures that call the recompiled procedure or package bodies that define procedures that call the recompiled procedure. If ORACLE recompiles the procedure successfully, the procedure becomes valid. If recompiling the procedure results in compilation errors, then ORACLE returns an error and the procedure remains invalid. You can then debug procedures using the predefined package DBMS_OUTPUT. For information on debugging procedures, see Chapter 7 "Using Procedures and Packages"  of the ORACLE7 Server Application Developer's Guide. For information on how ORACLE maintains dependencies among schema objects, including remote objects, see Chapter 16 "Dependencies Among Schema Objects" of the ORACLE7 Server Concepts Manual.

Note: This command does not change the declaration or definition of an existing procedure. To redeclare or redefine a procedure, you must use the CREATE PROCEDURE command with the OR REPLACE option.

Example	To explicitly recompile the procedure CLOSE_ACCT owned by the user HENRY, issue this statement:

ALTER PROCEDURE henry.close_acct

COMPILE

If ORACLE encounters no compilation errors while recompiling CLOSE_ACCT, CLOSE_ACCT becomes valid. ORACLE can subsequently execute it without recompiling it at runtime. If recompiling CLOSE_ACCT results in compilation errors, ORACLE returns an error and CLOSE_ACCT remains invalid.

ORACLE also invalidates all dependent objects. These objects include any procedures, functions, and package bodies that call CLOSE_ACCT. If you subsequently reference one of these objects without first explicitly recompiling it, ORACLE recompiles it implicitly at runtime.

Related Topics

ALTER FUNCTION, ALTER PACKAGE, and CREATE PROCEDURE command.

________________________________________

ALTER PROFILE

Purpose

To add, modify, or remove a resource limit in a profile.

Prerequisites

You must have ALTER PROFILE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the profile's creation label or you must satisfy one of these criteria:

•	If the profile's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the profile's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the profile's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

profile	is the name of the profile to be altered.

integer 	defines a new limit for a resource in this profile. For information on resource limits, see the CREATE PROFILE command later in this chapter.

UNLIMITED	specifies that this profile allows unlimited use of the resource.

DEFAULT	removes a resource limit from the profile. Any user assigned the profile is subject to the limit on the resource defined in the DEFAULT profile in their subsequent sessions.

Usage Notes

Changes made to a profile with an ALTER PROFILE statement only affectusers in their subsequent sessions, not in their current sessions.

You cannot remove a limit from the DEFAULT profile.

Example I	This statement defines a new limit of 5 concurrent sessions for the ENGINEER profile:

ALTER PROFILE engineer  LIMIT  SESSIONS_PER_USER  5

If the ENGINEER profile does not currently define a limit for SESSIONS_PER_USER, this statement adds the limit of 5 to the profile. If the profile already defines a limit, this statement redefines it to 5. Any user assigned the ENGINEER profile is subsequently limited to 5 concurrent sessions.

Example II	This statement defines unlimited idle time for the ENGINEER profile:

ALTER PROFILE engineer  LIMIT  IDLE_TIME  UNLIMITED

Any user assigned the ENGINEER profile is subsequently permitted unlimited idle time.

Example III	This statement removes the IDLE_TIME limit from the ENGINEER profile:

ALTER PROFILE engineer  LIMIT  IDLE_TIME  DEFAULT

Any user assigned the ENGINEER profile is subject to the IDLE_TIME limit defined in the DEFAULT profile in their subsequent sessions.

Example IV	This statement defines a limit of 2 minutes of idle time for the DEFAULT profile:

ALTER PROFILE default  LIMIT  IDLE_TIME  2

This IDLE_TIME limit applies to these users:

•	users who are not explicitly assigned any profile

•	users who are explicitly assigned a profile that does not define an IDLE_TIME limit

Related Topics

CREATE PROFILE command.

________________________________________

ALTER RESOURCE COST

Purpose

To specify a formula to calculate the total resource cost used in a session. For any session, this cost is limited by the value of the COMPOSITE_LIMIT parameter in the user's profile.

Prerequisites

You must have ALTER RESOURCE COST system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match DBLOW or you must have WRITEDOWN system privileges.

Syntax

Keywords and Parameters

integer	is the weight of each resource.

Usage Notes

The ALTER RESOURCE COST command specifies the formula by which ORACLE calculates the total resource cost used in a session. With this command,you can assign a weight to each of these resources:

CPU_PER_

SESSION	The amount of CPU time used by a session measured in hundredths of seconds.

CONNECT_

TIME	The amount of CPU time used by a session measured in hundredths of seconds.

CPU_PER_

SESSION	 The elapsed time of a session measured in minutes.

LOGICAL_

READS_PER_

SESSION	 The number of data blocks read during a session, including blocks read from both memory and disk.

PRIVATE_SGA	 The number of bytes of private space in the System Global Area (SGA) used by a session. This limit only applies if you are using the multi-threaded server architecture and allocating private space in the SGA for your session.

ORACLE calculates the total resource cost by multiplying the amount of each resource used in the session by the resource's weight and summing the products for all four resources. Both the products and the total cost are expressed in units called service units.

Although ORACLE monitors the use of other resources, only these four can contribute to the total resource cost for a session. For information on all resources, see the CREATE PROFILE command later in this chapter.

The weight that you assign to each resource determines how much the use of that resource contributes to the total resource cost. Using a resource with a lower weight contributes less to the cost than using a resource with a higher weight. If you do not assign a weight to a resource, the weight defaults to 0 and use of the resource subsequently does not contribute to the cost. The weights you assign apply to all subsequent sessions in the database.

Once you have specified a formula for the total resource cost, you can limit this cost for a session with the COMPOSITE_LIMIT parameter of the CREATE PROFILE command. If a session's cost exceeds the limit, ORACLE aborts the session and returns an error. For information on establishing resource limits, see the CREATE PROFILE command later in this chapter. If you use the ALTER RESOURCE COST command to change the weight assigned to each resource, ORACLE uses these new weights to calculate the total resource cost for all current and subsequent sessions.

Example	This statement assigns weights to the resources CPU_PER_SESSION and CONNECT_TIME:

ALTER RESOURCE COST

CPU_PER_SESSION 100

 	CONNECT_TIME      1

The weights establish this cost formula for a session:

T = (100 * CPU) + CON

where:

T	is the total resource cost for the session expressed in service units.

CPU	is the CPU time used by the session measured in hundredths of seconds.

CON	is the elapsed time of a session measured in minutes.

Because this statement assigns no weight to the resources LOGICAL_READS_PER_SESSION and PRIVATE_SGA, these resources do not appear in the formula.

If a user is assigned a profile with a COMPOSITE_LIMIT value of 500, a session exceeds this limit whenever T exceeds 500. For example, a session using .04 seconds of CPU time and 101 minutes of elapsed time exceeds the limit. A session .0301 seconds of CPU time and 200 minutes of elapsed time also exceeds the limit.

You can subsequently change the weights with another ALTER RESOURCE statement:

ALTER RESOURCE COST

LOGICAL_READS_PER_SESSION 2

CONNECT_TIME              0

These new weights establish a new cost formula:

T = (100 * CPU) + (2 * LOG)

where:

T CPU	are the same as in the previous formula.

LOG	is the number of data blocks read during the session.

This ALTER RESOURCE COST statement changes the formula in these ways:

•	Because the statement assigns a weight to the LOGICAL_READS_PER_SESSION resource, this resource now appears in the formula.

•	Because the statement assigns a weight of 0 to the CONNECT_TIME resource, this resource no longer appears in the formula.

•	Because the statement omits a weight for the CPU_PER_SESSION resource and the resource was already assigned a weight, the resource remains in the formula with its original weight.

•	Because the statement omits a weight for the PRIVATE_SGA resource and the resource was not already assigned a weight, the resource still does not appear in the formula.

Related Topics

CREATE PROFILE command.

________________________________________

ALTER ROLE

Purpose

To change the authorization needed to enable a role.

Prerequisites

You must either have been granted the role with the ADMIN OPTION or have ALTER ANY ROLE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the role's creation label or you must satisfy one of these criteria:

•	If the role's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the role's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the role's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

The keywords and parameters in the ALTER ROLE command all have the same meaning as in the CREATE ROLE command. For information on these keywords and parameters, see the CREATE ROLE command later in this chapter.

Example	This statement changes the password on the TELLER role to LETTER:

ALTER ROLE teller

IDENTIFIED BY letter

Users granted the TELLER role must subsequently specify the new password to enable the role.

Related Topics

CREATE ROLE and SET ROLE commands.

________________________________________

ALTER ROLLBACK SEGMENT

Purpose

To alter a rollback segment in one of these ways:

•	by bringing it online

•	by taking it offline

•	by changing its storage characteristics

Prerequisites

You must have ALTER ROLLBACK SEGMENT system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the rollback segment's creation label or you must satisfy one of these criteria:

•	If the rollback segment's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the rollback segment's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the rollback segment's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

rollback_segment	specifies the name of an existing rollback segment.

ONLINE	brings the rollback segment online.

OFFLINE	takes the rollback segment offline.

STORAGE	changes the rollback segment's storage characteristics. See the STORAGE clause on page 8 - 371.

Usage Notes

When you create a rollback segment, it is initially offline. An offline rollback segment is not available for transactions.

The ONLINE option brings the rollback segment online making it available for transactions by your instance. You can also bring a rollback segment online when you start your instance with the initialization parameter ROLLBACK_SEGMENTS.

The OFFLINE option takes the rollback segment offline. If the rollback segment does not contain information necessary to rollback any active transactions, ORACLE takes it offline immediately. If the rollback segment does contain information for active transactions, ORACLE makes the rollback segment unavailable for future transactions and takes it offline after all the active transactions are committed or rolled back. Once the rollback segment is offline, it can be brought online by any instance.

You cannot take the SYSTEM rollback segment offline.

You can tell whether a rollback segment is online or offline by querying the data dictionary view DBA_ROLLBACK_SEGS. Online rollback segments are indicated by a STATUS value of 'IN_USE'. Offline rollback segments are indicated by a STATUS value of 'AVAILABLE'.

For more information on making rollback segments available and unavailable, see Chapter 9  of the ORACLE7 Server Administrator's Guide.

The STORAGE clause of the ALTER ROLLBACK SEGMENT command affects future space allocation in the rollback segment. You cannot change the values of the INITIAL and MINEXTENTS for an existing rollback segment.

Example I	This statement brings the rollback segment RSONE online:

ALTER ROLLBACK SEGMENT rsone ONLINE

Example II	This statement changes the STORAGE parameters for RSONE:

ALTER ROLLBACK SEGMENT rsone

STORAGE (NEXT 1000  MAXEXTENTS 20)

Related Topics

CREATE ROLLBACK SEGMENT, and CREATE TABLESPACE commands; STORAGE clause.

________________________________________

ALTER SEQUENCE

Purpose

To change the sequence in one of these ways:

•	changing the increment between future sequence values

•	setting or eliminating the minimum or maximum value

•	changing the number of cached sequence numbers

•	specifying whether or not sequence numbers must be ordered

Prerequisites

The sequence must be in your own schema or you must have ALTER privilege on the sequence or you must have ALTER ANY SEQUENCE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the sequence's creation label or you must satisfy one of these criteria:

•	If the sequence's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the sequence's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the sequence's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

The keywords and parameters in this command serve the same purpose that they do in the CREATE SEQUENCE command. See the description of this command later in this chapter.

Usage Notes

The sequence must be dropped and recreated in order to restart the sequence at a different number. Only future sequence numbers are affected by the ALTER SEQUENCE command.

Some validations are performed. For example, a new MAXVALUE cannot be imposed that is less than the current sequence number.

Example I	This statement sets a new maximum value for the ESEQ sequence:

ALTER SEQUENCE eseq

MAXVALUE 1500

Example II	This statement turns on CYCLE and CACHE for the ESEQ sequence:

ALTER SEQUENCE eseq

CYCLE

 	CACHE 5

Related Topics

CREATE SEQUENCE and DROP SEQUENCE commands.

________________________________________

ALTER SESSION

Purpose

To alter your current session in one of these ways:

•	to enable or disable the SQL trace facility

•	to enable or disable global name resolution

•	to change the values of NLS parameters

•	to change your DBMS session label in Trusted ORACLE

•	to change the default label format for your session

•	to close a database link

•	to send advice to remote databases for forcing an in-doubt distributed transaction

•	to permit or prohibit procedures and stored functions from issuing COMMIT and ROLLBACK statements

•	to change the goal of the cost-based optimization approach

Prerequisites

To enable and disable the SQL trace facility or to change the default label format, you must have ALTER SESSION system privilege.

To raise your session label, you must have WRITEUP and READUP system privileges. To lower your session label, you must have WRITEDOWN system privilege. To change your session label laterally, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

To perform the other operations of this command, you do not need any privileges.

Syntax

Keywords and Parameters

SQL_TRACE	controls the SQL trace facility for your session:

TRUE	enables the SQL trace facility.

FALSE	disables the SQL trace facility.

GLOBAL_

NAMES	controls the enforcement of global name resolution for your session:

TRUE	enables the enforcement of global name resolution.

FALSE	disables the enforcement of global name resolution.

For information on enabling and disabling global name resolution with this parameter, see the ALTER SYSTEM command later in this chapter.

NLS_

LANGUAGE	changes the language in which ORACLE returns errors and other messages. This parameter also implicitly specifies new values for these items:

•	language for day and month names and abbreviations and spelled values of other date format elements

•	sort sequence

NLS_TERRITORY	implicitly specifies new values for these items:

•	default date format

•	decimal character and group separator

•	local currency symbol

•	ISO currency symbol

•	first day of the week for D date format element

NLS_DATE_

FORMAT	explicitly specifies a new default date format. The 'fmt' value must be a date format model as specified in the section "Date Format  on page NO TAG.

NLS_DATE_

LANGUAGE	explicitly changes the language for day and month names and abbreviations and spelled values of other date format elements.

NLS_NUMERIC_CHARACTERS	explicitly specifies a new decimal character and group separator. The 'text' value must have this form:

'dg'

where:

d	is the new decimal character.

g	is the new group separator.

The decimal character and the group separator must be different and can only be single-byte characters.

NLS_ISO_

CURRENCY	explicitly specifies the territory whose ISO currency symbol should be used.

NLS_CURRENCY	explicitly specifies a new local currency symbol.

NLS_SORT	changes the sequence into which ORACLE sorts character values.

sort	specifies the name of a linguistic sort sequence.

BINARY	specifies a binary sort.

LABEL	changes your DBMS session label to either:

•	the label specified by 'text' in your session's default label format

•	the label equivalent to DBHIGH

•	the label equivalent to DBLOW

•	your operating system label using OSLABEL

MLS_LABEL_

FORMAT	changes the default label format for your session. For more information on these parameters, see the Trusted ORACLE7 Server Administrator's Guide.

OPTIMIZER_

GOAL	specifies the approach and goal of the optimizer for your session:

RULE	specifies the rule-based approach.

ALL_ROWS	specifies the cost-based approach and optimizes for best throughput.

FIRST_ROWS	specifies the cost-based approach and optimizes for best response time.

CHOOSE	causes the optimizer to choose an optimization approach based on the presence of statistics in the data dictionary.

CLOSE DATABASE LINK	closes the database link dblink, eliminating your session's connection to the remote database. The database link cannot be currently in use by an active transaction or an open cursor.

ADVISE	sends advice for forcing a distributed transaction to a remote database. This advice appears on the remote database in the ADVICE column of the DBA_2PC_PENDING data dictionary view in the event the distributed transaction becomes in-doubt. The following are advice options:

COMMIT	places the value 'C' in DBA_2PC_PENDING.ADVICE.

ROLLBACK	places the value 'R' in DBA_2PC_PENDING.ADVICE.

NOTHING	places the value ' ' in DBA_2PC_PENDING.ADVICE.

COMMIT IN PROCEDURE	specifies whether procedures and stored functions can issue COMMIT and ROLLBACK statements:

ENABLE	permits procedures and stored functions to issue these statements.

DISABLE	prohibits procedures and stored functions from issuing these statements.

Enabling and Disabling the SQL Trace Facility

The SQL trace facility generates performance statistics for the processingof SQL statements. You can enable and disable the SQL trace facilityfor all sessions on an ORACLE instance with the initialization parameter SQL_TRACE. When you begin a session, ORACLE enables or disables the SQL trace facility based on the value of this parameter. You can subsequently enable or disable the SQL trace facility for your session with the SQL_TRACE option of the ALTER SESSION command.

For more information on the SQL trace facility, including how to format and interpret its output, see Appendix B  of the ORACLE7 Server Application Developer's Guide.

Example I	To enable the SQL trace facility for your session, issue this statement:

ALTER SESSION

SET SQL_TRACE = TRUE

Using NLS Parameters

ORACLE contains support for use in different nations and with different languages. When you start an instance, ORACLE establishes support for a language and certain language- and territory-dependent items based on the values of initialization parameters that begin with "NLS".

For information on these parameters, see Appendix C "National Language Support"of the ORACLE7 Server Administrator's Guide.  You can use the NLS parameters of the ALTER SESSION command to change these items dynamically for your session. You can query the dynamic performance table V$NLS_PARAMETERS to see the current NLS attributes for your session.

 Language for Error Messages

You can specify a new language for error messages with the NLS_LANGUAGE parameter.

Note that this parameter also implicitly changes other language-related items. ORACLE provides error messages in a wide range of languages on many platforms.

Example II	This statement changes the language for error messages to French:

ALTER SESSION

SET NLS_LANGUAGE = French

ORACLE returns error messages in French:

SELECT * FROM empp

ORA-00942:  Table ou vue n'existe pas

 Default Date Format

You can specify a new default date format either explicitly with the NLS_DATE_FORMAT parameter or implicitly with the NLS_TERRITORY parameter. For information on the default date format models, see the section "Date  on page NO TAG.

Example III	This statement dynamically changes the default date format for your session to 'YYYY MM DD-HH24:MI:SS':

ALTER SYSTEM

SET NLS_DATE_FORMAT = 'YYYY MM DD HH24:MI:SS'

ORACLE uses the new default date format:

SELECT TO_CHAR(SYSDATE) Today

 	FROM DUAL

TODAY

-------------------

1993 08 12 14:25:56

 Language for Months and Days

You can specify a new language for names and abbreviations of months and days either explicitly with the NLS_DATE_LANGUAGE parameter or implicitly with the NLS_LANGUAGE parameter.

Example IV	This statement changes the language for date format elements to French:

ALTER SESSION

SET NLS_DATE_LANGUAGE = French

ORACLE returns values for date format elements in French:

SELECT TO_CHAR(SYSDATE, 'Day DD Month YYYY') Today

 	FROM DUAL

TODAY

---------------------------

Mardi     28 Fé vrier   1992

 Decimal Character and Group Separator

You can specify new values for these number format elements either explicitly with the  NLS_NUMERIC_CHARACTERS parameter or implicitly with the NLS_TERRITORY parameter:

D (decimal character)	is the character that separates the integer and decimal portions of a number.

G (group separator)	is the character that separates groups of digits in the integer portion of a number.

For information on how to use number format models, see the section "Number Format Models" on page NO TAG.

The decimal character and the group separator can only be single-byte characters and cannot be the same character. If the decimal character is not a period (.), you must use single quotes to enclose all number values that appear in expressions in your SQL statements.

Example V	This statement dynamically changes the decimal character to ',' and the group separator to '.':

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ',.'

ORACLE returns these new characters when you use their number format elements:

SELECT TO_CHAR( SUM(sal), 'L999G999D99') Total FROM emp

TOTAL

-------------

   FF29.025,00

 ISO Currency Symbol

You can specify a new value for the C number format element, the ISO currency symbol, either explicitly with the NLS_ISO_CURRENCY parameter or implicitly with the NLS_TERRITORY parameter. The value that you specify for these parameters is a territory whose ISO currency symbol becomes the value of the C number format element.

Example VI	This statement dynamically changes the ISO currency symbol to the ISO currency symbol for the territory America:

ALTER SESSION

 	SET NLS_ISO_CURRENCY = America

ORACLE uses the ISO currency symbol defined for America:

SELECT TO_CHAR( SUM(sal), 'L999G999D99') Total

 	FROM emp

TOTAL

-------------

 USD29,025.00

 Local Currency Symbol

You can specify a new value for the L number format element, called the local currency symbol, either explicitly with the NLS_CURRENCY parameter or implicitly with the NLS_TERRITORY parameter.

Example VII	This statement dynamically changes the local currency symbol to 'DM':

ALTER SESSION

 	SET NLS_CURRENCY = 'DM'

ORACLE returns the new local currency symbol when you use the L number format element:

SELECT TO_CHAR( SUM(sal), 'L999G999D99') Total

 	FROM emp

TOTAL

-------------

   DM29.025,00

 Linguistic Sort Sequence

You can specify a new linguistic sort sequence or a binary sort either explicitly with the NLS_SORT parameter or implicitly with the NLS_LANGUAGE parameter.

Example VIII	This statement dynamically changes the linguistic sort sequence to Spanish:

ALTER SESSION

 	SET NLS_SORT = XSpanish

ORACLE sorts character values based on their position in the Spanish linguistic sort sequence.

Changing the Optimization Approach and Goal

The ORACLE optimizer can use either of these approaches to optimize a SQL statement:

rule-based 	The optimizer optimizes a SQL statement based on the indexes and clusters associated with the accessed tables, the syntactic constructs of the statement, and a heuristically-ranked list of these constructs.

cost-based	The optimizer optimizes a SQL statement by considering statistics describing the tables, indexes, and clusters accessed by the statement as well as the information considered with the rule-based approach.

With the cost-based approach, the optimizer can optimize a SQL statement with one of these goals:

best throughput 	or the minimal time necessary to return all rows accessed by the statement

best response time	or the minimal time necessary to return the first row accessed by the statement

When you start your instance, the optimization approach is established by the initialization parameter OPTIMIZER_MODE. If this parameter establishes the cost-based approach, the default goal is best throughput. You can subsequently change the optimization approach or the goal of the cost-based optimization approach for your session with the OPTIMIZER_GOAL parameter.

Example XI	This statement changes the goal of the cost-based approach to best response time:

ALTER SESSION

 	SET OPTIMIZER_GOAL = FIRST_ROWS

For information on how to choose a goal for the cost-based approach based on the characteristics of your application, see Chapter 5 "Tuning SQL Statements" of the ORACLE7 Server Application Developer's Guide.

Closing Database Links

A database link allows you to access a remote database in DELETE, INSERT, LOCK TABLE, SELECT, and UPDATE statements. When you issue a statement that uses a database link, ORACLE creates a session for you on the remote database using the database link. The connection remains open until you end your local session or until the number of database links for your session exceeds the value of the initialization parameter OPEN_LINKS.

You can use the CLOSE DATABASE LINK clause of the ALTER SESSION command to explicitly close a database link if you do not plan to use it again in your session. You may want to explicitly close a database link if the network overhead associated with leaving it open is costly. Before closing a database link, you must first close all cursors that use the link and then end your current transaction if it uses the link.

Example IX	This example updates the employee table on the SALES database using a database link, commits the transaction, and explicitly closes the database link:

UPDATE emp@sales

SET sal = sal + 200

 	WHERE empno = 9001

COMMIT

ALTER SESSION

 	CLOSE DATABASE LINK sales

Offering Advice for Forcing In-doubt Distributed Transactions

In the event of a network or machine failure during the commit process for a distributed transaction, the state of the transaction may be unknown, or in-doubt. The transaction can be manually committed or rolled back on each database involved in the transaction with the FORCE clause of the COMMIT or ROLLBACK commands.

Before committing a distributed transaction, you can use the ADVISE clause of the ALTER SESSION command to send advice to a remote database in the event a distributed transaction becomes in-doubt. If the transaction becomes in-doubt, the advice appears in the ADVICE column of the DBA_2PC_PENDING view on the remote database. The administrator of that database can then use this advice to decide whether to commit or roll back the transaction on the remote database. For more information on distributed transactions and how to decide whether to commit or roll back in-doubt distributed transactions, see Chapter 15 "Managing Distributed Databasess"  of the ORACLE7 Server Administrator's .

You issue multiple ALTER SESSION statements with the ADVISE clause in a single transaction. Each such statement sends advice to the databases referenced in the following statements in the transaction until another such statement is issued. This allows you to send different advice to different databases.

Example X	This transaction inserts an employee record into the EMP table on the database identified by the database link SITE1 and deletes an employee record from the EMP table on the database identified by SITE2:

ALTER SESSION

 	ADVISE COMMIT

INSERT INTO emp@site1

VALUES (8002, 'FERNANDEZ', 'ANALYST', 7566,             	TO_DATE('04-OCT-1992', 'DD-MON-YYYY'), 3000, NULL, 20)

ALTER SESSION

 	ADVISE ROLLBACK

DELETE FROM emp@site2

 	WHERE empno = 8002

COMMIT

This transaction has two ALTER SESSION statements with the ADVISE clause. If the transaction becomes in-doubt, SITE1 is sent the advice 'COMMIT' by virtue of the first ALTER SESSION statement and SITE2 is sent the advice 'ROLLBACK' by virtue of the second.

Enabling and Disabling Transaction Control in Procedures and Stored Functions

Since procedures and stored functions are written in PL/SQL, they can issue COMMIT and ROLLBACK statements. If your application performs record management that would be disrupted by a COMMIT or ROLLBACK statement not issued directly by the application itself, you may want to prevent procedures and stored functions called during your session from issuing these statements. You can do this with this statement:

ALTER SESSION DISABLE COMMIT IN PROCEDURE

If you subsequently call a procedure or a stored function that issues a COMMIT or ROLLBACK statement, ORACLE returns an error and does not commit or roll back the transaction. SQL*Forms automatically prohibits COMMIT and ROLLBACK statements in procedures and stored functions.

You can subsequently allow procedures and stored functions to issue COMMIT and ROLLBACK statements in your session by issuing this statement:

ALTER SESSION ENABLE COMMIT IN PROCEDURE

This command does not apply to database triggers. Triggers can never issue COMMIT or ROLLBACK statements.

Related Topics

Chapter 5 "Tuning SQL Statements" and Appendix B "Performance Diagnostic Tools" of the ORACLE7 Server Application Developer's Guide.

________________________________________

ALTER SNAPSHOT

Purpose

To alter a snapshot in one of these ways:

•	changing its storage characteristics

•	changing its automatic refresh mode and times

Prerequisites

The snapshot must be in your own schema or you must have ALTER ANY SNAPSHOT system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the snapshot's creation label or you must satisfy one of these criteria:

•	If the snapshot's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the snapshot's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the snapshot's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

To change the storage characteristics of the internal table that ORACLE uses to maintain the snapshot's data, you must also have the privileges to alter that table. For information on these privileges, see the ALTER TABLE command later in this chapter.

Syntax

Keywords and Parameters

schema	is the schema containing the snapshot. If you omit schema, ORACLE assumes the snapshot is in your own schema.

snapshot	is the name of the snapshot to be altered.

PCTFREE PCTUSED INITRANS MAXTRANS	change the values of these parameters for the internal table that ORACLE uses to maintain the snapshot's data.

STORAGE	changes the storage characteristics of the internal table ORACLE uses to maintain the snapshot's data.

USING INDEX	changes the value of INITRANS, MAXTRANS, and STORAGE parameters for the index ORACLE uses to maintain the snapshot's data.

For information on the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters, see the CREATE TABLE command later in this chapter. For information on the STORAGE clause, see page 8 - 371.

REFRESH	changes the mode and times for automatic refreshes:

FAST	specifies a fast refresh, or a refresh using the snapshot log associated with the master table.

COMPLETE	specifies a complete refresh, or a refresh that re-executes the snapshot's query.

FORCE	specifies a fast refresh if one is possible or complete refresh if a fast refresh is not possible. ORACLE decides whether a fast refresh is possible at refresh time.

If you omit the FAST, COMPLETE, and FORCE options, ORACLE uses FORCE by default.

START WITH	specifies a date expression for the next automatic refresh time.

NEXT	specifies a new date expression for calculating the interval between automatic refreshes.

START WITH and NEXT values must evaluate to times in the future.

Usage Notes

For more information on snapshots, including refreshing snapshots,see the CREATE SNAPSHOT command later in this chapter.

Example I	This statement changes the automatic refresh mode for the HQ_EMP to FAST:

ALTER SNAPSHOT hq_emp

 	REFRESH FAST

The next automatic refresh of the snapshot will be a fast refresh provided it is a simple snapshot and its master table has a snapshot log that was created before the snapshot was created or last refreshed.

Because the REFRESH clause does not specify START WITH or NEXT values, the refresh intervals established by the REFRESH clause when the HQ_EMP snapshot was created or last altered are still used.

Example II	This statement stores a new interval between automatic refreshes for the BRANCH_EMP snapshot:

ALTER SNAPSHOT branch_emp

 	REFRESH NEXT SYSDATE+7

Because the REFRESH clause does not specify a START WITH value, the next automatic refresh occurs at the time established by the START WITH and NEXT values specified when the BRANCH_EMP snapshot was created or last altered.

At the time of the next automatic refresh, ORACLE refreshes the snapshot, evaluates the NEXT expression SYSDATE+7 to determine the next automatic refresh time, and continues to automatically refresh the snapshot once a week.

Because the REFRESH clause does not explicitly specify a refresh mode, ORACLE continues to use the refresh mode specified by the REFRESH clause of a previous CREATE SNAPSHOT or ALTER SNAPSHOT statement.

Example III	This statement specifies a new refresh mode, next refresh time, and new interval between automatic refreshes of the SF_EMP snapshot:

ALTER SNAPSHOT sf_emp

 	REFRESH COMPLETE  START WITH TRUNC(SYSDATE+1) + 9/24  NEXT SYSDATE+7

The START WITH value establishes the next automatic refresh for the snapshot to be 9:00am tomorrow. At that point, ORACLE performs a fast refresh of the snapshot, evaluates the NEXT expression, and subsequently refreshes the snapshot every week.

Related Topics

CREATE SNAPSHOT and DROP SNAPSHOT commands.

________________________________________

ALTER SNAPSHOT LOG

Purpose

Changes the storage characteristics of a snapshot log.

Prerequisites

Since a snapshot log is simply a table, the privileges that authorize operations on it are the same as those for a table. To change its storage characteristics, you must have the privileges listed for the ALTER TABLE command later in this chapter.

Syntax

Keywords and Parameters

schema	is the schema containing the snapshot log and its master table. If you omit schema, ORACLE assumes the snapshot log is in your own schema.

table	is the name of the master table associated with the snapshot log to be altered.

PCTFREE PCTUSED INITRANS MAXTRANS	change the values of these parameters for the snapshot log. See the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters of the CREATE TABLE command later in this chapter.

STORAGE	changes the storage characteristics of the snapshot log. See the STORAGE clause on page 8 - 371.

Usage Notes

For more information on snapshot logs, see the CREATE SNAPSHOT LOGcommand later in this chapter.

Example	This statement changes the MAXEXTENTS value of a snapshot log:

ALTER SNAPSHOT LOG dept

  	STORAGE MAXEXTENTS 50

Related Topics

CREATE SNAPSHOT, CREATE SNAPSHOT LOG, and DROP SNAPSHOT LOG commands.

________________________________________

ALTER SYSTEM

Purpose

To dynamically alter your ORACLE instance in one of these ways:

•	to restrict logons to ORACLE to only those users with RESTRICTED SESSION system privilege

•	to clear all data from the shared pool in the System Global Area (SGA)

•	to explicitly perform a checkpoint

•	to verify access to data files

•	to enable or disable resource limits

•	to enable or disable global name resolution

•	to manage shared server processes or dispatcher processes for the multi-threaded server architecture

•	to explicitly switch redo log file groups

•	to dynamically change or disable limits or thresholds for concurrent usage licensing and named user licensing

•	to switch redo log file groups

•	to enable distributed recovery in a single-process environment

•	to disable distributed recovery

•	to manually archive redo log file groups or to enable or disable automatic archiving

•	to terminate a session

Prerequisites

You must have ALTER SYSTEM system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must be the equivalent of DBHIGH.

Syntax

Keywords and Parameters

You can use these options regardless of whether your instance has the database dismounted or mounted, open or closed:

ENABLE RESTRICTED SESSION	allows only users with RESTRICTED SESSION system privilege to logon to ORACLE.

DISABLE RESTRICTED SESSION	reverses the effect of the ENABLE RESTRICTED SESSION option, allowing all users with CREATE SESSION system privilege to logon to ORACLE.

FLUSH SHARED_POOL	clears all data from the shared pool in the System Global Area (SGA).

You can use these options when your instance has the database mounted, open or closed:

CHECKPOINT	performs a checkpoint.

GLOBAL	performs a checkpoint for all instances that have opened the database.

LOCAL	performs a checkpoint only for the thread of redo log file groups for your instance. You can only use this option when your instance has the database open.

If you omit both the GLOBAL and LOCAL options, ORACLE performs a global checkpoint.

CHECK DATAFILES	verifies access to online data files.

GLOBAL	verifies that all instances that have opened the database can access all online data files.

LOCAL	verifies that your instance can access all online data files.

If you omit both the GLOBAL and LOCAL options, ORACLE uses GLOBAL by default.

You can only use these parameters and options when your instance has the database open:

RESOURCE_

LIMIT	controls resource limits.

TRUE	enables resource limits.

FALSE	disables resource limits.

GLOBAL_

NAMES	controls the enforcement of global naming:

TRUE	enables the enforcement of global names.

FALSE	disables the enforcement of global names.

MTS_SERVERS	specifies a new minimum number of shared server processes.

MTS_

DISPATCHERS	specifies a new number of dispatcher processes:

protocol	is the network protocol of the dispatcher processes.

integer	is the new number of dispatcher processes of the specified protocol.

You can specify multiple MTS_DISPATCHERS parameters in a single command for multiple network protocols.

LICENSE_MAX_

SESSIONS	limits the number of sessions on your instance. A value of 0 disables the limit.

LICENSE_

SESSIONS_

WARNING	establishes a threshold of sessions over which ORACLE writes warning messages to the ALERT file for subsequent sessions. A value of 0 disables the warning threshold.

LICENSE_MAX_USERS	limits the number of users on your database. A value of 0 disables the limit.

SWITCH LOGFILE	switches redo log file groups.

ENABLE DISTRIBUTED RECOVERY	enables distributed recovery. In a single-process environment, you must use this option to initiate distributed recovery.

DISABLE DISTRIBUTED RECOVERY	disables distributed recovery.

ARCHIVE LOG	manually archives redo log files or enables or disables automatic archiving. See the ARCHIVE LOG clause on page 4 - 92.

KILL SESSION	terminates a session. You must identify the session with both of these values from the V$SESSION:

integer1	is the value of the SID column.

integer2	is the value of the SERIAL# column.

Restricting Logons

By default, any user granted CREATE SESSION system privilege can log on to ORACLE. The ENABLE RESTRICTED SESSION option of the ALTER SYSTEM command prevents logons by all users except those having RESTRICTED SESSION system privilege. Existing sessions are not terminated.

You may want to restrict logons if you are performing application maintenance and you want only application developers with RESTRICTED SESSION system privilege to log on. To restrict logons, issue this statement:

ALTER SYSTEM

 	ENABLE RESTRICTED SESSION

You can then terminate any existing sessions using the KILL SESSION clause of the ALTER SYSTEM command.

After performing maintenance on your application, issue this statement to allow any user with CREATE SESSION system privilege to log on:

ALTER SYSTEM

 	DISABLE RESTRICTED SESSION

Clearing the Shared Pool

The FLUSH SHARED_POOL option of the ALTER SYSTEM command clears all information from the shared pool in the System Global Area (SGA). The shared pool stores this information:

•	cached data dictionary information

•	shared SQL and PL/SQL areas for SQL statements, stored procedures, functions, packages, and triggers

You might want to clear the shared pool before beginning performance analysis. To clear the shared pool, issue this statement:

ALTER SYSTEM

 	FLUSH SHARED_POOL

This statement does not clear shared SQL and PL/SQL areas for SQL statements, stored procedures, functions, packages, or triggers that are currently being executed or for SQL SELECT statements for which all rows have not yet been fetched.

Performing a Checkpoint

The CHECKPOINT clause of the ALTER SYSTEM command explicitly forces ORACLE to perform a checkpoint. You can force a checkpoint if you want to ensure that all changes made by committed transactions are written to the data files on disk. For more information on checkpoints, see Chapter 22 "Recovery Structure" of the ORACLE7 Server Concepts Manual.  If you are using ORACLE with the Parallel Server option in parallel mode, you can specify either the GLOBAL option to perform a checkpoint on all instances that have opened the database or the LOCAL option to perform a checkpoint on only your instance.

This statement forces a checkpoint:

ALTER SYSTEM

CHECKPOINT

ORACLE does not return control to you until the checkpoint is complete.

Checking Data Files

The CHECK DATAFILES clause of the ALTER SYSTEM command verifies access to all online data files. If any data file is not accessible, ORACLE writes a message to an ALERT file. You may want to perform this operation after fixing a hardware problem that prevented an instance from accessing a data file. For more information on using this clause, see the ORACLE7 Parallel Server Administrator's Guide.

This statement verifies that all instances that have opened the database can access all online data files:

ALTER SYSTEM

 	CHECK DATAFILES GLOBAL

Using Resource Limits

When you start an instance, ORACLE enables or disables resource limits based on the value of the initialization parameter RESOURCE_LIMIT. You can issue an ALTER SYSTEM statement with the RESOURCE_LIMIT option to enable or disable resource limits for subsequent sessions.

Enabling resource limits only causes ORACLE to enforce the resource limits assigned to users. To choose resource limit values for a user, you must create a profile, or a set of limits, and assign that profile to the user. For more information on this process, see the CREATE PROFILE and CREATE USER commands later in this chapter.

This ALTER SYSTEM statement dynamically enables resource limits:

ALTER SYSTEM

 	SET RESOURCE_LIMIT = TRUE

Enabling and Disabling Global Name Resolution

When you start an instance, ORACLE determines whether or not to enforce global name resolution for remote objects accessed in SQL statements based on the value of the initialization parameter GLOBAL_NAMES. You can subsequently enable or disable global names resolution while your instance is running with the GLOBAL_NAMES parameter of the ALTER SYSTEM command. You can also enable or disable global name resolution for your session with the GLOBAL_NAMES parameter of the ALTER SESSION command discussed earlier in this chapter.

Oracle Corporation recommends that you enable global name resolution. For more information on global name resolution and how ORACLE enforces it, see the section "Referring to Objects in Remote Databases" on page 2 - 13 of this Manual and Chapter 15 "Managing Distributed Databases" of the ORACLE7 Server Administrator`s Guide.

Managing Processes for the Multi-Threaded Server

When you start your instance, ORACLE creates shared server processes and dispatcher processes for the multi-threaded server architecture based on the values of these initialization parameters:

MTS_SERVERS	This parameter specifies the initial and minimum number of shared server processes. ORACLE may automatically change the number of shared server processes if the load on the existing processes changes. While your instance is running, the number of shared server processes can vary between the values of the initialization parameters MTS_SERVERS and MTS_MAX_SERVERS.

MTS_

DISPATCHERS

 This parameter specifies one or more network protocols and the number of dispatcher processes for each protocol.

You can subsequently use the MTS_SERVERS and MTS_DISPATCHERS parameters of the ALTER SYSTEM command to perform one of these operations while the instance is running:

To create additional shared server processes:   You can cause ORACLE to create additional shared server processes by increasing the minimum number of shared server processes.

To terminate existing shared server processes:   ORACLE terminates these shared server processes only after they finish processing their current calls and only if the load on the server processes is not so high that it cannot be managed by the remaining processes.

To create more dispatcher processes  for a specific protocol:   You can create additional dispatcher processes up to a maximum across all protocols specified by the initialization parameter MTS_MAX_DISPATCHERS.

You cannot use this command to create dispatcher processes for network protocols that are not specified by the initialization parameter MTS_DISPATCHERS. To create dispatcher processes for a new protocol, you must change the value of the initialization parameter.

To terminate existing dispatcher processes  for a specific protocol:   ORACLE terminates these dispatcher processes only after their current user processes disconnect from the instance.

Example I	This statement changes the minimum number of shared server processes to 25:

ALTER SYSTEM

 	SET MTS_SERVERS = 25

If there are currently fewer than 25 shared server processes, ORACLE creates more. If there are currently more than 25, ORACLE terminates some of them when they are finished processing their current calls if the load could be managed by the remaining 25.

Example II	This statement dynamically changes the number of dispatcher processes for the TCP/IP protocol to 5 and the number of dispatcher processes for the DECNET protocol to 10:

ALTER SYSTEM

SET MTS_DISPATCHERS = 'TCP, 5'

 	    MTS_DISPATCHERS = 'DECnet, 10'

If there are currently fewer than 5 dispatcher processes for TCP, ORACLE creates new ones. If there are currently more than 5, ORACLE terminates some of them after the connected users disconnect.

If there are currently fewer than 10 dispatcher processes for DECnet, ORACLE creates new ones. If there are currently more than 10, ORACLE terminates some of them after the connected users disconnect.

If there are currently existing dispatchers for another protocol, this statement does not affect the number of dispatchers for this protocol.

Using Licensing Limits

ORACLE enforces concurrent usage licensing and named user licensing limits specified by your ORACLE license. When you start your instance, ORACLE establishes these limits based on the values of these initialization parameters:

LICENSE_MAX_

SESSIONS	This parameter establishes the concurrent usage licensing limit, or the limit for concurrent sessions. Once this limit is reached, only users with RESTRICTED SESSION system privilege can connect.

LICENSE_

SESSIONS_

WARNING	This parameter establishes a warning threshold for concurrent usage. Once this threshold is reached, ORACLE writes a warning message to the database ALERT file for each subsequent session. Also, users with RESTRICTED SESSION system privilege receive warning messages when they begin subsequent sessions.

LICENSE_MAX_USERS	This parameter establishes the limit for users created for your database. Once this limit for users is reached, more users cannot be created.

You can subsequently use the LICENSE_MAX_SESSIONS, LICENSE_SESSIONS_WARNING, and LICENSE_MAX_USERS parameters of the ALTER SYSTEM command to dynamically change or disable limits or thresholds while your instance is running. Do not disable or raise session or user limits unless you have appropriately upgraded your ORACLE license. For information on upgrading your license, contact your Oracle sales representative.

New limits apply only to future sessions and users:

•	If you reduce the limit on sessions below the current number of sessions, ORACLE does not end existing sessions to enforce the new limit. Users without RESTRICTED SESSION system privilege can only begin new sessions when the number of sessions falls below the new limit.

•	If you reduce the warning threshold for sessions below the current number of sessions, ORACLE writes a message to the ALERT file for all subsequent sessions.

•	You cannot reduce the limit on users below the current number of users created for the database.

Example III	This statement dynamically changes the limit on sessions for your instance to 64 and the warning threshold for sessions on your instance to 54:

ALTER SYSTEM

SET LICENSE_MAX_SESSIONS = 64

    LICENSE_SESSIONS_WARNING = 54

If the number of sessions reaches 54, ORACLE writes a warning message to the ALERT file for each subsequent session. Also, users with RESTRICTED SESSION system privilege receive warning messages when they begin subsequent sessions.

If the number of sessions reaches 64, only users with RESTRICTED SESSION system privilege can begin new sessions until the number of sessions falls below 64 again.

Example IV	This statement dynamically disables the limit for sessions on your instance:

ALTER SYSTEM

 	SET LICENSE_MAX_SESSIONS = 0

After you issue this statement, ORACLE no longer limits the number of sessions on your instance.

Example V	This statement dynamically changes the limit on the number of users in the database to 200:

ALTER SYSTEM

 	SET LICENSE_MAX_USERS = 200

After you issue this statement, ORACLE prevents the number of users in the database from exceeding 200.

Switching Redo Log File Groups

The SWITCH LOGFILE option of the ALTER SYSTEM command explicitly forces ORACLE to beginwriting to a new redo log file group, regardless of whether the files in the current redo log file group are full. You may want to force a log switch in order to drop or rename the current redo log file group or one of its members, since you cannot drop or rename a file while ORACLE is writing to it. The forced log switch only affects your instance's redo log thread. Note that when you force a log switch, ORACLE begins to perform a checkpoint. ORACLE returns control to you immediately rather than when the associated checkpoint is complete.

This statement forces a log switch:

ALTER SYSTEM

SWITCH LOGFILE

Enabling Distributed Recovery

ORACLE allows you to perform distributed transactions, or transactions that modify data on multiple databases. In the event of a network or machine failure during the commit process for a distributed transaction, the state of the transaction may be unknown, or in-doubt. Once the failure has been corrected and the network and its nodes are back online, ORACLE recovers the transaction.

If you are using ORACLE in multiple-process mode, this distributed recovery is performed automatically. If you are using ORACLE in single-process (single user) mode, such as on the MS-DOS operating system, you must explicitly initiate distributed recovery with this statement.

ALTER SYSTEM ENABLE DISTRIBUTED RECOVERY

You may need to issue this statement more than once to recover an in-doubt transaction, especially if the remote node involved in the transaction is not accessible. In-doubt transactions appear in the data dictionary view DBA_2PC_PENDING. You can tell that the transaction is recovered when it no longer appears in DBA_2PC_PENDING. For more information about distributred transactions and distributed recovery, see Chapter 15 "Managing Distributed Databases" of the ORACLE7 Server Administrator's Guide.

Disabling Distributed Recovery

You can use this statement to disable distributed recovery in both single-process and multi-process mode:

ALTER SYSTEM DISABLE DISTRIBUTED RECOVERY

You may want to disable distributed recovery for demonstration purposes. You can then enable distributed recovery again by issuing an ALTER SYSTEM statement with the ENABLE DISTRIBUTED RECOVERY clause.

Terminating a Session

The KILL SESSION clause of the ALTER SYSTEM command terminates a session, immediately performing these tasks:

•	rolling back its current transactions

•	releasing all of its locks

•	freeing all of its resources

You may want to kill the session of a user that is holding resources needed by other users. The user receives an error message indicating that the session has been killed and can no longer make calls to the database without beginning a new session. You can only kill a session on the same instance as your current session.

If you try to kill a session that is performing some activity that must be completed, such as waiting for a reply from a remote database or rolling back a transaction, ORACLE waits for this activity to complete, kills the session, and then returns control to you. If the waiting lasts as long as a minute, ORACLE marks the session to be killed and returns control to you with a message indicating that the session is marked to be killed. ORACLE then kills the session when the activity is complete.

Example VI	Consider this data from the V$SESSION dynamic performance table:

SELECT sid, serial#, username

FROM v$session

SID  SERIAL#  USERNAME

--------------------------

1

2        1

3        1

4        1

5        1

7        1

8       28   OPS$PRITTO

10      211  OPS$WMAIMONE

11       39  OPS$ACCHEN

12       13  SYSTEM

13        8  SCOTT

This statement kills the session of the user SCOTT using the SID and SERIAL# values from V$SESSION:

ALTER SYSTEM

KILL SESSION '13, 8'

Related Topics

ALTER SESSION, CREATE PROFILE, and CREATE USER commands.

________________________________________

ALTER TABLE

Purpose

To alter the definition of a table in one of these ways:

•	to add a column

•	to add an integrity constraint

•	to redefine a column (datatype, size, default value)

•	to modify storage characteristics or other parameters

•	to enable, disable, or drop an integrity constraint or trigger

•	to explicitly allocate an extent

Prerequisites

The table must be in your own schema or you must have ALTER privilege on the table or you must have ALTER ANY TABLE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the table's creation label or you must satisfy one of these criteria:

•	If the table's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the table's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the table's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the table. If you omit schema, ORACLE assumes the table is in your own schema.

table 	is the name of the table to be altered.

ADD	adds a column or integrity constraint.

MODIFY	modifies

the definition of an existing column. If you omit any of the optional parts of the column definition (datatype, default value, or column constraint), these parts remain unchanged.

column	is the name of the column to be added or modified.

datatype	specifies a datatype for a new column or a new datatype for an existing column.

You can only omit the datatype if the statement also designates the column as part of the foreign key of a referential integrity constraint. ORACLE automatically assigns the column the same datatype as the corresponding column of the referenced key of the referential integrity constraint.

DEFAULT	specifies a default value for a new column or a new default for an existing column. ORACLE assigns this value to the column if a subsequent INSERT statement omits a value for the column. The datatype of the default value must match the datatype specified for the column. The column must also be long enough to hold the default value. A DEFAULT expression cannot contain references to other columns, the pseudocolumns CURRVAL, NEXTVAL, LEVEL, and ROWNUM, or date constants that are not fully specified.

column_constraint	adds or removes a NOT NULL constraint to or from and existing column. See the syntax of column_constraint on page 5 - 119.

table_constraint	adds an integrity constraint to the table. See the syntax of table_constraint on page 5 - 119.

PCTFREE PCTUSED INITRANS MAXTRANS	changes the value of one of these parameters for the table. See the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters of the CREATE TABLE command later in this chapter.

STORAGE	changes the storage characteristics of the table. See the STORAGE clause beginning on page 8 - 371.

DROP	drops an integrity constraint. See the DROP clause on page 6 - 238.

ALLOCATE EXTENT	explicitly allocates a new extent for the table.

SIZE	specifies the size of the extent in bytes. You can use K or M to specify the extent size in kilobytes or megabytes. If you omit this parameter, ORACLE determines the size based on the values of the table's STORAGE parameters.

DATAFILE	specifies one of the data files in the table's tablespace to contain the new extent. If you omit this parameter, ORACLE chooses the data file.

INSTANCE	makes the new extent available to the specified instance. An instance is identified by the value of its initialization parameter INSTANCE_NUMBER. If you omit this parameter, the extent is available to all instances. Only use this parameter if you are using ORACLE with the Parallel Server option in parallel mode.

Explicitly allocating an extent with this clause does affect the size for the next extent to be allocated as specified by the NEXT and PCTINCREASE storage parameters.

ENABLE	enables a single integrity constraint or all triggers associated with the table. See the ENABLE clause on page 7 - 263.

DISABLE	disables a single integrity constraint or all triggers associated with the table. See the DISABLE clause 6 - 235.

Integrity constraints specified in these clauses must be defined in the ALTER TABLE statement or in a previously issued statement. You can also enable and disable integrity constraints with the ENABLE and DISABLE keywords of the CONSTRAINT clause. If you define an integrity constraint but do not explicitly enable or disable it, ORACLE enables it by default.

Adding Columns

If you use the ADD clause to add a new column to the table, then the initial value of each row for the new column is null. You can adda column with a NOT NULL constraint only to a table that contains no rows.

If you create a view with a query that uses the asterisk (*) in the select list to select all columns from the base table and you subsequently add columns to the base table, ORACLE will not automatically add the new column to the view. To add the new column to the view, you can re-create the view using the CREATE VIEW command with the OR REPLACE option.

Operations performed by the ALTER TABLE command can cause ORACLE to invalidate procedures and stored functions that access the table. For information on how and when ORACLE invalidates such objects, see Chapter 16 "Dependencies Among Schema Objects"  of the ORACLE7 Server Concepts Manual.

Modifying Column Definitions

You can use the MODIFY clause to change any of these parts of a column definition:

•	datatype

•	size

•	default value

•	NOT NULL column constraint

The MODIFY clause need only specify the column name and the modified part of the definition, rather than the entire column definition.

 Datatypes and Sizes

You can change a column's datatype or decrease a column's size only if the column contains nulls in all rows. However, you can always increase the size of a character or raw column or the precision of a numeric column.

 Default Values

A change to a column's default value only affects rows subsequently inserted into the table. Such a change does not change default values previously inserted.

 Integrity Constraints

The only type of integrity constraint that you can add to an existing column using the MODIFY clause with the column constraint syntax is a NOT NULL constraint. However, you can define other types of integrity constraints (UNIQUE, PRIMARY KEY, referential integrity, and CHECK constraints) on existing columns using the ADD clause and the table constraint syntax.

You can define a NOT NULL constraint on an existing column only if the column contains no nulls.

Example I	This statement adds a column named THRIFTPLAN of datatype NUMBER with a maximum of seven digits and two decimal places and a column named LOANCODE of datatype CHAR with a size of one and a NOT NULL integrity constraint:

ALTER TABLE emp

ADD (thriftplan NUMBER(7,2),

 	 loancode   CHAR(1)     NOT NULL)

Example II	This statement increases the size of the THRIFTPLAN column to nine digits:

ALTER TABLE emp

 	MODIFY (thriftplan NUMBER(9,2))

Because the MODIFY clause contains only one column definition, the parentheses around the definition are optional.

Example III	This statement changes the values of the PCTFREE and PCTUSED parameters for the EMP table to 30 and 60, respectively:

ALTER TABLE emp

PCTFREE 30

 	PCTUSED 60

Example IV	This statement allocates an extent of 5 kilobytes for the EMP table and makes it available to instance 4:

ALTER TABLE emp

 	ALLOCATE EXTENT (SIZE 5K  INSTANCE 4)

Because this command omits the DATAFILE parameter, ORACLE allocates the extent in one of the data files belonging to the tablespace containing the table.

Example V	This example modifies the BAL column of the ACCOUNTS table so that it has a default value of 0:

ALTER TABLE accounts

 	MODIFY (bal  DEFAULT 0)

If you subsequently add a new row to the ACCOUNTS table and do not specify a value for the BAL column, the value of the BAL column is automatically 0:

INSERT INTO accounts(accno, accname)

 	VALUES (accseq.nextval, 'LEWIS')

SELECT *

FROM accounts

WHERE accname = 'LEWIS'

 ACCNO ACCNAME BAL

------ ------- ---

815234 LEWIS     0

Other Examples	For examples of defining integrity constraints with the ALTER TABLE command, see the CONSTRAINT clause beginning on page 5 - 119.

For examples of enabling, disabling, and dropping integrity constraints and triggers with the ALTER TABLE command, see the ENABLE clause on page 7 - 263, the DISABLE clause on page 6 - 235, and DROP clause on page 6 - 238.

For examples of changing the value of a table's storage parameters, see the STORAGE clause on page 8 - 371.

Related Topics

CREATE TABLE command; CONSTRAINT, DISABLE, DROP, ENABLE, and STORAGE clauses.

________________________________________

ALTER TABLESPACE

Purpose

To alter an existing tablespace in one of these ways:

•	to add or rename data file(s)

•	to change default storage parameters

•	to take the tablespace online or offline

•	to begin or end a backup

Prerequisites

If you have ALTER TABLESPACE system privilege, you can perform any of this command's operations. If you have MANAGE TABLESPACE system privilege, you can only perform these operations:

•	to take the tablespace online or offline

•	to begin or end a backup

•	make the tablespace read-only or read-write

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the tablespace's creation label or you must satisfy one of these criteria:

•	If the tablespace's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the tablespace's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the tablespace's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

If you are using Trusted ORACLE in DBMS MAC mode, to add a data file, your operating system process label must be the equivalent of DBHIGH.

Before taking a tablespace offline for a long period of time, you may want to alter any users who have been assigned the tablespace as either a default or temporary tablespace. When the tablespace is offline, these users cannot allocate space for objects or sort areas in the tablespace. You can reassign users new default and temporary tablespaces with the ALTER USER command.

Syntax

Keywords and Parameters

tablespace	is the name of the tablespace to be altered.

RENAME DATAFILE	renames one or more of the tablespace's data files. Take the tablespace offline before renaming the data file. Each 'filename' must fully specify a data file using the conventions for filenames on your operating system.

This clause only associates the tablespace with the new file rather than the old one. This clause does not actually change the name of the operating system file. You must change the name of the file through your operating system.

DEFAULT  STORAGE	specifies the new default storage parameters for objects subsequently created in the tablespace. See the STORAGE clause on page 8 - 371.

ONLINE	brings the tablespace online.

OFFLINE	takes the tablespace offline and prevents further access to its segments.

NORMAL	performs a checkpoint for all data files in the tablespace. All of these data files must be online. You need not perform media recovery on this tablespace before bringing it back online. You must use this option if the database is in noarchivelog mode.

TEMPORARY	performs a checkpoint for all online data files in the tablespace but does not ensure that all files can be written. Any offline files may require media recovery before you bring the tablespace back online.

IMMEDIATE	does not ensure that tablespace files are available and does not perform a checkpoint. You must perform media recovery on the tablespace before bringing it back online.

The default is NORMAL.

Suggestion: Before taking a tablespace offline for a long period of time, you may want to alter any users who have been assigned the tablespace as either a default or temporary tablespace.  When the tablespace is offline, these users cannot allocate space for objectsor sort areas in the tablespace.  You can reassign users new default and temporary tablespaces with the ALTER USER command.

BEGIN BACKUP	signifies that an online backup is to be performed on the data files that comprise this tablespace. This option does not prevent users from accessing the tablespace. This option is used for control file and redo log record keeping. You must use this option before beginning an online backup. You cannot use this option on a read-only tablespace.

While the backup is in progress, you cannot:

•	take the tablespace offline normally

•	shutdown the instance

•	begin another backup of the tablespace

END BACKUP	signifies that an online backup of the tablespace  is complete. Use this option as soon as possible after completing an online backup. You cannot use this option on a read-only tablespace.

Usage Notes

If you are using Trusted ORACLE, data files that you add to a tablespaceare labelled with the operating system equivalent of DBHIGH.

Example I	This statement signals to the database that a backup is about to begin:

ALTER TABLESPACE accounting

BEGIN BACKUP

Example II	This statement signals to the database that the backup is finished:

ALTER TABLESPACE accounting

END BACKUP

Example III	This example moves and renames a data file associated with the ACCOUNTING tablespace from 'DISKA:PAY1.DAT' to 'DISKB:RECEIVE1.DAT':

1.	Take the tablespace offline using an ALTER TABLESPACE statement with the OFFLINE option:

ALTER TABLESPACE accounting OFFLINE NORMAL

2.	Copy the file from 'DISKA:PAY1.DAT' to 'DISKB:RECEIVE1.DAT' using your operating system's commands.

3.	Rename the data file using the ALTER TABLESPACE command with the RENAME DATAFILE clause:

ALTER TABLESPACE accounting

 	RENAME DATAFILE 'diska:pay1.dat' TO 	'diskb:receive1.dat'

4.	Bring the tablespace back online using an ALTER TABLESPACE statement with the ONLINE option:

ALTER TABLESPACE accounting ONLINE

Related Topics

CREATE TABLESPACE, CREATE DATABASE, and DROP TABLESPACE commands; STORAGE clause.

________________________________________

ALTER TRIGGER

Purpose

To perform one of these operations on a database trigger:

•	enable

•	disable

Prerequisites

The trigger must be in your own schema or you must have ALTER ANY TRIGGER system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the trigger's creation label or you must satisfy one of these criteria:

•	If the trigger's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the trigger's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the trigger's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the trigger. If you omit schema, ORACLE assumes the trigger is in your own schema.

trigger	is the name of the trigger to be altered.

ENABLE	enables the trigger.

DISABLE	disables the trigger.

Enabling and Disabling Triggers

A database trigger is always in one of these states:

enabled	If a trigger is enabled, ORACLE fires the trigger when a triggering statement is issued.

disabled	If the trigger is disabled, ORACLE does not fire the trigger when a triggering statement is issued.

When you create a trigger, ORACLE enables it automatically. You can use the ENABLE and DISABLE options of the ALTER TRIGGER command to enable and disable a trigger.

You can also use the ENABLE and DISABLE clauses of the ALTER TABLE command to enable and disable all triggers associated with a table.

Note: The ALTER TRIGGER command does not change the definition of an existing trigger. To redefine a trigger, you must use the CREATE TRIGGER command with the OR REPLACE option.

Example	Consider a trigger named REORDER created on the INVENTORY table that is fired whenever an UPDATE statement reduces the number of a particular part on hand below the part's reorder point. The trigger inserts into a table of pending orders a row that contains the part number, a reorder quantity, and the current date.

When this trigger is created, ORACLE enables it automatically. You can subsequently disable the trigger with this statement:

ALTER TRIGGER reorder

 	DISABLE

When the trigger is disabled, ORACLE does not fire the trigger when an UPDATE statement causes the part's inventory to fall below its reorder point.

After disabling the trigger, you can subsequently enable it with this statement:

ALTER TRIGGER reorder

 	ENABLE

After you reenable the trigger, ORACLE fires the trigger whenever a part's inventory falls below its reorder point as a result of an UPDATE statement. Note that a part's inventory may have fallen below its reorder point while the trigger was disabled. When you reenable the trigger, ORACLE does not automatically fire the trigger for this part.

Related Topics

CREATE TRIGGER and DROP TRIGGER commands;  DISABLE and ENABLE clauses.

________________________________________

ALTER USER

Purpose

To change any of these characteristics of a database user:

•	password

•	default tablespace for object creation

•	tablespace for temporary segments created for the user

•	tablespace access and tablespace quotas

•	limits on database resources

•	default roles

Prerequisites

You must have ALTER USER privilege. However, you can change your own password without this privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the user's creation label or you must satisfy one of these criteria:

•	If the user's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the user's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the user's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

You can only change a user's default roles if your DBMS label matches the creation label of the user. Your DBMS label must also dominate the role's creation label or you must have READUP system privilege.

You can only establish a default or temporary tablespace if both your DBMS label and the user's creation label dominates the tablespace's creation label or if both you and the user have READUP system privilege.

You can only change a user's profile if both your DBMS label and the user's creation label dominate the profile's creation label or if both you and the user have READUP system privilege.

Syntax

Keywords and Parameters

user	is the user to be altered.

IDENTIFIED	indicates how ORACLE permits user access.

BY	specifies a new password for the user. The password does not appear in quotes.  Passwords must also follow the rules described in the section "Object Naming Rules" on page 2 - 3 and can only contain single-byte characters from your database character set regardless of whether your character set also contains multi-byte characters.

EXTERNALLY	indicates that ORACLE verifies user access with the operating system, rather than with a password. See the CREATE USER command later in this chapter.

Although you do not need privileges to change your own password, you must have ALTER USER system privilege to change from BY password to EXTERNALLY or vice-versa.

DEFAULT TABLESPACE	specifies the default tablespace for object creation.

TEMPORARY TABLESPACE	specifies the tablespace for the creation of temporary segments for operations such as sorting that require more space than is available in memory.

QUOTA	establishes a space quota of integer bytes on the tablespace for the user. This quota is the maximum space in tablespace that can be allocated for objects in the user's schema. You can use K or M to specify the quota in kilobytes or megabytes. You need not have quota on the tablespace to establish a quota on the tablespace for another user. See the CREATE USER command later in this chapter.

If you reduce an existing quota to a value below the space allocated for existing objects in the user's schema in the tablespace, no more space in the tablespace can be allocated to objects in the schema.

Note that an ALTER USER statement can contain multiple QUOTA clauses for multiple tablespaces.

UNLIMITED	places no limit on the space in the tablespace allocated to objects in the user's schema.

PROFILE	changes the user's profile to profile. In subsequent sessions, the user is subject to the limits defined in the new profile.

To assign the default limits to the user, assign the user the DEFAULT profile.

DEFAULT ROLE	establishes default roles for the user. ORACLE enables the user's default roles at logon. By default, all roles granted to the user are default roles.

ALL	makes all the roles granted to the user default roles, except those listed in the EXCEPT clause.

NONE	makes none of the roles granted to the user default roles.

Establishing Default Roles

The DEFAULT ROLE clause can only contain roles that have been granteddirectly to the user with a GRANT statement. You cannot use the DEFAULTROLE clause to enable:

•	roles not granted to the user

•	roles granted through other roles

•	roles managed by the operating system

Note that ORACLE enables default roles at logon without requiring the user to specify their passwords.

Example I	This statement changes the user SCOTT's password to LION and default tablespace to the tablespace TSTEST:

ALTER USER scott

IDENTIFIED BY lion

 	DEFAULT TABLESPACE tstest

Example II	This statement assigns the CLERK profile to SCOTT:

ALTER USER scott

PROFILE clerk

In subsequent sessions, SCOTT is restricted by limits in the CLERK profile.

Example III	This statement makes all roles granted directly to SCOTT default roles, except the AGENT role:

ALTER USER scott

DEFAULT ROLE ALL EXCEPT agent

At the beginning of SCOTT's next session, ORACLE enables all roles granted directly to SCOTT except the AGENT role.

Related Topics

CREATE PROFILE, CREATE ROLE, CREATE USER, and CREATE TABLESPACE commands.

________________________________________

ALTER VIEW

Purpose

To recompile a view.

Prerequisites

The view must be in your own schema or you must have ALTER ANY TABLE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the view's creation label or you must satisfy one of these criteria:

•	If the view's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the view's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the view's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the view. If you omit schema, ORACLE assumes the view is in your own schema.

view	is the name of the view to be recompiled.

COMPILE	causes ORACLE to recompile the view. The COMPILE keyword is required.

Usage Notes

You can use the ALTER VIEW command to explicitly recompile a viewthat is invalid. Explicit recompilation allows you to locate recompilationerrors prior to runtime. You may want to explicitly recompile a view after altering one of its base tables to ensure that the alteration does not affect the view or other objects that depend on it.

When you issue an ALTER VIEW statement, ORACLE recompiles the view regardless of whether it is valid or invalid. ORACLE also invalidates any local objects that depend on the view. For more information on how ORACLE maintains dependencies among schema objects, including remote objects, see Chapter 16  of the ORACLE7 Server Concepts Manual.

Note: This command does not change the definition of an existing view. To redefine a view, you must use the CREATE VIEW command with the OR REPLACE option.

Example	To recompile the view CUSTOMER_VIEW, issue this statement:

ALTER VIEW customer_view

 	COMPILE

If ORACLE encounters no compilation errors while recompiling CUSTOMER_VIEW, CUSTOMER_VIEW becomes valid. If recompiling results in compilation errors, ORACLE returns an error and CUSTOMER_VIEW remains invalid.

ORACLE also invalidates all dependent objects. These objects include any procedures, functions, package bodies, and views that reference CUSTOMER_VIEW. If you subsequently reference one of these objects without first explicitly recompiling it, ORACLE recompiles it implicitly at runtime.

Related Topics

CREATE VIEW command.

________________________________________

ANALYZE

Purpose

To perform one of these functions on an index, table, or cluster:

•	to collect statistics about the object used by the optimizer and store them in the data dictionary

•	to delete statistics about the object from the data dictionary

•	to validate the structure of the object

•	to identify migrated and chained rows of the table or cluster

Prerequisites

The object to be analyzed must be in your own schema or you must have the ANALYZE ANY system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the creation label of the object to be analyzed or you must satisfy one of these criteria:

•	If the object's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the object's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the object's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

If you want to list chained rows of a table or cluster into a list table, the list table must be in your own schema or you must have INSERT privilege on the list table or you must have INSERT ANY TABLE system privilege. If you are using Trusted ORACLE in DBMS MAC mode, the list table must also meet the criteria for the analyzed object described above.

Syntax

Keywords and Parameters

INDEX	identifies an index to be analyzed. If you omit schema, ORACLE assumes the index is in your own schema.

TABLE	identifies a table to be analyzed. If you omit schema, ORACLE assumes the table is in your own schema. When you collect statistics for a table, ORACLE also automatically collects the statistics for each of the table's indexes.

CLUSTER	identifies a cluster to be analyzed. If you omit schema, ORACLE assumes the cluster is in your own schema. When you collect statistics for a cluster, ORACLE also automatically collects the statistics for all the cluster's tables and all their indexes, including the cluster index.

COMPUTE STATISTICS	computes exact statistics about the analyzed object and stores them in the data dictionary.

ESTIMATE STATISTICS	estimates statistics about the analyzed object and stores them in the data dictionary.

SAMPLE	specifies the amount of data from the analyzed object ORACLE samples to estimate statistics. If you omit this parameter, ORACLE samples 1064 rows. If you specify more than half of the data, ORACLE reads all the data and computes the statistics.

ROWS	causes ORACLE to sample integer rows of the table or cluster or integer entries from the index. The integer must be at least 1.

PERCENT	causes ORACLE to sample integer percent of the rows from the table or cluster or integer percent of the index entries. The integer can range from 1 to 99.

DELETE STATISTICS	deletes any statistics about the analyzed object that are currently stored in the data dictionary.

VALIDATE STRUCTURE	validates the structure of the analyzed object. If you use this option when analyzing a cluster, ORACLE automatically validates the structure of the cluster's tables.

CASCADE	validates the structure of the indexes associated with the table or cluster. If you use this option when validating a table, ORACLE also validates the table's indexes. If you use this option when validating a cluster, ORACLE also validates all the clustered tables' indexes, including the cluster index.

LIST CHAINED ROWS	identifies migrated and chained rows of the analyzed table or cluster. You cannot use this option when analyzing an index.

INTO	specifies a table into which ORACLE lists the migrated and chained rows. If you omit schema,  ORACLE assumes the list table is in your own schema. If you omit this clause altogether, ORACLE assumes that the table is named  CHAINED_ROWS. The list table must be on your local database.

Collecting Statistics

You can collect statistics about the physical storage characteristicsand data distribution of an index, table, or cluster and store themin the data dictionary. You can use the COMPUTE STATISTICS or ESTIMATE STATISTICS option to cause ORACLE to compute or estimate these statistics:

•	Computation always provides exact values, but can take longer than estimation.

•	Estimation is often much faster than computation and the results are usually nearly exact.

Use estimation, rather than computation, unless you feel you need exact values. Some statistics are always computed exactly, regardless of whether you specify computation or estimation. If you choose estimation and the time saved by estimating a statistic is negligible, ORACLE computes the statistic exactly.

If the data dictionary already contains statistics for the analyzed object, ORACLE updates the existing statistics with the new ones.

The statistics are used by the ORACLE optimizer to choose the execution plan for SQL statements that access analyzed objects. These statistics may also be useful to application developers who write such statements. For information on how these statistics are used, see Chapter 13 "The Optimizer" of the ORACLE7 Server Concepts Manual.

The following sections list the statistics for indexes, tables, and clusters.

 Indexes

For an index, ORACLE collects these statistics:

•	depth of the index from its root block to its leaf blocks*

•	number of leaf blocks

•	number of distinct index values

•	average number of leaf blocks per index value

•	average number of data blocks per index value

 (for an index on a table)

•	clustering factor

 (how well ordered are the rows about the indexed values)

The statistics marked with asterisks (*) are always computed exactly.

These statistics appear in the data dictionary views USER_INDEXES, ALL_INDEXES, and DBA_INDEXES.

 Tables

For a table, ORACLE collects these statistics:

•	number of rows

•	number of data blocks currently containing data *

•	number of data blocks allocated to the table that have never been used *

•	average available free space in each data block in bytes

•	number of chained rows

•	average row length, including the row's overhead, in bytes

•	number of distinct values for each column

•	maximum* and minimum* values for each column

 (Note that these are the second greatest and second least values)

The statistics marked with asterisks (*) are always computed.

These statistics all appear in the data dictionary views USER_TABLES, ALL_TABLES, and DBA_TABLES, except for the number of distinct values and the maximum and minimum values for each column which appear in USER_TAB_COLUMNS, ALL_TAB_COLUMNS, and DBA_TAB_COLUMNS.

 Clusters

For an indexed cluster, ORACLE collects the average number of data blocks taken up by a single cluster key value and all of its rows. For a hash clusters, ORACLE collects the average number of data blocks taken up by a single hash key value and all of its rows. These statistics appear in the data dictionary views USER_CLUSTERS and DBA_CLUSTERS.

Example I	This statement estimates statistics for the CUST_HISTORY table and all of its indexes:

ANALYZE TABLE cust_history

 	ESTIMATE STATISTICS

Deleting Statistics

With the DELETE STATISTICS option of the ANALYZE command, you can remove existing statistics about an object from the data dictionary. You may want to remove statistics if you no longer want the ORACLE optimizer to use them.

When you use the DELETE STATISTICS option on a table, ORACLE also automatically removes statistics for all the table's indexes. When you use the DELETE STATISTICS option on a cluster, ORACLE also automatically removes statistics for all the cluster's tables and all their indexes, including the cluster index.

Example II	This statement deletes statistics about the CUST_HISTORY table and all its indexes from the data dictionary:

ANALYZE TABLE cust_history

 	DELETE STATISTICS

Validating Structures

With the VALIDATE STRUCTURE option of the ANALYZE command, you can verify the integrity of the structure of an index, table, or cluster. If ORACLE successfully validates the structure, a message confirming its validation is returned to you. If ORACLE encounters corruption in the structure of the object, an error message is returned to you. In this case, drop and recreate the object.

Since the validating the structure of a object prevents SELECT, INSERT, UPDATE, and DELETE statements from concurrently accessing the object, do not use this option on the tables, clusters, and indexes of your production applications during periods of high database activity.

 Indexes

For an index, the VALIDATE STRUCTURE option verifies the integrity of each data block in the index and checks for block corruption. Note that this option does not confirm that each row in the table has an index entry or that each index entry points to a row in the table. You can perform these operations by validating the structure of the table.

When you use the VALIDATE STRUCTURE option on an index, ORACLE also collects statistics about the index and stores them in the data dictionary view INDEX_STATS. ORACLE overwrites any existing statistics about previously validated indexes. At any time, INDEX_STATS can contain only one row describing only one index.

The statistics collected by this option are not used by the ORACLE optimizer. Do not confuse these statistics with the statistics collected by the COMPUTE STATISTICS and ESTIMATE STATISTICS options.

Example III	This statement validates the structure of the index PARTS_INDEX:

ANALYZE INDEX parts_index

 	VALIDATE STRUCTURE

 Tables

For a table, the VALIDATE STRUCTURE option verifies the integrity of each of the table's data blocks and rows. You can use the CASCADE option to also validate the structure of all indexes on the table and to perform cross-referencing between the table and each of its indexes. For each index, the cross-referencing involves these validations:

•	Each value of the tables's indexed column must match the indexed column value of an index entry. The matching index entry must also identify the row in the table by the correct ROWID.

•	Each entry in the index identifies a row in the table. The indexed column value in the index entry must match that of the identified row.

Example III	This statement analyzes the EMP table and all of its indexes:

ANALYZE TABLE emp

 	VALIDATE STRUCTURE CASCADE

 Clusters

For a cluster, the VALIDATE STRUCTURE option verifies the integrity of each row in the cluster and automatically validates the structure of each of the cluster's tables. You can use the CASCADE option to also validate the structure of all indexes on the cluster's tables, including the cluster index.

Example IV	This statement analyzes the ORDER_CUSTS cluster, all of its tables, and all of their indexes, including the cluster index:

ANALYZE CLUSTER order_custs

 	VALIDATE STRUCTURE CASCADE

Listing Chained Rows

With the LIST option of the ANALYZE command, you can collect information about the migrated and chained rows in a table or cluster. A migrated row is one that has been moved from one data block to another. For example, ORACLE migrates a row in a cluster if its cluster key value is updated. A chained row is one that is contained in more than one data block. For example, ORACLE chains a row of a table or cluster if the row is too long to fit in a single data block. Migrated and chained rows may cause excessive I/O. You may want to identify such rows in order to eliminate them. For information on eliminating migrated and chained rows, see Chapter 22 "Tuning I/O" of the ORACLE7 Server Administrator's Guide.

You can use the INTO clause to specify an output table into which ORACLE places this information. The definition of a sample output table CHAINED_ROWS is provided in a SQL script available on your distribution media. Your list table must have the same column names, types, and sizes as the CHAINED_ROWS table.  On many operating systems, the name of this script is UTLCHAIN.SQL. The actual name and location of this script may vary depending on your operating system.

Example V	This statement collects information about all the chained rows of the table ORDER_HIST:

ANALYZE TABLE order_hist

 	LIST CHAINED ROWS INTO cr

This statement places the information into the table CR.

You can then examine these rows with this query:

SELECT *

FROM cr

OWNER_NAME  TABLE_NAME  CLUSTER_NAME  HEAD_ROWID          TIMESTAMP

----------  ----------  ------------  ------------------  ---------

SCOTT       ORDER_HIST                0000346A.000C.0003  15-MAR-93

Related Topics

Chapter 13 "The Optimizer" of the  ORACLE7 Server Concepts Manual  and  Chapter 22 "Tuning I/O" of the  ORACLE7 Server Administrator's Guide.

________________________________________

ARCHIVE LOG clause

Purpose

To manually archive redo log file groups or to enable or disable automatic archiving.

Prerequisites

The ARCHIVE LOG clause must appear in an ALTER SYSTEM command. You must have the privileges necessary to issue this statement. For information on these privileges, see the ALTER SYSTEM command earlier in this chapter.

You must also have the OSDBA or OSOPER role enabled.

You can use most of the options of this clause when your instance has the database mounted, open or closed. Options that require your instance to have the database open are noted.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must be the equivalent of DBHIGH.

Syntax

Keywords and Parameters

THREAD	specifies thread containing the redo log file group to be archived. You only need to specify this parameter if you are using ORACLE with the Parallel Server option in parallel mode.

SEQ	manually archives the online redo log file group identified by the log sequence number integer in the specified thread. If you omit the THREAD parameter, ORACLE archives the specified group from the thread assigned to your instance.

CHANGE	manually archives the online redo log file group containing the redo log entry with the system change number (SCN) specified by integer in the specified thread. If the SCN is in the current redo log file group, ORACLE performs a log switch. If you omit the THREAD parameter, ORACLE archives the groups containing this SCN from all enabled threads. You can only use this option when your instance has the database open.

CURRENT	manually archives the current redo log file group of the specified thread, forcing a log switch. If you omit the THREAD parameter, ORACLE archives the current redo log file groups from all enabled threads. You can only use this option when your instance has the database open.

GROUP	manually archives the online redo log file group with the specified GROUP value. You can determine the GROUP value for a redo log file group by examining the data dictionary view DBA_LOG_FILES. If you specify both the THREAD and GROUP parameters, the specified redo log file group must be in the specified thread.

LOGFILE	manually archives the online redo log file group containing the redo log file member identified by 'filename'. If you specify both the THREAD and LOGFILE parameters, the specified redo log file group must be in the specified thread.

NEXT	manually archives the next online redo log file group from the specified thread that is full but has not yet been archived. If you omit the THREAD parameter, ORACLE archives the earliest unarchived redo log file group from any enabled thread.

ALL	manually archives all online redo log file groups from the specified thread that are full but have not been archived. If you omit the THREAD parameter, ORACLE archives all full unarchived redo log file groups from all enabled threads.

START	enables automatic archiving of redo log file groups. You can only enable automatic archiving for the thread assigned to your instance.

TO	specifies the location to which the redo log file group is archived. The value of this parameter must be a fully-specified file location following the conventions of your operating system. If you omit this parameter, ORACLE archives the redo log file group to the location specified by the initialization parameter LOG_ARCHIVE_DEST.

STOP	disables automatic archiving of redo log file groups. You can only disable automatic archiving for the thread assigned to your instance.

Usage Notes

You must archive redo log file groups in the order in which they arefilled. If you specify a redo log file group for archiving with theSEQ or LOGFILE parameter and earlier redo log file groups are not yet archived, ORACLE returns an error. If you specify a redo log file group for archiving with the CHANGE parameter or CURRENT option and earlier redo log file groups are not yet archived, ORACLE archives all unarchived groups up to and including the specified group.

You can also manually archive redo log file groups with the ARCHIVE LOG SQL*DBA command. For information on this command, see the ORACLE7 Server Utilities User's Guide.

You can also choose to have ORACLE archive redo log files groups automatically. For information on automatic archiving, see Chapter 17 "Archiving Redo Information" of the ORACLE7 Server Administrator`s Guide. Note that you can always manually archive redo log file groups regardless of whether automatic archiving is enabled.

Example I	This statement manually archives the redo log file group with the log sequence number 4 in thread number 3:

ALTER SYSTEM ARCHIVE LOG THREAD 3 SEQ 4

Example II	This statement manually archives the redo log file group containing the redo log entry with the SCN 9356083:

ALTER SYSTEM ARCHIVE LOG CHANGE 9356083

Example III	This statement manually archives the redo log file group containing a member named 'DISKL:LOG6.LOG' to an archived redo log file in the location 'DISKA:[ARCH$]':

ALTER SYSTEM ARCHIVE LOG LOGFILE 'diskl:log6.log' TO 'diska:[arch$]'

Related Topics

ALTER SYSTEM command.

________________________________________

AUDIT (SQL Statements)

Purpose

To choose specific SQL statements for auditing in subsequent user sessions. To choose particular schema objects for auditing, use the AUDIT command (Schema Objects).

Prerequisites

You must have AUDIT SYSTEM system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of the users whose SQL statements you are auditing.

Syntax

Keywords and Parameters

statement_opt	chooses specific SQL statements for auditing. For a list of these statement options and the SQL statements they audit, see Table 4 - 7 on page 4 - 98 and Table 4 - 8 on page 4 - 100.

system_priv	chooses SQL statements that are authorized by the specified system privilege for auditing. For a list of all system privileges and the SQL statements that they authorize, see Table 6 - 1 on page 7 - 289.

BY user	chooses only SQL statements issued by specified users for auditing. If you omit this clause, ORACLE audits all users' statements.

BY SESSION	causes ORACLE to write a single record for all SQL statements of the same type issued in the same session.

BY ACCESS	causes ORACLE to write one record for each audited statement.

If you specify statement options or system privileges that audit Data Definition Language statements, ORACLE automatically audits by access regardless of whether you specify the BY SESSION or BY ACCESS option.

For statement options and system privileges that audit other types of SQL statements, you can specify either the BY SESSION or BY ACCESS option. BY SESSION is the default.

WHENEVER SUCCESSFUL	chooses auditing only for SQL statements that complete successfully.

NOT	chooses auditing only for statements that fail, or result in errors.

If you omit the WHENEVER clause, ORACLE audits SQL statements regardless of success or failure.

Auditing

Auditing keeps track of operations performed by database users. Foreach audited operation, ORACLE produces an audit record containingthis information:

•	user performing the operation

•	type of operation

•	object involved in the operation

•	date and time of the operation

ORACLE writes audit records to the audit trail. The audit trail is a database table that contains audit records. You can review database activity by examining the audit trail through data dictionary views. For information on these views, see Appendix B "Data Dictionary Reference"  of the ORACLE7 Server Administrator's Guide.

How to Audit

To generate audit records, you must perform these steps:

Enable auditing:      You must enable auditing with the initialization parameter AUDIT_TRAIL.

Specify auditing options:      To specify auditing options, you must use the AUDIT command. Auditing options choose which SQL commands, operations, database objects, and users ORACLE audits. After you specify auditing options, they appear in the data dictionary.   For more information on data dictionary views containing auditing options see Appendix B "Data Dictionary Reference" of the ORACLE7 Sercer Administrator's Guide.

Auditing options specified by the AUDIT command (SQL Statements) apply only to subsequent sessions, rather than to current sessions.

Statement Options

Table 4 - 7 lists the statement options and the statements that they audit.

Statement Option	SQL Statements and Operations

CLUSTER	CREATE CLUSTER

AUDIT CLUSTER

DROP CLUSTER

TRUNCATE CLUSTER

DATABASE LINK	CREATE DATABASE LINK

DROP DATABASE LINK

EXISTS	All SQL statements that fail be

cause an object, part of an object,

or valuse already exists in the da

tabase. This option is only avail

able with Trusted ORACLE.

INDEX	CREATE INDEX

ALTER INDEX

DROP INDEX

NOT EXISTS	All SQL statements that fail be

cause a specified object does not

exist.

PROCEDURE	CREATE FUNCTION

CREATE PACKAGE

CREATE PACKAGE BODY

CREATE PROCEDURE

DROP FUNCTION

DROP PACKAGE

DROP PROCEDURE

PROFILE	CREATE PROFILE

ALTER PROFILE

DROP PROFILE

PUBLIC DATABASE LINK	CREATE PUBLIC DATABASE

LINK

DROP PUBLIC DATABASE

LINK

PUBLIC SYNONYM	CREATE PUBLIC SYNONYM

DROP PUBLIC SYNONYM

ROLE	CREATE ROLE

ALTER ROLE

DROP ROLE

SET ROLE

ROLLBACK STATEMENT	CREATE ROLLBACK SEGMENT

ALTER ROLLBACK SEGMENT

DROP ROLLBACK SEGMENT

SEQUENCE	CREATE SEQUENCE

DROP SEQUENCE

SESSION	Logons

SYNONYM	CREATE SYNONYM

DROP SYNONYM

SYSTEM AUDIT	AUDIT (SQL Statements)

NOAUDIT (SQL Statements)

SYSTEM GRANT	GRANT (System Priviledges and

Roles)

REVOKE (System Privileges and

Roles)

TABLE	CREATE TABLE

DROP TABLE

TRUNCATE TABLE

TABLESPACE	CREATE TABLESPACE

ALTER TABLESPACE

DROP TABLESPACE

USER	CREATE USER

ALTER USER

DROP USER

VIEW	CREATE VIEW

DROP VIEW

Table 4 - 7.  Statement Auditing Options

Short Cuts for System Privileges and Statement Options

ORACLE provides short cuts for specifying system privileges and statement options. With these shortcuts, you can specify auditing for multiple system privileges and statement options at once:

CONNECT	This short cut is equivalent to specifying the CREATE SESSION system privilege.

RESOURCE	This short cut is equivalent to specifying these system privileges:

•	ALTER SYSTEM

•	CREATE CLUSTER

•	CREATE DATABASE LINK

•	CREATE PROCEDURE

•	CREATE ROLLBACK SEGMENT

•	CREATE SEQUENCE

•	CREATE SYNONYM

•	CREATE TABLE

•	CREATE TABLESPACE

•	CREATE VIEW

DBA	This short cut is equivalent to the SYSTEM GRANT statement option and these system privileges:

•	AUDIT SYSTEM

•	CREATE PUBLIC DATABASE LINK

•	CREATE PUBLIC SYNONYM

•	CREATE ROLE

•	CREATE USER

ALL	This short cut is equivalent to specifying all statement options shown in Table 4 - 7, but not the additional statement options shown in Table 4 - 8.

ALL PRIVILEGES	This short cut is equivalent to specifying all system privileges.

Oracle Corporation encourages you to choose individual system privileges and statement options for auditing, rather than these short cuts. These short cuts may not be supported in future versions of ORACLE.

Additional Statement Options

Table 4 - 8 lists additional statement options and the SQL statements and operations that they audit. Note that these statement options are not included in the ALL short cut.

Statement Option	SQL Statements and Operations

ALTER SEQUENCE	ALTER SEQUENCE

ALTER TABLE	ALTER TABLE

COMMENT TABLE	COMMENT ON TABLE table,

view, snapshot

COMMENT ON COLUMN

table.column, view.column, snap

shot.column

DELETE TABLE	DELETE FROM table, view

EXECUTE PROCEDURE	Execution of any procedure or

function or access to any variable

or cursor inside a package.

GRANT PROCEDURE	GRANT priviledge ON proce

dure, function, package

REVOKE priviledge ON proce

dure, function, package

GRANT SEQUENCE	GRANT privilege ON sequence

REVOKE privilege ON sequence

GRANT TABLE	GRANT privilege ON table, view,

snapshot

REVOKE privilege ON table,

view, snapshot

INSERT TABLE	INSERT INTO table, view

LOCK TABLE	LOCK TABLE table, view

SELECT SEQUENCE	Any statement containing se

quence.CURRVAL or se

quence.NEXTVAL

SELECT TABLE	SELECT FROM table, view, snap

shot

UPDATE TABLE	UPDATE table, view

Table 4 - 8.  Additional Statement Auditing Options

Example I	To choose auditing for every SQL statement that creates, alters, drops, or sets a role, regardless of whether the statement completes successfully, issue this statement:

AUDIT ROLE

To choose auditing for every statement that successfully creates, alters, drops, or sets a role, issue this statement:

AUDIT ROLE

 	WHENEVER SUCCESSFUL

To choose auditing for every CREATE ROLE, ALTER ROLE, DROP ROLE, or SET ROLE statement that results in an ORACLE error, issue this statement:

AUDIT ROLE

 	WHENEVER NOT SUCCESSFUL

Example II	To choose auditing for any statement that queries or updates any table, issue this statement:

AUDIT SELECT TABLE, UPDATE TABLE

To choose auditing for statements issued by the users SCOTT and BLAKE that query or update a table or view, issue this statement:

AUDIT SELECT TABLE, UPDATE TABLE

 	BY scott, blake

Example III	To choose auditing for statements issued using the DELETE ANY TABLE system privilege, issue this statement:

AUDIT DELETE ANY TABLE

Related Topics

AUDIT (Schema Objects) and NOAUDIT (SQL Statements) commands.

________________________________________

AUDIT (Schema Objects)

Purpose

To choose a specific schema object for auditing. To choose particular SQL commands for auditing, use the AUDIT command (SQL Statements) described in the previous section of this chapter.

Prerequisites

The object you choose for auditing must be in your own schema or you must have AUDIT ANY system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the object's creation label or you must satisfy one of these criteria:

•	If the object's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the object's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

If the object's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

object_opt	specifies a particular operation for auditing.  Table 4 - 9 shows each object option and the types of objects for which it applies.

schema	is the schema containing the object chosen for auditing. If you omit schema, ORACLE assumes the object is in your own schema.

object	identifies the object chosen for auditing. The object must be one of these types:

•	table

•	view

•	sequence

•	stored procedure, function, or package

•	snapshot

You can also specify a synonym for a table, view, sequence, procedure, stored function, package, or snapshot.

DEFAULT	establishes the specified object options as default object options for subsequently created objects.

BY SESSION	means that ORACLE writes a single record for all operations of the same type on the same object issued in the same session.

BY ACCESS	means that ORACLE writes one record for each audited operation.

If you omit both of these options, ORACLE audits by session.

WHENEVER SUCCESSFUL	chooses auditing only for SQL statements that complete successfully.

NOT	chooses auditing only for statements that fail, or result in errors.

If you omit the WHENEVER clause entirely, ORACLE audits all SQL statements, regardless of success or failure.

Auditing

Auditing keeps track of operations performed by database users. Fora brief conceptual overview of auditing including how to enable auditing,see the AUDIT command (SQL Statements) described in the previous section of this chapter. Note that auditing options established by the AUDIT command (Schema Objects) apply to current sessions as well as to subsequent sessions.

Object Options

Table 4 - 9 shows the object options you can choose for each type of object.

Procedures

Functions

Object Option	Tables	Views	Sequences	Packages	Snapshots

ALTER	3	3

AUDIT	3	3	3	3

COMMENT	3	3

DELETE	3	3

EXECUTE	3

GRANT	3	3	3	3

INDEX	3

INSERT	3	3

LOCK	3	3

RENAME	3	3	3

SELECT	3	3	3	3

UPDATE	3	3

Table 4 - 9.  Object Auditing Options

The name of each object option specifies a command to be audited. For example, if you choose to audit a table with the ALTER option, ORACLE audits all ALTER TABLE statements issued against the table. If you choose to audit a sequence with the SELECT option, ORACLE audits all statements that use any of the sequence's values.

 Short Cuts for Object Options

ORACLE provides a short cut for specifying object auditing options:

 ALL	This short cut is equivalent to specifying all object options applicable for the type of object. You can use this short cut rather than explicitly specifying all options for an object.

Default Auditing

You can use the DEFAULT option of the AUDIT command to specify auditing options for objects that have not yet been created. Once you have established these default auditing options, any subsequently created object is automatically audited with those options. Note that the default auditing options for a view are always the union of the auditing options for the view's base tables.

If you change the default auditing options, the auditing options for previously-created objects remain the same. You can only change the auditing options for an existing object by specifying the object in the ON clause of the AUDIT command.

Example I	To choose auditing for every SQL statement that queries the EMP table in the schema SCOTT, issue this statement:

AUDIT SELECT

 	ON scott.emp

To choose auditing for every statement that successfully queries the EMP table in the schema SCOTT, issue this statement:

AUDIT SELECT

ON scott.emp

 	WHENEVER SUCCESSFUL

To choose auditing for every statement that queries the EMP table in the schema SCOTT and results in an ORACLE error, issue this statement:

AUDIT SELECT

ON scott.emp

 	WHENEVER NOT SUCCESSFUL

Example II	To choose auditing for every statement that inserts or updates a row in the DEPT table in the schema BLAKE, issue this statement:

AUDIT INSERT, UPDATE

 	ON blake.dept

Example III	To choose auditing for every statement that performs any operation on the ORDER sequence in the schema ADAMS, issue this statement:

AUDIT ALL

 	ON adams.order

This statement uses the ALL short cut to choose auditing for these statements that operate on the sequence:

•	ALTER SEQUENCE

•	AUDIT

•	GRANT

•	any statement that accesses the sequence's values using the pseudocolumns CURRVAL or NEXTVAL

Example IV	This statement specifies default auditing options for objects created in the future:

AUDIT ALTER, GRANT, INSERT, UPDATE, DELETE

 	ON DEFAULT

Any objects created later are automatically audited with the specified options that apply to them, provided that auditing has been enabled:

•	If you create a table, ORACLE automatically audits any ALTER, INSERT, UPDATE, or DELETE statements issued against the table.

•	If you create a view, ORACLE automatically audits any INSERT, UPDATE, or DELETE statements issued against the view.

•	If you create a sequence, ORACLE automatically audits any ALTER statements issued against the sequence.

•	If you create a procedure, package, or function, ORACLE automatically audits any ALTER statements issued against it.

Related Topics

AUDIT (SQL Statements) and NOAUDIT (Schema Objects) commands.

________________________________________

CLOSE (Embedded SQL)

Purpose

To disable a cursor, freeing the resources acquired by opening the cursor, and releasing parse locks.

Prerequisites

 The cursor must be already open.

Syntax

Keywords and Parameters

cursor	is the cursor to be closed. The cursor must currently be open.

Usage Notes

 Rows cannot be fetched from a closed cursor. A cursor need not beclosed to be reopened. The HOLD_CURSOR and RELEASE_CURSOR precompiler options alter the effect of the CLOSE command. For information on these options, see the Programmer's Guide to the ORACLE Precompilers.

Example	This example illustrates the use of the CLOSE command:

EXEC SQL CLOSE emp_cursor

Related Topics

PREPARE, DECLARE CURSOR, and OPEN commands.

________________________________________

COMMENT

Purpose

To add a comment about a table, view, snapshot, or column into the data dictionary.

Prerequisites

The table, view, or snapshot must be in your own schema or you must have COMMENT ANY TABLE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the creation label of the table, view, snapshot, or column.

Syntax

Keywords and Parameters

TABLE	specifies the schema and name of the table, view, or snapshot to be commented.

COLUMN	specifies the name of the column of a table, view, or snapshot to be commented.

If you omit schema, ORACLE assumes the table, view, or snapshot is in your own schema.

IS 'text'	is the text of the comment. See the syntax description of 'text'  on page 2 - 17.

Usage Notes

You can effectively drop a comment from the database by setting itto the empty string ''.   For information on the data dictionary viewsthat contain comments, see Appendix B "Data Dictionary Reference" of the ORACLE7 Server Administrator's Guide.

Example	To insert an explanatory remark on the NOTES column of the SHIPPING table, you might issue this statement:

COMMENT ON COLUMN shipping.notes

IS 'Special packing or shipping instructions'

To drop this comment from the database, issue this statement:

COMMENT ON COLUMN shipping.notes IS ''

Related Topics

The section "Comments" on page 2 - 42.


CHAPTER 5. COMMANDS - COMMITTO CREATE ROLE

________________________________________

COMMIT

Purpose

To end your current transaction and make permanent all changes performed in the transaction. This command also erases all savepoints in the transaction and releases the transaction's locks.

You can also use this command to manually commit an in-doubt distributed transaction.

Prerequisites

You need no privileges to commit your current transaction.

To manually commit a distributed in-doubt transaction that you originally committed, you must have FORCE TRANSACTION system privilege. To manually commit a distributed in-doubt transaction that was originally committed by another user, you must have FORCE ANY TRANSACTION system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, you can only commit an in-doubt transaction if your DBMS label matches the label the transaction's label and the creation label of the user who originally committed the transaction or if you satisfy one of these criteria:

•	If the transaction's label or the user's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the transaction's label or the user's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the transaction's label or the user's creation label is noncomparable with your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

WORK	is supported only for compliance with standard SQL. The statements COMMIT and COMMIT WORK are equivalent.

COMMENT 	specifies a comment to be associated with the current transaction. The 'text' is a quoted literal of up to 50 characters that ORACLE stores in the data dictionary view DBA_2PC_PENDING along with the transaction ID if the transaction becomes in-doubt.

FORCE	manually commits an in-doubt distributed transaction. The transaction is identified by the 'text' containing its local or global transaction ID. To find the IDs of such transactions, query the data dictionary view DBA_2PC_PENDING. You can also use the integer to specifically assign the transaction a system change number (SCN). If you omit the integer, the transaction is committed using the current SCN.

COMMIT statements using the FORCE clause are not supported in PL/SQL.

Usage Notes

Oracle Corporation recommends that you explicitly end every transactionin your application programs with a COMMIT or ROLLBACK statement,including the last transaction, before disconnecting from ORACLE. If you do not explicitly commit the transaction and the program terminates abnormally, the last uncommitted transaction is automatically rolled back.

A normal exit from most ORACLE utilities and tools causes the current transaction to be committed. A normal exit from an ORACLE Precompiler program does not commit the transaction and relies on ORACLE to rollback the current transaction. See the COMMIT command (Embedded SQL) in the next section.

Transactions

A transaction (or a logical unit of work) is a sequence of SQL statements that ORACLE treats as a single unit. A transaction begins with the first executable SQL statement after a COMMIT, ROLLBACK or connection to the database. A transaction ends with a COMMIT, ROLLBACK or disconnection (intentional or unintentional) from the database. Note that ORACLE issues an implicit COMMIT before and after any Data Definition Language statement.

You can also use a COMMIT or ROLLBACK statement to terminate a read only transaction begun by a SET TRANSACTION statement.

Example I	This example inserts a row into the DEPT table and commits this change:

INSERT INTO dept 	VALUES (50, 'MARKETING', 'TAMPA')

COMMIT WORK

Example II	This statement commits the current transaction and associates a comment with it:

COMMIT WORK

COMMENT 'In-doubt transaction Code 36, Call (415) 555-2637'

If a network or machine failure prevents this distributed transaction from committing properly, ORACLE stores the comment in the data dictionary along with the transaction ID. The comment indicates the part of the application in which the failure occurred and provides information for contacting the administrator of the database where the transaction was committed.

 Distributed Transactions

ORACLE with the distributed option allows you to perform distributed transactions, or transactions that modify data on multiple databases. To commit a distributed transaction, you need only issue a COMMIT statement as you would to commit any other transaction. Each component of the distributed transaction is then committed on each database.

In the event of a network or machine failure during the commit process for a distributed transaction, the state of the transaction may be unknown, or in-doubt. After consultation with the administrators of the other databases involved in the transaction, you may decide to manually commit or roll back the transaction on your local database. You can manually commit the transaction on your local database by using the FORCE clause of the COMMIT command. For more information on these topics, see Chapter 15 "Managing Distributed Databases" of the ORACLE7 Server Administrator's Guide.

Note that a COMMIT statement with a FORCE clause only commits the specified transaction. Such a statement does not affect your current transaction.

Example III	This statement manually commits an in-doubt distributed transaction:

COMMIT

FORCE '22.57.53'

Related Topics

COMMIT (Embedded SQL), ROLLBACK, SAVEPOINT and SET TRANSACTION commands.

________________________________________

COMMIT (Embedded SQL)

Purpose

To end your current transaction, making permanent all its changes  to the database and optionally freeing all resources and disconnecting from ORACLE.

Prerequisites

To commit your current transaction, no privileges are necessary.

To manually commit a distributed in-doubt transaction that you originally committed, you must have FORCE TRANSACTION system privilege. To manually commit a distributed in-doubt transaction that was originally committed by another user, you must have FORCE ANY TRANSACTION system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, you can only commit an in-doubt transaction if your DBMS label matches the label the transaction's label and the creation label of the user who originally committed the transaction or if you satisfy one of these criteria:

•	If the transaction's label or the user's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the transaction's label or the user's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the transaction's label or the user's creation label is noncomparable with your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keyword and Parameters

AT	identifies the database to which the COMMIT statement is issued. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, ORACLE issues the statement to your default database.

WORK	is supported only for compliance with standard SQL. The statements COMMIT and COMMIT WORK are equivalent.

COMMENT 	specifies a comment to be associated with the current transaction. The 'text' is a quoted literal of up to 50 characters that ORACLE stores in the data dictionary view DBA_2PC_PENDING along with the transaction ID if the transaction becomes in-doubt.

RELEASE	frees all resources and disconnects you  from ORACLE.

FORCE	manually commits an in-doubt distributed transaction. The transaction is identified by the 'text' containing its local or global transaction ID. To find the IDs of such transactions, query the data dictionary view DBA_2PC_PENDING. You can also use the optional integer to explicitly assign the transaction a system change number (SCN). If you omit the integer, the transaction is committed using the current SCN.

Usage Notes

Always explicitly commit or rollback the last transaction in yourprogram by using the COMMIT or ROLLBACK command and the RELEASE option. ORACLEautomatically rolls back changes if the program terminates abnormally.

The COMMIT command has no effect on host variables or on the flow of control in the program. For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example	This example illustrates the use of the embedded SQL COMMIT command:

EXEC SQL AT sales_db COMMIT RELEASE

Related Topics

COMMIT, ROLLBACK, SAVEPOINT, and SET TRANSACTION commands.

________________________________________

CONNECT (Embedded SQL)

Purpose

To log on to an ORACLE database.

Prerequisites

You must have CREATE SESSION system privilege in the specified database.

If you are using Trusted ORACLE in DBMS MAC mode, your operating system label must dominate both your creation label and the label at which you were granted CREATE SESSION system privilege. Your operating system label must also fall between the operating system equivalents of DBHIGH and DBLOW, inclusive.

If you are using Trusted ORACLE in OS MAC mode, your operating system label must match the label of the database to which you are connecting.

Syntax

Keyword and Parameters

:user :password	specifies your username and password separately.

:user_password	is a single host variable containing the ORACLE username and password separated by a slash (/).

To allow ORACLE to verify your connection through your operating system, specify a :user_password value of '/'.

AT	identifies the database to which the connection is made. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

USING	specifies the SQL*Net database specification string used to connect to a non-default database. If you omit this clause, you are connected to your default database.

Usage Notes

A program can have multiple connections, but can only connect onceto your default database.  For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example	The following example illustrate the use of CONNECT:

EXEC SQL CONNECT :username

IDENTIFIED BY :password

You can also use this statement in which the value of :userid is the value of :username and :password separated by a "/" such as 'SCOTT/TIGER':

EXEC SQL CONNECT :userid

Related Topics

COMMIT, DECLARE DATABASE, and ROLLBACK commands.

________________________________________

CONSTRAINT clause

Purpose

To define an integrity constraint. An integrity constraintis a rule that restricts the values for one or more columns in a table.

Prerequisites

CONSTRAINT clauses can appear in either CREATE TABLE or ALTER TABLE commands. To define an integrity constraint, you must have the privileges necessary to issue one of these commands. See the CREATE TABLE and ALTER TABLE commands in this chapter.

Defining a constraint may also require additional privileges or preconditions that depend on the type of constraint. For information on these privileges, see the descriptions of each type of integrity constraint later in this section.

Syntax

Keywords and Parameters

CONSTRAINT	identifies the integrity constraint by the name constraint. ORACLE stores this name in the data dictionary along with the definition of the integrity constraint. If you omit this identifier, ORACLE generates a name with this form:

SYS_Cn 	where n is an integer that makes the name unique within the database. For the names and definitions of integrity constraints, query the data dictionary. For information on data dictionary views that contain constraints, see Appendix D "Data Dictionary Reference" of the ORACLE7 Server Application Developer's Guide.

NULL	specifies that a column can contain null values.

NOT NULL	specifies that a column cannot contain null values.

If you do not specify NULL or NOT NULL in a column definition, NULL is the default.

UNIQUE	designates a column or combination of columns as a unique key.

PRIMARY KEY	designates a column or combination of columns as the table's primary key.

FOREIGN KEY	designates a column or combination of columns as the foreign key in a referential integrity constraint.

REFERENCES	identifies the primary or unique key that is referenced by a foreign key in a referential integrity constraint.

ON DELETE CASCADE	specifies that ORACLE maintains referential integrity by automatically removing dependent foreign key values if you remove a referenced primary or unique key value.

CHECK	specifies a condition that each row in the table must satisfy.

USING INDEX	specifies parameters for the index ORACLE uses to enforce a UNIQUE or PRIMARY KEY constraint. The name of the index is the same as the name of the constraint. For information on these parameters, see the CREATE TABLE command later in this chapter.

Only use this clause when enabling UNIQUE and PRIMARY KEY constraints.

EXCEPTIONS INTO	identifies a table into which ORACLE places information about rows that violate an enabled integrity constraint. This table must exist before you use this option. If you omit schema, ORACLE assumes the exception table is in your own schema. The exception table must be on your local database.

If a CREATE TABLE statement contains both the AS clause and a CONSTRAINT clause with the EXCEPTIONS option, ORACLE ignores the EXCEPTIONS option. If any rows violate the integrity constraint, ORACLE does not create the table and returns an error message.

DISABLE	disables the integrity constraint. If an integrity constraint is disabled, ORACLE does not enforce it. If you do not specify this option, ORACLE automatically enables the integrity constraint.

You can also enable and disable integrity constraints with the ENABLE and DISABLE clauses of the CREATE TABLE and ALTER TABLE commands. See the ENABLE and DISABLE clauses on pages 7 - 263 and 6 - 235, respectively.

Defining Integrity Constraints

To define an integrity constraint, include a CONSTRAINT clause ina CREATE TABLE or ALTER TABLE statement. The CONSTRAINT clause hastwo syntactic forms:

table_constraintsyntax	The table_constraint syntax is part of the table definition. An integrity constraint defined with this syntax can impose rules on any columns in the table.

The table_constraint syntax can appear in a CREATE TABLE or ALTER TABLE statement. This syntax can define any type of integrity constraint except a NOT NULL constraint.

column_constraintsyntax	The column_constraint syntax is part of a column definition. In most cases, an integrity constraint defined with this syntax can only impose rules on the column in which it is defined.

Column_constraint syntax that appears in a CREATE TABLE statement can define any type of integrity constraint. Column_constraint syntax that appears in an ALTER TABLE statement can only define or remove a NOT NULL constraint.

The table_constraint syntax and the column_constraint syntax are simply different syntactic means of defining integrity constraints. There is no functional difference between an integrity constraint defined with table_constraint syntax and the same constraint defined with column_constraint syntax.

NOT NULL Constraints

The NOT NULL constraint specifies that a column cannot contain nulls. To satisfy this constraint, every row in the table must contain a value for the column.

The NULL keyword indicates that a column can contain nulls. It does not actually define an integrity constraint. If you do not specify either NOT NULL or NULL, the column can contain nulls by default.

You can only specify NOT NULL or NULL with column_constraint syntax in a CREATE TABLE or ALTER TABLE statement, not with table_constraint syntax.

Example I	This statement alters the EMP table and defines and enables a NOT NULL constraint on the SAL column:

ALTER TABLE emp

MODIFY (sal  NUMBER  CONSTRAINT nn_sal NOT NULL)

NN_SAL ensures that no employee in the table has a null salary.

UNIQUE Constraints

The UNIQUE constraint designates a column or combination of columns as a unique key. To satisfy a UNIQUE constraint, no two rows in the table can have the same value for the unique key. However, the unique key made up of a single column can contain nulls.

A unique key column cannot be of datatype LONG or LONG RAW. You cannot designate the same column or combination of columns as both a unique key and a primary key or as both a unique key and a cluster key. However, you can designate the same column or combination of columns as both a unique key and a foreign key.

 Defining Unique Keys

You can define a unique key on a single column with column_constraint syntax.

Example II	This statement creates the DEPT table and defines and enables a unique key on the DNAME column:

CREATE TABLE dept

   (deptno  NUMBER(2),

    dname   VARCHAR2(9)  CONSTRAINT unq_dname UNIQUE,

    loc     VARCHAR2(10) )

The constraint UNQ_DNAME identifies the DNAME column as a unique key. This constraint ensures that no two departments in the table have the same name. However, the constraint does allow departments without names.

Alternatively, you can define and enable this constraint with the table_constraint syntax:

CREATE TABLE dept

   (deptno  NUMBER(2),

    dname   VARCHAR2(9),

    loc     VARCHAR2(10),

   CONSTRAINT unq_dname

     UNIQUE (dname)

     USING INDEX PCTFREE 20  TABLESPACE user_x                	     STORAGE (INITIAL 8K  NEXT 6K) )

This statement also uses the USING INDEX option to specify storage characteristics for the index that ORACLE creates to enforce the constraint.

 Defining Composite Unique Keys

A composite unique key is a unique key made up of a combination of columns. Since ORACLE creates an index on the columns of a unique key, a composite unique key can contain a maximum of 16 columns. To define a composite unique key, you must use table_constraint syntax, rather than column_constraint syntax.

To satisfy a constraint that designates a composite unique key, no two rows in the table can have the same combination of values in the key columns. Also, any row that contains nulls in all key columns automatically satisfies the constraint. However, two rows that contain nulls for one or more key columns and the same combination of values for the other key columns violate the constraint.

Example III	This statement defines and enables a composite unique key on the combination of the CITY and STATE columns of the CENSUS table:

ALTER TABLE census

   ADD CONSTRAINT unq_city_state

         UNIQUE (city, state)

         USING INDEX PCTFREE 5  TABLESPACE user_y 	      EXCEPTIONS INTO bad_keys_in_ship_cont

The UNQ_CITY_STATE constraint ensures that the same combination of CITY and STATE values does not appear in the table more than once.

The CONSTRAINT clause also specifies other properties of the constraint:

•	The USING INDEX option specifies storage characteristics for the index ORACLE creates to enforce the constraint.

•	The EXCEPTIONS option causes ORACLE to write information to the BAD_KEYS_IN_SHIP_CONT table about any rows currently in the SHIP_CONT table that violate the constraint.

PRIMARY KEY Constraints

A PRIMARY KEY constraint designates a column or combination of columns as the table's primary key. To satisfy a PRIMARY KEY constraint, both of these conditions must be true:

•	No primary key value can appear in more than one row in the table.

•	No column that is part of the primary key can contain a null.

A table can have only one primary key.

A primary key column cannot be of datatype LONG or LONG RAW. You cannot designate the same column or combination of columns as both a primary key and a unique key or as both a primary key and a cluster key. However, you can designate the same column or combination of columns as both a primary key and a foreign key.

 Defining Primary Keys

You can use the column_constraint syntax to define a primary key on a single column.

Example IV	This statement creates the DEPT table and defines and enables a primary key on the DEPTNO column:

CREATE TABLE dept

   (deptno   NUMBER(2)      CONSTRAINT pk_dept PRIMARY KEY,

   dname   VARCHAR2(9), 	 loc     VARCHAR2(10) )

The PK_DEPT constraint identifies the DEPTNO column as the primary key of the DEPTNO table. This constraint ensures that no two departments in the table have the same department number and that no department number is NULL.

Alternatively, you can define and enable this constraint with table_constraint syntax:

CREATE TABLE dept

(deptno  NUMBER(2),

 dname   VARCHAR2(9),

 loc   VARCHAR2(10),

 CONSTRAINT pk_dept PRIMARY KEY (deptno) )

 Defining Composite Primary Keys

A composite primary key is a primary key made up of a combination of columns. Because ORACLE creates an index on the columns of a primary key, a composite primary key can contain a maximum of 16 columns. To define a composite primary key, you must use the table_constraint syntax, rather than the column_constraint syntax.

Example V	This statement defines a composite primary key on the combination of the SHIP_NO and CONTAINER_NO columns of the SHIP_CONT table:

ALTER TABLE ship_cont

ADD PRIMARY KEY (ship_no, container_no) DISABLE

This constraint identifies the combination of the SHIP_NO and CONTAINER_NO columns as the primary key of the SHIP_CONTAINER. The constraint ensures that no two rows in the table have the same values for both the SHIP_NO column and the CONTAINER_NO column.

The CONSTRAINT clause also specifies these properties of the constraint:

•	Since the constraint definition does not include a constraint name, ORACLE generates a name for the constraint.

•	The DISABLE option causes ORACLE to define the constraint but not enforce it.

Referential Integrity Constraints

A referential integrity constraint designates a column or combination of columns as a foreign key and establishes a relationship between that foreign key and a specified primary or unique key, called the referenced key. In this relationship, the table containing the foreign key is called the child table and the table containing the referenced key is called the parent table. Note these caveats:

•	The child and parent tables must be on the same database. They cannot be on different nodes of a distributed database. ORACLE allows you to enforce referential integrity across nodes of a distributed database with database triggers. For information on how to use database triggers for this purpose, see Chapter 8 "Using Database Triggers"of the ORACLE7 Server Application Developer's Guide.

•	The foreign key and the referenced key can be in the same table. In this case, the parent and child tables are the same.

To satisfy a referential integrity constraint, each row of the child table must meet one of these conditions:

•	The value of the row's foreign key must appear as a referenced key value in one of the parent table's rows. The row in the child table is said to depend on the referenced key in the parent table.

•	The value of one of the columns that makes up the foreign key must be null.

A referential integrity constraint is defined in the child table. A referential integrity constraint definition can include any of these keywords:

FOREIGN KEY	identifies the column or combination of columns in the child table that makes up of the foreign key. Only use this keyword when you define a foreign key with a table constraint clause.

REFERENCES	identifies the parent table and the column or combination of columns that make up the referenced key.

If you only identify the parent table and omit the column names, the foreign key automatically references the primary key of the parent table.

The corresponding columns of the referenced key and the foreign key must match in number and datatypes.

ON DELETE CASCADE	allows deletion of referenced key values in the parent table that have dependent rows in the child table and causes ORACLE to automatically delete dependent rows from the child table to maintain referential integrity.

If you omit this option, ORACLE forbids deletions of referenced key values in the parent table that have dependent rows in the child table.

Before you define a referential integrity constraint in the child table, the referenced UNIQUE or PRIMARY KEY constraint on the parent table must already be defined. Also, the parent table must be in your own schema or you must have REFERENCES privilege on the columns of the referenced key in the parent table. Before you enable a referential integrity constraint, its referenced constraint must be enabled.

You cannot define a referential integrity constraint in a CREATE TABLE statement that contains an AS clause. Instead, you can create the table without the constraint and then add it later with an ALTER TABLE statement.

A foreign key column cannot be of datatype LONG or LONG RAW. You can designate the same column or combination of columns as both a foreign key and a primary or unique key. You can also designate the same column or combination of columns as both a foreign key and a cluster key.

You can define multiple foreign keys in a table. Also, a single column can be part of more than one foreign key.

 Defining Referential Integrity Constraints

You can use column_constraint syntax to define a referential integrity constraint in which the foreign key is made up of a single column.

Example VI	This statement creates the EMP table and defines and enables a foreign key on the DEPTNO column that references the primary key on the DEPTNO column of the DEPT table:

CREATE TABLE emp

(empno     NUMBER(4),

 ename     VARCHAR2(10),

 job       VARCHAR2(9),

 mgr       NUMBER(4),

 hiredate  DATE,

 sal       NUMBER(7,2),

 comm      NUMBER(7,2),

 deptno    CONSTRAINT fk_deptno REFERENCES dept(deptno) )

The constraint FK_DEPTNO ensures that all employees in the EMP table work in a department in the DEPT table. However, employees can have null department numbers.

Before you define and enable this constraint, you must define and enable a constraint that designates the DEPTNO column of the DEPT table as a primary or unique key. For the definition of such a constraint, see Example IV.

Note that the referential integrity constraint definition does not use the FOREIGN KEY keyword to identify the columns that make up the foreign key. Because the constraint is defined with a column constraint clause on the DEPTNO column, the foreign key is automatically on the DEPTNO column.

Note that the constraint definition identifies both the parent table and the columns of the referenced key. Because the referenced key is the parent table's primary key, the referenced key column names are optional.

Note that this statement omits the DEPTNO column's datatype. Because this column is a foreign key, ORACLE automatically assigns it the datatype of the DEPT.DEPTNO column to which the foreign key refers.

Alternatively, you can define a referential integrity constraint with table_constraint syntax:

CREATE TABLE emp

  (empno     NUMBER(4),

   ename     VARCHAR2(10),

   job       VARCHAR2(9),

   mgr       NUMBER(4),

   hiredate  DATE,

   sal       NUMBER(7,2),

   comm      NUMBER(7,2),

   deptno,

   CONSTRAINT fk_deptno

      FOREIGN KEY (deptno)

   REFERENCES dept(deptno) )

Note that the foreign key definitions in both of these statements omit the ON DELETE CASCADE option, causing ORACLE to forbid the deletion of a department if any employee works in that department.

 Maintaining Referential Integrity with the ON DELETE CASCADE Option

If you use the ON DELETE CASCADE option, ORACLE permits deletions of referenced key values in the parent table and automatically deletes dependent rows in the child table to maintain referential integrity.

Example VII	This example creates the EMP table, defines and enables the referential integrity constraint FK_DEPTNO, and uses the ON DELETE CASCADE option:

CREATE TABLE emp

  (empno     NUMBER(4),

   ename     VARCHAR2(10),

   job       VARCHAR2(9),

   mgr       NUMBER(4),

   hiredate  DATE,

   sal       NUMBER(7,2),

   comm      NUMBER(7,2),

   deptno    NUMBER(2)

             CONSTRAINT fk_deptno

             REFERENCES dept(deptno)

         ON DELETE CASCADE )

Because of the ON DELETE CASCADE option, ORACLE cascades any deletion of a DEPTNO value in the DEPT table to the DEPTNO values of its dependent rows of the EMP table. For example, if department 20 is deleted from the DEPT table, ORACLE deletes the department's employees from the EMP table.

 Referential Integrity Constraints with Composite Keys

A composite foreign key is a foreign key made up of a combination of columns. A composite foreign key can contain as many as 16 columns. To define a referential integrity constraint with a composite foreign key, you must use table_constraint syntax. You cannot use column_constraint syntax because this syntax can only impose rules on a single column. A composite foreign key must refer to a composite unique key or a composite primary key.

To satisfy a referential integrity constraint involving composite keys, each row in the child table must satisfy one of these conditions:

•	The values of the foreign key columns must match the values of the referenced key columns in a row in the parent table.

•	The value of at least one of the columns of the foreign key must be null.

Example IX	This statement defines and enables a foreign key on the combination of the AREACO and PHONENO columns of the PHONE_CALLS table:

ALTER TABLE phone_calls

   ADD CONSTRAINT fk_areaco_phoneno

      FOREIGN KEY (areaco, phoneno)

      REFERENCES customers(areaco, phoneno)

      EXCEPTIONS INTO wrong_numbers

The constraint FK_AREACO_PHONENO ensures that all the calls in the PHONE_CALLS table are made from phone numbers that are listed in the CUSTOMERS table. Before you define and enable this constraint, you must define and enable a constraint that designates the combination of the AREACO and PHONENO columns of the CUSTOMERS table as a primary or unique key.

The EXCEPTIONS option causes ORACLE to write information to the WRONG_NUMBERS about any rows in the PHONE_CALLS table that violate the constraint.

CHECK Constraints

The CHECK constraint explicitly defines a condition. To satisfy the constraint, each row in the table must make the condition either TRUE or unknown (due to a null). For information on conditions, see the syntax description of condition on page NO TAG. The condition of a CHECK constraint can refer to any column in the table, but it cannot refer to columns of other tables. CHECK constraint conditions cannot contain these constructs:

•	queries to refer to values in other rows

•	calls to the functions SYSDATE, UID, USER, or USERENV

•	the pseudocolumns CURRVAL, NEXTVAL, LEVEL, or ROWNUM

•	date constants that are not fully specified

Whenever ORACLE evaluates a CHECK constraint condition for a particular row, any column names in the condition refer to the column values in that row.

If you create multiple CHECK constraints for a column, design them carefully so their purposes do not conflict. ORACLE does not verify that CHECK conditions are not mutually exclusive.

Example X	This statement creates the DEPT table and defines a CHECK constraint in each of the table's columns:

CREATE TABLE dept

(deptno  NUMBER

         CONSTRAINT check_deptno

           CHECK (deptno BETWEEN 10 AND 99)

           DISABLE,

 dname   VARCHAR2(9)

         CONSTRAINT check_dname

           CHECK (dname = UPPER(dname))

           DISABLE,

 loc     VARCHAR2(10)

         CONSTRAINT check_loc

           CHECK (loc IN ('DALLAS','BOSTON','NEW YORK','CHICAGO'))

           DISABLE)

Each constraint restricts the values of the column in which it is defined:

CHECK_DEPTNO	ensures that no department numbers are less than 10 or greater than 99.

CHECK_DNAME	ensures that all department names are in uppercase.

CHECK_LOC	restricts department locations to Dallas, Boston, New York, or Chicago.

Unlike other types of constraints, a CHECK constraint defined with column_constraint syntax can impose rules on any column in the table, rather than only on the column in which it is defined.

Because each CONSTRAINT clause contains the DISABLE option, ORACLE only defines these constraints and does not enforce them.

Example XI	This statement creates the EMP table and uses a column constraint clause to define and enable a CHECK constraint:

CREATE TABLE emp

  (empno     NUMBER(4),

   ename     VARCHAR2(10),

   job       VARCHAR2(9),

   mgr       NUMBER(4),

   hiredate  DATE,

   sal       NUMBER(7,2)  CHECK (sal + comm <= 5000),

   comm      NUMBER(7,2),

   deptno    NUMBER(2) )

This constraint uses an inequality condition to limit an employee's total compensation, the sum of salary and commission, to $5000:

•	If an employee has non-null values for both salary and commission, the sum of these values must not be more than $5000 to satisfy the constraint.

•	If an employee has a null salary or commission, the result of the condition is unknown and the employee automatically satisfies the constraint.

Because the CONSTRAINT clause in this example does not supply a constraint name, ORACLE generates a name for the constraint.

Alternatively, you can define and enable this constraint with table_constraint syntax:

CREATE TABLE emp

(empno     NUMBER(4),

 ename     VARCHAR2(10),

 job       VARCHAR2(9),

 mgr       NUMBER(4),

 hiredate  DATE,

 sal       NUMBER(7,2),

 comm      NUMBER(7,2),

 deptno    NUMBER(2), 	 CHECK (sal + comm <= 5000) )

Example XII	This statement defines and enables a PRIMARY KEY constraint, two referential integrity constraints, a NOT NULL constraint, and two CHECK constraints:

CREATE TABLE order_detail

(CONSTRAINT pk_od PRIMARY KEY (order_id, part_no),

 order_id  NUMBER

           CONSTRAINT fk_oid REFERENCES scott.order (order_id),

 part_no   NUMBER

           CONSTRAINT fk_pno REFERENCES scott.part (part_no),

 quantity  NUMBER

           CONSTRAINT nn_qty NOT NULL

           CONSTRAINT check_qty_low CHECK (quantity > 0),

 cost      NUMBER

           CONSTRAINT check_cost CHECK (cost > 0) )

The constraints enforce these rules on table data:

PK_OD	identifies the combination of the ORDER_ID and PART_NO columns as the primary key of the table. To satisfy this constraint, these conditions must be true:

•	No two rows in the table can contain the same combination of values in the ORDER_ID and the PART_NO columns.

•	No row in the table can have a null in either the ORDER_ID column or the PART_NO column.

FK_OID	identifies the ORDER_ID column as a foreign key that references the ORDER_ID column in the ORDER table in SCOTT's schema. All new values added to the column ORDER_DETAIL.ORDER_ID must already appear in the column SCOTT.ORDER.ORDER_ID.

FK_PNO	identifies the PART_NO column as a foreign key that references the PART_NO column in the PART table owned by SCOTT. All new values added to the column ORDER_DETAIL.PART_NO must already appear in the column SCOTT.PART.PART_NO.

NN_QTY	forbids nulls in the QUANTITY column.

CHECK_QTY	ensures that values in the QUANTITY column are always greater than 0.

CHECK_COST	ensures the values in the COST column are always greater than 0.

This example also illustrates these points about constraint clauses and column definitions:

•	Table_constraint syntax and column definitions can appear in any order. In this example, note that the table_constraint syntax that defines the PK_OD constraint precedes the column definitions. In Example IV in this section, the table_constraint syntax defining the table's primary key follows the column definitions.

•	A column definition can use column_constraint syntax multiple times. In this example, the definition of the QUANTITY column contains the definitions of both the NN_QTY and CHECK_QTY constraints.

•	A table can have multiple CHECK constraints. Multiple CHECK constraints, each with a simple condition enforcing a single business rule is better than a single CHECK constraint with a complicated condition enforcing multiple business rules. When a constraint is violated, ORACLE returns an error message identifying the constraint. Such an error message more precisely identifies the violated business rule if the identified constraint enforces a single business rule.

Related Topics

CREATE TABLE and ALTER TABLE commands; ENABLE and DISABLE clauses; column element.

________________________________________

CREATE CLUSTER

Purpose

To create a cluster. A cluster is a schema object that contains one or more tables that all have one or more columns in common.

Prerequisites

To create a cluster in your own schema, you must have CREATE CLUSTER system privilege. To create a cluster in another user's schema, you must have CREATE ANY CLUSTER system privilege. Also, the owner of the schema to contain the cluster must have either space quota on the tablespace containing the cluster or UNLIMITED TABLESPACE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the label of the tablespace to contain the cluster. To create a cluster in another user's schema, your DBMS label must dominate the creation label of the owner of the schema.

Syntax

Keywords and Parameters

schema	is the schema to contain the cluster. If you omit schema, ORACLE creates the cluster in your current schema.

cluster 	is the name of the cluster to be created.

column 	is the name of a column of the cluster key.

datatype	is the datatype of a cluster key column. A cluster key column can have any internal datatype except LONG or LONG RAW. For information on datatypes, see the section "Datatypes" on page 2 - 21.

PCTUSED	specifies the limit that ORACLE uses to determine when additional rows can be added to a cluster's data block. The value of this parameter is expressed as a whole number and interpreted as a percentage.

PCTFREE	specifies the space reserved in each of the cluster's data blocks for future expansion. The value of the parameter is expressed as a whole number and interpreted as a percentage.

INITRANS	specifies the initial number of concurrent update transactions allocated for data blocks of the cluster. The value of this parameter for a cluster cannot be less than 2 or more than the value of the MAXTRANS parameter. The default value is the greater of the INITRANS value for the cluster's tablespace and 2.

MAXTRANS	specifies the maximum number of concurrent update transactions for any given data block belonging to the cluster. The value of this parameter cannot be less than the value of the INITRANS parameter. The maximum value of this parameter is 255. The default value is the MAXTRANS value for the tablespace to contain the cluster.

For a complete description of the PCTUSED, PCTFREE, INITRANS, and MAXTRANS parameters, see the CREATE TABLE command later in this chapter.

SIZE	specifies the amount of space in bytes to store all rows with the same cluster key value or the same hash value. You can use K or M to specify this space in kilobytes or megabytes. The value of this parameter cannot exceed the size of a data block. If you omit this parameter, ORACLE reserves one data block for each cluster key value or hash value.

TABLESPACE	specifies the tablespace in which the cluster is created.

STORAGE	specifies how data blocks are allocated to the cluster. See the STORAGE clause on page 8 - 371.

INDEX	creates an indexed cluster. In an indexed cluster, rows are stored together based on their cluster key values.

HASH IS	specifies a column to be used as the hash function for a hash cluster. In a hash cluster, rows are stored together based on their hash values. The hash function specifies the hash value for each row in the cluster. The value that you specify must be the only column of the cluster key and have a datatype of NUMBER with a scale of 0. Each value in the column must be a non-negative integer.

If you omit this parameter, ORACLE uses an internal hash function for the hash cluster. The cluster key of a hash column can have one or more columns of any datatype. Hash clusters with composite cluster keys or cluster keys made up of non-integer columns must use the internal hash function.

HASHKEYS	creates a hash cluster and specifies the number of hash values for a hash cluster. ORACLE rounds the HASHKEYS value up to the nearest prime number to obtain the actual number of hash values. The minimum value for this parameter is 2.

If you omit both the INDEX option and the HASHKEYS parameter, ORACLE creates an indexed cluster by default.

Usage Notes

A cluster is a schema object thatcontains one or more tables that all have one or more columns in common. Rowsof one or more tables that share the same value in these common columns are physically stored together within the database.

Clustering provides more control over the physical storage of rows within the database. Clustering can reduce both the time it takes to access clustered tables and the space needed to store the table. After you create a cluster and add tables to it, the cluster is transparent. You can access clustered tables with SQL statements just as you can unclustered tables.

As a general rule, you should only cluster tables that are frequently joined on the cluster key columns in SQL statements. While clustering multiple tables improves the performance of joins, it is likely to reduce the performance of full table scans, INSERT statements, and UPDATE statements that modify cluster key values. Before clustering, consider its benefits and tradeoffs in light of the operations you plan to perform on your data. For more information on the performance implications of clustering, see Chapter 5 "Tuning SQL Statements" of the ORACLE7 Server Application Developer's Guide.

When you create a cluster in Trusted ORACLE, it is labeled with your DBMS label.

Cluster Keys

The columns defined by the CREATE CLUSTER command make up the cluster key. These cluster columns must correspond in both datatype and size to columns in each of the clustered tables, although they need not correspond in name.

You cannot specify integrity constraints as part of the definition of a cluster key column. Instead, you can associate integrity constraints with the tables that belong to the cluster.

Types of Clusters

A cluster can be one of these types:

•	indexed cluster

•	hash cluster

 Indexed Clusters

In an indexed cluster, ORACLE stores rows having the same cluster key value together. Each distinct cluster key value is stored only once in each data block, regardless of the number of tables and rows in which it occurs.  This saves disk space and improves performance for many operations.

You may want to use indexed clusters in these cases:

•	Your queries retrieve rows over a range of cluster key values.

•	Your clustered tables may grow unpredictably.

After you create an indexed cluster, you must create an index on the cluster key before you can issue any Data Manipulation Language statements against a table in the cluster. This index is called the cluster index. For information on creating a cluster index, see the CREATE INDEX command later in this chapter. As with the columns of any index, the order of the columns in the cluster key affects the structure of the cluster index.

A cluster index provides quick access to rows within a cluster based on the cluster key. If you issue a SQL statement that searches for a row in the cluster based on its cluster key value, ORACLE searches the cluster index for the cluster key value and then locates the row in the cluster based on its ROWID.

 Hash Clusters

In a hash cluster, ORACLE stores together rows that have the same hash key value. The hash value for a row is the value returned by the cluster's hash function. When you create a hash cluster, you can either specify a hash function or use ORACLE's internal hash function. Hash  values are not actually stored in the cluster, although cluster key values are stored for every row in the cluster.

You may want to use hash clusters in these cases:

•	Your queries retrieve rows based on equality conditions involving all cluster key columns.

•	Your clustered tables are static or you can determine the maximum number of rows and the maximum amount of space required by the cluster when you create the cluster.

The hash function provides access to rows in the table based on the cluster key value. If you issue a SQL statement that locates a row in the cluster based on its cluster key value, ORACLE applies the hash function to the given cluster key value and uses the resulting hash value to locate the matching rows. Because multiple cluster key values can map to the same hash value, ORACLE must also check the row's cluster key value. Note that this process often results in less I/O than the process for the indexed cluster because the index search is not required.

ORACLE's internal hash function returns values ranging from 0 to the value of HASHKEYS - 1. If you specify a column with the HASH IS clause, the column values need not fall into this range. ORACLE divides the column value by the HASHKEYS value and uses the remainder as the hash value. The hash value for null is HASHKEYS - 1. ORACLE also rounds the HASHKEYS value up to the nearest prime number to obtain the actual number of hash values. This rounding reduces the likelihood of hash collisions, or multiple cluster key values having the same hash value.

You cannot create a cluster index for a hash cluster, and you need not create an index on a hash cluster key.

Cluster Size

ORACLE uses the value of the SIZE parameter to determine the spacereserved for rows corresponding to one cluster key value or one hash value. This space then determines the maximum number of cluster or hash values stored in a data block. If the SIZE value is not a divisor of the data block size, ORACLE uses the next largest divisor. If the SIZE value is larger than the data block size, ORACLE uses the operating system block size, reserving at least one data block per cluster or hash value.

ORACLE also considers the length of the cluster key when determining how much space to reserve for the rows having a cluster key value. Larger cluster keys require larger sizes. To see the actual size, query the KEY_SIZE column of the USER_CLUSTERS data dictionary view. This does not apply to hash clusters because hash values are not actually stored in the cluster.

Although the maximum number of cluster and hash key values per data block is fixed on a per cluster basis, ORACLE does not reserve an equal amount of space for each cluster or hash key value. Varying this space stores data more efficiently because the data stored per cluster or hash key value is rarely fixed.

A SIZE value smaller than the space needed by the average cluster or hash key value may require the data for one cluster key or hash key value to occupy multiple data blocks. A SIZE value much larger results in wasted space.

When you create a hash cluster, ORACLE immediately allocates space for the cluster based on the values of the SIZE and HASHKEYS parameters. For more information on how ORACLE allocates space for clusters, see  Chapter 5 "Schema Objects" of the ORACLE7 Server Concepts Manual.

Adding Tables to a Cluster

You can add tables to an existing cluster by issuing a CREATE TABLE statement with the CLUSTER clause. A cluster can contain as many as 32 tables, although the performance gains of clustering are often negated in clusters of more than four or five tables.

All tables in the cluster have the cluster's storage characteristics as specified by the PCTUSED, PCTFREE, INITRANS,  MAXTRANS, TABLESPACE, and STORAGE parameters.

Example I	This statement creates an indexed cluster named PERSONNEL with the cluster key column DEPARTMENT_NUMBER, a cluster size of 512 bytes, and storage parameter values:

CREATE CLUSTER personnel

( department_number  NUMBER(2) )

SIZE 512

STORAGE (INITIAL 100K  NEXT 50K  PCTINCREASE 10)

These statements add the EMP and DEPT tables to the cluster:

CREATE TABLE emp

(empno     NUMBER        PRIMARY KEY,

 ename     VARCHAR2(10)  NOT NULL

                         CHECK (ename = UPPER(ename)),

 job       VARCHAR2(9),

 mgr       NUMBER        REFERENCES scott.emp(empno),

 hiredate  DATE          CHECK (hiredate >= SYSDATE),

 sal       NUMBER(10,2)  CHECK (sal > 500),

 comm      NUMBER(9,0)   DEFAULT NULL,

deptno   NUMBER(2)    NOT NULL )

CLUSTER personnel (deptno)

CREATE TABLE dept

(deptno  NUMBER(2),

 dname   VARCHAR2(9),

 loc     VARCHAR2(9))

 	CLUSTER personnel (deptno)

This statement creates the cluster index on the cluster key of PERSONNEL:

CREATE INDEX idx_personnel ON CLUSTER personnel

After creating the cluster index, you can insert rows into either the EMP or DEPT tables.

Example II	This statement creates a hash cluster named PERSONNEL with the cluster key column DEPARTMENT_NUMBER, a maximum of 503 hash key values, each of size 512 bytes, and storage parameter values:

CREATE CLUSTER personnel

( department_number  NUMBER )

SIZE 512  HASHKEYS 500 	STORAGE (INITIAL 100K  NEXT 50K  PCTINCREASE 10)

Because this statement omits the HASH IS clause, ORACLE uses the internal hash function for the cluster.

Related Topics

CREATE INDEX and CREATE TABLE commands; STORAGE clause.

________________________________________

CREATE CONTROLFILE

Purpose

To recreate a control file in one of these cases:

•	All copies of your existing control files have been lost through media failure.

•	You want to change the name of the database.

•	You want to change the maximum number of redo log file groups, redo log file members, archived redo log files, data files, or instances that can concurrently have the database mounted and open.

Warning:  Oracle Corporation recommends that you perform a full backup of all files in the database before using this command.

Prerequisites

You must have the OSDBA role enabled. The database must not be mounted by any instance.

If you are using Trusted ORACLE in DBMS MAC mode, your operating system label must be the equivalent of DBHIGH.

Syntax

Keywords and Parameters

REUSE	specifies that existing control files identified by the initialization parameter CONTROL_FILES can be reused, thus ignoring and overwriting any and all information they may currently contain. If you omit this option and any of these control files already exist, ORACLE returns an error.

SET DATABASE	changes the name of the database. The name of a database can be as long as eight bytes.

DATABASE	specifies the name of the database. The value of this parameter must be the existing database name established by the previous CREATE DATABASE statement or CREATE CONTROLFILE statement.

LOGFILE	specifies the redo log file groups for your database. You must list all members of all redo log file groups. These files must all exist. See the syntax description of filespec on page 7 - 279.

RESETLOGS	ignores the contents of the files listed in the LOGFILE clause. Each filespec in the LOGFILE clause must specify the SIZE parameter. ORACLE assigns all redo log file groups to thread 1 and enables this thread for public use by any instance. After using this option, you must open the database using the RESETLOGS option of the ALTER DATABASE command.

NORESETLOGS	specifies that all files in the LOGFILE clause should be used as they were when the database was last open. These files must be the current redo log files rather than restored backups. ORACLE reassigns the redo log file groups to the threads to which they were previously assigned and re-enables the threads as they were previously enabled. If you specify GROUP values, ORACLE verifies these values with the GROUP values when the database was last open.

DATAFILE	specifies the data files of the database. You must list all data files. These files must all exist, although they may be restored backups that require media recovery. See the syntax description of filespec on page 7 - 279.

MAXLOGFILES	specifies the maximum number of redo log file groups that can ever be created for the database. ORACLE uses this value to determine how much space in the control file to allocate for the names of redo log files.

The default and maximum values depend on your operating system. The value that you specify should not be less than the greatest GROUP value for any redo log file group.

Note that the number of redo log file groups accessible to your instance is also limited by the initialization parameter LOG_FILES.

MAXLOG

MEMBERS	specifies the maximum number of members, or copies, for a redo log file group. ORACLE uses this value to determine how much space in the

control file to allocate for the names of redo log files. The minimum value is 1. The maximum and default values depend on your operating system.

MAXLOG

HISTORY	specifies the maximum number of archived redo log file groups for automatic media recovery of the ORACLE Parallel Server. ORACLE uses this value to determine how much space in the control file to allocate for the names of archived redo log files. The minimum value is 0.

The default value is a multiple of the MAXINSTANCES value and varies depending on your operating system. The maximum value is limited only by the maximum size of the control file. Note that this parameter is only useful if you are using ORACLE with the Parallel Server option in both parallel mode and archivelog mode.

MAXDATAFILES	specifies the maximum number of data files that can ever be created for the database.

The minimum value is 1. The maximum and default values depend on your operating system. The value you specify should not be less than the total number of data files ever in the database, including those for tablespaces that have been dropped.

Note that the number of data files accessible to your instance is also limited by the initialization parameter DB_FILES.

MAXINSTANCES	specifies the maximum number of instances that can simultaneously have the database mounted and open. This value takes precedence over the value of the

initialization parameter INSTANCES. The minimum value is 1. The maximum and default values depend on your operating system.

ARCHIVELOG	establishes the mode of archiving the contents of redo log files before reusing them. This option prepares for the possibility of media recovery as well as instance recovery.

NOARCHIVE

LOG	establishes the initial mode of reusing redo log files without archiving their contents. This option prepares for the possibility of instance recovery but not media recovery.

If you omit both the ARCHIVELOG and NOARCHIVELOG options, ORACLE chooses noarchivelog mode by default. After creating the control file, you can change between archivelog mode and noarchivelog mode with the ALTER DATABASE command.

Usage Notes

Oracle Corporation recommends that you take a full backup of all filesin the database before issuing a CREATE CONTROLFILE statement.

When you issue a CREATE CONTROLFILE statement, ORACLE creates a new control file based on the information you specify in the statement. If you omit any of the options from the statement, ORACLE uses the default options, rather than the options for the previous control file. After successfully creating the control file, ORACLE mounts the database in exclusive mode. You then must perform media recovery before opening the database. Oracle Corporation recommends that you then shutdown the instance and take a full backup of all files in the database.  For more information on using this command, see Chapter 19 "Recovering a Database" of the ORACLE7 Server Administrator's Guide.

When you create a control file in Trusted ORACLE, it is labeled with your DBMS label. The control file cannot be used unless it is labeled at the operating system equivalent of DBHIGH. If you issue a CREATE CONTROLFILE statement in DBMS MAC mode, Trusted ORACLE automatically switches to OS MAC mode. You can then return to DBMS MAC mode by issuing an ALTER DATABASE statement with the SET DBMAC ON clause.

Example	This example recreates a control file:

CREATE CONTROLFILE REUSE

SET DATABASE orders_2

LOGFILE GROUP 1 ('diskb:log1.log', 'diskc:log1.log') SIZE 50K,

        GROUP 2 ('diskb:log2.log', 'diskc:log2.log') SIZE 50K

NORESETLOGS

DATAFILE 'diska:dbone.dat' SIZE 2M

MAXLOGFILES 5

MAXLOGHISTORY 100

MAXDATAFILES 10

MAXINSTANCES 2

ARCHIVELOG

Related Topics

CREATE DATABASE command.

________________________________________

CREATE DATABASE

Purpose

To create a database, making it available for general use, with these options:

•	to establish a maximum number of instances, data files, redo log files groups, or redo log file members

•	to specify names and sizes of data files and redo log files

•	to choose a mode of use for the redo log

Warning:  This command prepares a database for initial use and erases any data currently in the specified files. Only use this command when you understand its ramifications.

Prerequisites

You must have the OSDBA role enabled.

If you are using Trusted ORACLE and you plan to use the database in DBMS MAC mode, your operating system label should be the

equivalent of DBLOW.

Syntax

Keyword and Parameters

database	is the name of the database to be created and can be up to eight bytes long. ORACLE writes this name into the control file. If you subsequently issue an ALTER DATABASE statement and that explicitly specifies a database name, ORACLE verifies that name with the name in the control file.

The database cannot be a SQL*DBA reserved word. These reserved words appear in the ORACLE7 Server Utilities User's . If you omit database from a CREATE DATABASE statement, ORACLE uses the name specified by the initialization parameter DB_NAME.

CONTROLFILE REUSE	reuses existing control files identified by the initialization parameter CONTROL_FILES, thus ignoring and overwriting any information they currently contain. This option is usually used only when you are recreating a database, rather than creating one for the first time. You cannot use this option if you also specify a parameter value that requires that the control file be larger than the existing files. These parameters are  MAXLOGFILES, MAXLOGMEMBERS, MAXLOGHISTORY, MAXDATAFILES, and MAXINSTANCES.

If you omit this option and any of the files specified by CONTROL_FILES already exist, ORACLE returns an error message.

LOGFILE	specifies one or more files to be used as redo log files. Each filespec specifies a redo log file group containing one or more redo log file members, or copies. See the syntax description of filespec on page 7 - 279. All redo log files specified in a CREATE DATABASE statement are added to redo log thread number 1.

You can also choose the value of the GROUP parameter for the redo log file group. Each value uniquely identifies a redo log file group and can range from 1 to the value of the MAXLOGFILES parameter. You cannot specify multiple redo log file groups having the same GROUP value. If you omit this parameter, ORACLE generates its value automatically. You can examine the GROUP value for a redo log file group through the dynamic performance table V$LOG.

If you omit the LOGFILE clause, ORACLE creates two redo log file groups by default. The names and sizes of the default files vary depending on your operating system.

MAXLOGFILES	specifies the maximum number of redo log file groups that can ever be created for the database. ORACLE uses this value to determine how much space in the control file to allocate for the names of redo log files. The default, minimum, and maximum values vary depending on your operating system.

The number of redo log file groups accessible to your instance is also limited by the initialization parameter LOG_FILES.

MAXLOG

MEMBERS	specifies the maximum number of members, or copies, for a redo log file group. ORACLE uses this value to determine how much space in the control file to allocate for the names of redo log files. The minimum value is 1. The maximum and default values vary depending on your operating system.

MAXLOG

HISTORY	specifies the maximum number of archived redo log files for automatic media recovery of ORACLE with the Parallel Server option. ORACLE uses this value to determine how much space in the control file to allocate for the names of archived redo log files. The minimum value is 0. The default value is a multiple of the MAXINSTANCES value and varies depending on your operating system. The maximum value is limited only by the maximum size of the control file. Note that this parameter is only useful if you are using the ORACLE with the Parallel Server option in parallel mode and archivelog mode.

DATAFILE	specifies one or more files to be used as data files. See the syntax description of filespec on page 7 - 279. These files all become part of the SYSTEM tablespace. If you omit this clause, ORACLE creates one data file by default. The name and size of this default file depends on your operating system.

MAXDATAFILES	specifies the maximum number of data files that can ever be created for the database.

The minimum value is 1. The maximum and default values depend on your operating system.

The number of data files accessible to your instance is also limited by the initialization parameter DB_FILES.

MAXINSTANCES	specifies the maximum number of instances that can simultaneously have this database mounted and open. This value takes precedence over the

value of the initialization parameter INSTANCES. The minimum value is 1. The maximum and default values depend on your operating system.

ARCHIVELOG	establishes archivelog mode for redo log file groups. In this mode, the contents of a redo log file group must be archived before the group can be reused. This option prepares for the possibility of media recovery.

NOARCHIVE

LOG	establishes noarchivelog mode for redo log files groups. In this mode, the contents of a redo log file group need not be archived before the group can be reused. This option does not prepares for the possibility of media recovery.

The default is noarchivelog mode. After creating the database, you can change between archivelog mode and noarchivelog mode with the ALTER DATABASE command.

EXCLUSIVE	mounts the database in exclusive mode after it is created. This mode allows only your instance to access the database. ORACLE automatically mounts the database in exclusive mode after creating it, so this keyword is entirely optional.

For multiple instances to access the database, you must first create the database, close and dismount the database, and then mount it in parallel mode. For information on closing, dismounting, and mounting the database, see the ALTER DATABASE command earlier in this chapter.

CHARACTER SET	specifies the character set the database uses to store data. You cannot change the database character set after creating the database. The supported character sets and default value of this parameter depends on your operating system.

Usage Notes

This command erases all data in any specified data files that alreadyexist to prepare them for initial database use. If you use the commandon an existing database, all data in the data files is lost.

After creating the database, this command mounts it in exclusive mode and opens it, making it available for normal use.

If you create a database using Trusted ORACLE, it is labeled with your operating system label and is created in OS MAC mode. If you plan to use the database in DBMS MAC mode, be sure you set values for DBHIGH and DBLOW. For more information on creating Trusted ORACLE databases, see the Trusted ORACLE7 Server Administrator's Guide.

Example	This statement creates a small database using defaults for all arguments:

CREATE DATABASE

This statement creates a database and fully specifies each argument:

CREATE DATABASE newtest

CONTROLFILE REUSE

LOGFILE GROUP 1 ('diskb:log1.log', 'diskc:log1.log') SIZE 50K,

GROUP 2 ('diskb:log2.log', 'diskc:log2.log') SIZE 50K

MAXLOGFILES 5

MAXLOGHISTORY 100

DATAFILE 'diska:dbone.dat' SIZE 2M

MAXDATAFILES 10

MAXINSTANCES 2

ARCHIVELOG

EXCLUSIVE

Related Topics

ALTER DATABASE, CREATE ROLLBACK SEGMENT and CREATE TABLESPACE commands; STARTUP and SHUTDOWN SQL*DBA commands in the ORACLE7 Server Utilities User's .

________________________________________

CREATE DATABASE LINK

Purpose

To create a database link. A database link is an object in the local database thatallows you to access objects on a remote database or to mount a secondary database in read-only mode. The remote database can be either an ORACLE or a non-ORACLE database.

Prerequisites

To create a private database link, you must have CREATE DATABASE LINK system privilege. To create a public database link, you must have CREATE PUBLIC DATABASE LINK system privilege. Also, you must have CREATE SESSION privilege on a remote database. SQL*Net must be installed on both the local and remote databases.

can only be specified for public database links. For information on specifying read-only mounts, see the Trusted ORACLE7 Server Administrator's Guide.

Syntax

Keyword and Parameters

PUBLIC	creates a public database link available to all users. If you omit this option, the database link is private and is available only to you.

dblink	is the complete or partial name of the database link. For guidelines for naming database links, see the section "Referring to Objects  on page 2 - 13.

CONNECT TO  user

IDENTIFIED BY password 	is the username and password used to connect to the remote database. If you omit this clause, the database link uses the username and password of each user who uses the database link.

USING	specifies either:

•	the database specification of a remote database

•	the specification of a secondary database for a read-only mount.

For information on specifying remote databases, see the SQL*Net User's Guide for your specific SQL*Net protocol.

Read-only mounts are only available in Trusted ORACLE and can only be specified for public database links.  For more information on specifying read-only mounts, see the Truested ORACLE7 Sercer Administrator's Guide.

Usage Notes

You cannot create a database link in another user's schema and youcannot qualify dblink with the name of a schema. Since periodsare permitted in names of database links, ORACLE interprets the entire name, such as RALPH.LINKTOSALES, as the name of a database link in your schema rather than as a database link named LINKTOSALES in the schema RALPH.

Once you have created a database link, you can use it to refer to tables and views on the remote database. You can refer to a remote table or view in a SQL statement by appending @dblink to the table or view name. You can query a remote table or view with the SELECT command. If you are using ORACLE with the distributed option, you can also access remote tables and views in any of these commands:

•	DELETE

•	INSERT

•	LOCK TABLE

•	UPDATE

For information on accessing remote tables and views with these commands, see the section on each command later in this chapter.

The number of different database links that can appear in a single statement is limited to the value of the initialization parameter OPEN_LINKS.

When you create a database link in Trusted ORACLE, it is labeled with your DBMS label.

Example	This statement defines a database link named SALES.HQ.ACME.COM that refers to user SCOTT with password TIGER on the database specified by the string D:BOSTON-MFG:

CREATE DATABASE LINK sales.hq.acme.com

CONNECT TO scott IDENTIFIED BY tiger

USING 'D:BOSTON-MFG'

Once this database link is created, you can query tables in the schema SCOTT on the remote database in this manner:

SELECT *

FROM emp@sales.hq.acme.com

You can also use Data Manipulation Language commands to modify data on the remote database:

INSERT INTO accounts@sales.hq.acme.com(acc_no, acc_name, balance)

 	VALUES (5001, 'BOWER', 2000)

UPDATE accounts@sales.hq.acme.com

SET balance = balance + 500

DELETE FROM accounts@sales.hq.acme.com

WHERE acc_name = 'BOWER'

You can also access tables owned by other users on the same database. This example assumes SCOTT has access to ADAM's DEPT table:

SELECT *

FROM adams.dept@sales.hq.acme.com

The previous statement connects to the user SCOTT on the remote database and then queries ADAM's DEPT table.

A synonym may be created to hide the fact that SCOTT's EMP table is on a remote database. This statement causes all future references to EMP to access a remote EMP table owned by SCOTT.

CREATE SYNONYM emp

FOR scott.emp@sales.hq.acme.com

Related Topics

The CREATE SYNONYM and SELECT commands.

________________________________________

CREATE FUNCTION

Purpose

To create a stand-alone stored function. A stored function is a setof PL/SQL statements you can call by name. Stored functions are very similar to procedures, except that a function returns a value to the environment in which it is called.

Prerequisites

Before a stored function can be created, the user SYS must run the SQL script DBMSSTDX.SQL. The exact name and location of this script may vary depending on your operating system.

To create a function in your own schema, you must have CREATE PROCEDURE system privilege. To create a function in another user's schema, you must have CREATE ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, you can create a function in another user's schema if your DBMS label dominates the creation label of the other user.

To create a stored function, you must be using ORACLE with the procedural option.

how to write a PL/SQL subprogram body, see the PL/SQL User's Guide and Reference.

Syntax

Keywords and Parameters

OR REPLACE	recreates the function if it already exists. You can use this option to change the definition of an existing function without dropping, recreating, and regranting object privileges previously granted on the function. If you redefine a function, ORACLE recompiles it. For information on recompiling functions, see the ALTER FUNCTION command earlier in this chapter.

Users who had previously been granted privileges on a redefined function can still access the function without being regranted the privileges.

schema	is the schema to contain the function. If you omit schema, ORACLE creates the function in your current schema.

function	is the name of the function to be created.

argument	is the name of an argument to the function. If the function does not accept arguments, you can omit the parentheses following the function name.

IN	specifies that you must supply a value for the argument when calling the function. This is always true for function arguments, so this keyword is entirely optional.

A procedure, rather than a stored function, can accept arguments for which the procedure passes a value back to the calling environment after execution.

datatype	is the datatype of an argument. An argument can have any datatype supported by PL/SQL.

The datatype cannot specify a length, precision, or scale. ORACLE derives the length, precision, or scale of an argument from the environment from which the function is called.

RETURN datatype	specifies the datatype of the function's return value. Because every function must return a value, this clause is required. The return value can have any datatype supported by PL/SQL.

The datatype cannot specify a length, precision, or scale. ORACLE derives the length, precision, or scale of the return value from the environment from which the function is called. For information on PL/SQL datatypes, see the PL/SQL User's Guide and .

pl/sql_subprogram_body	is the definition of the function. Function definitions are written in PL/SQL. For information on PL/SQL, including

To embed a CREATE FUNCTION statement inside an ORACLE Precompiler program, you must terminate the statement with the keyword END-EXEC followed by the embedded SQL statement terminator for the specific language.

Usage Notes

A stored function is setof PL/SQL statements that you can call by name. Functions are verysimilar to procedures, except that a function explicitly returns a value to its calling environment. For a general discussion of procedures and functions, see the CREATE PROCEDURE command later in this chapter.

The CREATE FUNCTION command creates a function as a stand-alone schema object. You can also create a function as part of a package. For information on creating packages, see the CREATE PACKAGE command later in this chapter.

When you create a stored function in Trusted ORACLE, it is labeled with your DBMS label.

Example	This statement creates the function GET_BAL:

CREATE FUNCTION get_bal(acc_no IN NUMBER)

RETURN NUMBER

IS

acc_bal NUMBER(11,2);

BEGIN

SELECT balance

INTO acc_bal

FROM accounts

WHERE account_id = acc_no;

RETURN(acc_bal);

END

The GET_BAL function returns the balance of a specified account.

When you call the function, you must specify the argument ACC_NO, the number of the account whose balance is sought. The datatype of ACC_NO is NUMBER.

The function returns the account balance. The RETURN clause of the CREATE FUNCTION statement specifies the datatype of the return value to be NUMBER.

The function uses a SELECT statement to select the BALANCE column from the row identified by the argument ACC_NO in the ACCOUNTS table. The function uses a RETURN statement to return this value to the environment in which the function is called.

Related Topics

ALTER FUNCTION, CREATE PACKAGE, CREATE PACKAGE BODY, CREATE PROCEDURE, DROP FUNCTION commands.

________________________________________

CREATE INDEX

Purpose

To create an index on one or more columns of a table or a cluster. An index is a database object that contains an entry for each value that appears in the indexed column(s) of the table or cluster and provides direct, fast access to rows.

Prerequisites

To create an index in your own schema, one of these conditions must be true:

•	The table or cluster to be indexed must be in your own schema.

•	You must have INDEX privilege on the table to be indexed.

•	You must have CREATE ANY INDEX system privilege.

To create an index in another schema, you must have CREATE ANY INDEX system privilege.

Also, the owner of the schema to contain the index must have either space quota on the tablespace to contain the index or UNLIMITED TABLESPACE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the tablespace's label and match the table's label. If the table was created at DBHIGH or DBLOW, you must explicitly set your label to DBHIGH or DBLOW. You can create an index in another user's schema if your DBMS label dominates the creation label of the other user.

Syntax

Keywords and Parameters

schema	is the schema to contain the index. If you omit schema, ORACLE creates the index in your own schema.

index	is the name of the index to be created.

table	is the name of the table for which the index is to be created. If you do not qualify table with schema, ORACLE assumes the table is contained in your own schema.

column	is the name of a column in the table. An index can have as many as 16 columns. A column of an index cannot be of datatype LONG or LONG RAW.

ASC DESC	are allowed for DB2 syntax compatibility, although indexes are always created in ascending order. Indexes on character data are created in ascending order of the character values in the database character set.

CLUSTER	specifies the cluster for which a cluster index is to be created. If you do not qualify cluster with schema, ORACLE assumes the cluster is contained in your current schema. You cannot create a cluster index for a hash cluster.

INITRANS MAXTRANS	establishes values for these parameters for the index. See the INITRANS and MAXTRANS parameters of the CREATE TABLE command later in this chapter.

TABLESPACE	is the name of the tablespace to hold the index. If you omit this option, ORACLE creates the index in the default tablespace of the owner of the schema containing the index.

STORAGE	establishes the storage characteristics for the index. See the STORAGE clause on page 8 - 371.

PCTFREE	is the percentage of space to leave free for updates and insertions within each of the index's data blocks.

NOSORT	indicates to ORACLE that the rows are stored in the database in ascending order and therefore ORACLE does not have to sort the rows when creating the index.

Usage Notes

 ORACLE can use indexes to improve performance when:

•	searching for rows with specified index column values

•	accessing tables in index column order

However, an index can slow down INSERT, UPDATE, and DELETE commands that affect indexed column values because ORACLE must maintain both the index data as well as the table data. For more information on how indexes can improve performance see Chapter 5 "Tuning SQL Statements"of the ORACLE7 Server Application Developer's Guide.

When you initially insert rows into a new table, it is generally faster to create the table, insert the rows, and then create the index. If you create the index before inserting the rows, ORACLE must update the index for every row inserted.

When you create an index in Trusted ORACLE, it is labeled with your DBMS label.

Index Columns

An index can contain a maximum of 16 columns. The indexentry becomes the concatenation of all data values from each column. You can specify the columns in any order. The order you choose is important to how ORACLE uses the index.

When appropriate, ORACLE uses the entire index or a leading portion of the index. Assume an index named IDX1 is created on columns A,B, and C of table TAB1 (in the order A,B,C). ORACLE uses the index for references to columns A,B,C (the entire index); A,B; or just column A. References to columns B,C do not use the IDX1 index. Of course, you can also create another index just for columns B and C.

Multiple Indexes Per Table

You can create several indexes on different columns (or different combinations of columns) in the same table. ORACLE imposes no limits on the number of indexes you can create on a single table. Note that each index increases the processing time needed to maintain the table during updates to indexed data.

The NOSORT Option

The NOSORT option can substantially reduce the time required to create an index. Normal index creation first sorts the rows of the table based on the index columns and then builds the index. The sort operation is often a substantial portion of the total work involved. If the rows are physically stored in ascending order (based on the indexed column values), then the NOSORT option causes ORACLE to bypass the sort phase of the process.

You cannot use the NOSORT option to create a cluster index.

The NOSORT option also reduces the amount of space required to build the index. ORACLE uses temporary segments during the sort. Since a sort is not performed, the index is created with much less temporary space.

To use the NOSORT option, you must guarantee that the rows are physically sorted in ascending order. Because of the physical data independence inherent in relational database management systems, especially ORACLE, there is no way to force a physical internal order on a table. The CREATE INDEX command with the NOSORT option should be used immediately after the initial load of rows into a table.

You run no risk by trying the NOSORT option. If your rows are not in the ascending order, ORACLE returns an error. You can issue another  CREATE INDEX without the NOSORT option.

Nulls

Nulls are not indexed. Consider this statement:

SELECT ename

FROM emp

WHERE comm IS NULL

This query does not use an index that had been created on the COMM column.

Creating Cluster Indexes

ORACLE does not automatically create an index for a cluster when the cluster is initially created. Data Manipulation Language statements cannot be issued against clustered tables until a cluster index has been created.

To create an index for the EMPLOYEE cluster, issue this statement:

CREATE INDEX ic_emp

ON CLUSTER employee

Note that no index columns are specified since the index is automatically built on all the columns of the cluster key.

Example	This command creates an index on the ENAME column of the EMP table EMP:

CREATE INDEX i_emp_ename

ON emp (ename)

Related Topics

ALTER INDEX and DROP INDEX commands; CONSTRAINT and STORAGE clauses.

________________________________________

CREATE PACKAGE

Purpose

To create the specification for a stored package. A package is an encapsulated collection of related procedures, functions, and other program objects stored together in the database. The specification  declares these objects.

Prerequisites

Before a package can be created, the user SYS must run the SQL script DBMSSTDX.SQL. The exact name and location of this script may vary depending on your operating system.

To create a package in your own schema, you must have CREATE PROCEDURE system privilege. To create a package in another user's schema, you must have CREATE ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, you can only create a package in another user's schema if your DBMS label dominates the creation label of the other user.

To create a package, you must be using ORACLE with the procedural option.

Syntax

Keywords and Parameters

OR REPLACE	recreates the package specification if it already exists. You can use this option to change the specification of an existing package without dropping, recreating, and regranting object privileges previously granted on the package. If you change a package specification, ORACLE recompiles it. For information on recompiling package specifications, see the ALTER PROCEDURE command earlier in this chapter.

Users who had previously been granted privileges on a redefined package can still access the package without being regranted the privileges.

schema	is the schema to contain the package. If you omit schema, ORACLE creates the package in your own schema.

package	is the name of the package to be created.

pl/sql_package_spec	is the package specification. The package specification can declare program objects. Package specifications are written in PL/SQL. For information on PL/SQL, including writing package specifications, see the PL/SQL User's Guide and Reference.

To embed a CREATE PACKAGE statement inside an ORACLE Precompiler program, you must terminate the statement with the keyword END-EXEC followed by the embedded SQL statement terminator for the specific language.

Packages

 A package is an encapsulated collection of relatedprogram objects stored together in the database. Program objects are:

•	procedures

•	functions

•	variables

•	constants

•	cursors

•	exceptions

Using packages is an alternative to creating procedures and functions as stand-alone schema objects. Packages have many advantages over stand-alone procedures and functions:

•	Packages allow you to organize your application development more efficiently.

•	Packages allow you to grant privileges more efficiently.

•	Packages allow you to modify package objects without recompiling dependent schema objects.

•	Packages allow ORACLE to read multiple package objects into memory at once.

•	Packages can contain global variables and cursors that are available to all procedures and functions in the package.

•	Packages allow you to overload procedures or functions. Overloading a procedure means creating multiple procedures with the same name in the same package, each taking arguments of different number or datatype.

For more information on these and other benefits of packages, see Chapter 7 "Using Procedures and Packages" of the ORACLE7 Server Application Developer's Guide .

When you create a package in Trusted ORACLE, it is labeled with your DBMS label.

How to Create Packages

To create a package, you must perform two distinct steps:

1. Create the package specification with the CREATE PACKAGE command. You can declare program objects in the package specification. Such  objects are called public objects. Public objects can be referenced outside the package as well as by other objects in the package.

2. Create the package body with the CREATE PACKAGE BODY command.    You can declare and define program objects in the package body:

•	You must define public objects declared in the package specification.

•	You can also declare and define additional package objects. Such objects are called private objects. Since private objects are declared in the package body rather than in the package specification, they can only be referenced by other objects in the package. They cannot be referenced outside the package.

See the CREATE PACKAGE BODY command later in this chapter.

 The Separation of Specification and Body

ORACLE stores the specification and body of a package separately in the database. Other schema objects that call or reference public program objects depend only on the package specification, not on the package body. This distinction allows you to change the definition of a program object in the package body without causing ORACLE to invalidate other schema objects that call or reference the program object. ORACLE only invalidates dependent schema objects if you change the declaration of the program object in the package specification.

Example	This SQL statement creates the specification of the EMP_MGMT package:

CREATE PACKAGE emp_mgmt AS

FUNCTION hire(ename VARCHAR2, job VARCHAR2, mgr NUMBER, sal NUMBER,

              comm NUMBER, deptno NUMBER)

RETURN NUMBER;

FUNCTION create_dept(dname VARCHAR2, loc VARCHAR2)

RETURN NUMBER;

PROCEDURE remove_emp(empno NUMBER);

PROCEDURE remove_dept(deptno NUMBER);

PROCEDURE increase_sal(empno NUMBER, sal_incr NUMBER);

PROCEDURE increase_comm(empno NUMBER, comm_incr NUMBER);

no_comm EXCEPTION;

no_sal EXCEPTION;

END emp_mgmt

The specification for the EMP_MGMT package declares these public program objects:

•	the functions HIRE and CREATE_DEPT

•	the procedures REMOVE_EMP, REMOVE_DEPT, INCREASE_SAL, and INCREASE_COMM

•	the exceptions NO_COMM and NO_SAL

All of these objects are available to users who have access to the package. After creating the package, you can develop applications that call any of the package's public procedures or functions or raise any of the package's public exceptions.

Before you can call this package's procedures and functions, you must define these procedures and functions in the package body. For an example of a CREATE PACKAGE BODY statement that creates the body of the EMP_MGMT package, see the CREATE PACKAGE BODY command next in this chapter.

Related Topics

ALTER PACKAGE, CREATE FUNCTION, CREATE PROCEDURE, CREATE PACKAGE BODY, and DROP PACKAGE commands.

________________________________________

CREATE PACKAGE BODY

Purpose

To create the body of a stored package. A package is an encapsulated collection of related procedures, stored functions, and other program objects stored together in the database. The body defines these objects.

Prerequisites

Before a package can be created, the user SYS must run the SQL script DBMSSTDX.SQL. The exact name and location of this script may vary depending on your operating system.

To create a package in your own schema, you must have CREATE PROCEDURE system privilege. To create a package in another user's schema, you must have CREATE ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, you can only create a package in another user's schema if your DBMS label dominates the creation label of the other user.

To create a package, you must be using ORACLE with the procedural option.

Syntax

Keywords and Parameters

OR REPLACE	recreates the package body if it already exists. You can use this option to change the body of an existing package without dropping, recreating, and regranting object privileges previously granted on it. If you change a package body, ORACLE recompiles it. For information on recompiling package bodies, see the ALTER PACKAGE BODY command earlier in this chapter.

Users who had previously been granted privileges on a redefined package can still access the package without being regranted the privileges.

schema	is the schema to contain the package. If you omit schema, ORACLE creates the package in your current schema.

package	is the name of the package to be created.

pl/sql_package_body	is the package body. The package body can declare and define program objects. Package bodies are written in PL/SQL. For information on PL/SQL, including writing package bodies, see the PL/SQL User's Guide and Reference.

To embed a CREATE PACKAGE BODY statement inside an ORACLE Precompiler program, you must terminate the statement with the keyword END-EXEC followed by the embedded SQL statement terminator for the specific language.

Packages

 A package is an encapsulated collection of relatedprocedures, functions, and other program objects stored together inthe database. Packages are an alternative to creating procedures and functions as stand-alone schema objects. For a discussion of packages, including how to create packages, see the CREATE PACKAGE command earlier in this chapter.

Example	This SQL statement creates the body of the EMP_MGMT package:

CREATE PACKAGE BODY emp_mgmt AS

tot_emps  NUMBER; 	tot_depts NUMBER;

 	FUNCTION hire(ename VARCHAR2, job VARCHAR2, mgr NUMBER, sal NUMBER,

 	              comm NUMBER, deptno NUMBER)

 	RETURN NUMBER IS

 	new_empno NUMBER(4);

 	BEGIN

 	SELECT empseq.NEXTVAL

 	INTO new_empno

 	FROM DUAL;

 	INSERT INTO emp

 	VALUES (new_empno, ename, job, mgr, sal, comm, deptno)

 	tot_emps := tot_emps + 1;

 	RETURN(new_empno);

 	END;

 	FUNCTION create_dept(dname VARCHAR2, loc VARCHAR2)

 	RETURN NUMBER IS

 	new_deptno NUMBER(4);

 	BEGIN

 	SELECT deptseq.NEXTVAL

 	INTO new_deptno

 	FROM dual;

 	INSERT INTO dept

 	VALUES (new_deptno, dname, loc);

 	tot_depts := tot_depts + 1;

 	RETURN(new_deptno);

 	END;

 	PROCEDURE remove_emp(empno NUMBER) IS

 	BEGIN

 	DELETE FROM emp

 	WHERE emp.empno = remove_emp.empno;

 	tot_emps := tot_emps - 1;

 	END;

PROCEDURE remove_dept(deptno NUMBER) IS

BEGIN

DELETE FROM dept

WHERE dept.deptno = remove_dept.deptno;

tot_depts := tot_depts - 1;

SELECT COUNT(*)

INTO tot_emps

FROM emp;

/*  In case ORACLE deleted employees from the EMP table

to enforce referential integrity constraints, reset

the value of the variable TOT_EMPS to the total

number of employees in the EMP table.	*/ 	END;

PROCEDURE increase_sal(empno NUMBER, sal_incr NUMBER) IS

curr_sal NUMBER(7,2);

BEGIN

SELECT sal

INTO curr_sal

FROM emp

WHERE emp.empno = increase_sal.empno;

IF curr_sal IS NULL

THEN RAISE no_sal;

ELSE UPDATE emp

SET sal = sal + sal_incr

WHERE empno = empno;

END IF;

END;

PROCEDURE increase_comm(empno NUMBER, comm_incr NUMBER) IS 	curr_comm NUMBER(7,2);

 	BEGIN

 	SELECT comm

 	INTO curr_comm

 	FROM emp

 	WHERE emp.empno = increase_comm.empno

 	IF curr_comm IS NULL

 	THEN RAISE no_comm;

 	ELSE UPDATE emp

 	SET comm = comm + comm_incr;

 	END;

 	END emp_mgmt

This package body corresponds to the package specification in the example of the CREATE PACKAGE statement earlier in this chapter. The package body defines the public program objects declared in the package specification:

•	the functions HIRE and CREATE_DEPT

•	the procedures REMOVE_EMP, REMOVE_DEPT, INCREASE_SAL, and INCREASE_COMM

Since these objects are declared in the package specification, they can be called by application programs, procedures, and functions outside the package. For example, if you have access to the package, you can create a procedure INCREASE_ALL_COMMS separate from the EMP_MGMT package that calls the INCREASE_COMM procedure.

Since these objects are defined in the package body, you can change their definitions without causing ORACLE to invalidate dependent schema objects. For example, if you subsequently change the definition of HIRE, ORACLE need not recompile INCREASE_ALL_COMMS before executing it.

The package body in this example also declares private program objects, the variables TOT_EMPS and TOT_DEPTS. Since these objects are declared in the package body rather than the package specification, they are accessible to other objects in the package, but they are not accessible outside the package. For example, you cannot develop an application that explicitly changes the value of the variable TOT_DEPTS. However, since the function CREATE_DEPT is part of the package, CREATE_DEPT can change the value of TOT_DEPTS.

Related Topics

ALTER PACKAGE, CREATE FUNCTION, CREATE PROCEDURE, CREATE PACKAGE, and DROP PACKAGE commands.

________________________________________

CREATE PROCEDURE

Purpose

To create a stand-alone stored procedure. A procedure  is a group of PL/SQL statements that you cancall by name.

Prerequisites

Before a procedure can be created, the user SYS must run the SQL script DBMSSTDX.SQL. The exact name and location of this script may vary depending on your operating system.

To create a procedure in your own schema, you must have CREATE PROCEDURE system privilege. To create a procedure in another schema, you must have CREATE ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, you can only create a procedure in another user's schema if your DBMS label dominates the creation label of the other user.

To create a procedure, you must be using ORACLE with the procedural option.

Syntax

Keywords and Parameters

OR REPLACE	recreates the procedure if it already exists. You can use this option to change the definition of an existing procedure without dropping, recreating, and regranting object privileges previously granted on it. If you redefine a procedure, ORACLE recompiles it. For information on recompiling procedures, see the ALTER PROCEDURE command earlier in this chapter.

Users who had previously been granted privileges on a redefined procedure can still access the procedure without being regranted the privileges.

schema	is the schema to contain the procedure. If you omit schema, ORACLE creates the procedure in your current schema.

procedure	is the name of the procedure to be created.

argument	is the name of an argument to the procedure. If the procedure does not accept arguments, you can omit the parentheses following the procedure name.

IN	specifies that you must specify a value for the argument when calling the procedure.

OUT	specifies that the procedure passes a value for this argument back to its calling environment after execution.

IN OUT	specifies that you must specify a value for the argument when calling the procedure and that the procedure passes a value back to its calling environment after execution.

If you omit IN, OUT, and IN OUT, the argument defaults to IN.

datatype	is the datatype of an argument. An argument can have any datatype supported by PL/SQL. For information on PL/SQL datatypes, see the PL/SQL User's Guide and .

The datatype cannot specify a length, precision, or scale. ORACLE derives the length, precision, or scale of an argument from the environment from which the procedure is called.

pl/sql_

subprogram_body	is the definition of the procedure. Procedure definitions are written in PL/SQL. For information on PL/SQL, including how to write a PL/SQL subprogram body, see the PL/SQL User's .

To embed a CREATE PROCEDURE statement inside an ORACLE Precompiler program, you must terminate the statement with the keyword END-EXEC followed by the embedded SQL statement terminator for the specific language.

Usage Notes

 A procedure is a group of PL/SQLstatements that you can call by name. Stored procedures and storedfunctions are similar in many ways. This discussion applies to functions as well as to procedures. For information specific to functions, see the CREATE FUNCTION command earlier in this chapter.

With PL/SQL, you can group multiple SQL statements together with procedural PL/SQL statements similar to those in programming languages such as Ada and C. With the CREATE PROCEDURE command, you can create a procedure and store it in the database. You can call a stored procedure from any environment from which you can issue a SQL statement.

Stored procedures offer you advantages in these areas:

•	development

•	integrity

•	security

•	performance

•	memory allocation

For more information on stored procedures, including how to call stored procedures, see Chapter 7  of the ORACLE7 Server Application Developer's Guide.

When you create a procedure in Trusted ORACLE, it is labeled with your DBMS label.

The CREATE PROCEDURE command creates a procedure as a stand-alone schema object. You can also create a procedure as part of a package. For information on creating packages, see the CREATE PACKAGE command earlier in this chapter.

Example	This statement creates the procedure CREDIT in the schema SAM:

CREATE PROCEDURE sam.credit (acc_no IN NUMBER, amount IN NUMBER)

AS BEGIN

UPDATE accounts

SET balance = balance + amount

WHERE account_id = acc_no; 	END;

The CREDIT procedure credits a specified bank account with a specified amount. When you call the procedure, you must specify these arguments:

ACC_NO	This argument is the number of the bank account to be credited. The argument's datatype is NUMBER.

AMOUNT	This argument is the amount of the credit. The argument's datatype is NUMBER.

The procedure uses an UPDATE statement to increase the value in the BALANCE column of the ACCOUNTS table by the value of the argument AMOUNT for the account identified by the argument ACC_NO.

Related Topics

ALTER PROCEDURE, CREATE FUNCTION, CREATE PACKAGE, CREATE PACKAGE BODY, and DROP PROCEDURE commands.

________________________________________

CREATE PROFILE

Purpose

To create a profile. A profile is a set of limits on database resources. If you assign the profile to a user, that user cannot exceed these limits.

Prerequisites

You must have CREATE PROFILE system privilege.

Syntax

Keywords and Parameters

profile	is the name of the profile to be created.

SESSIONS_PER_USER	limits a user to integer concurrent sessions.

CPU_PER_

SESSION	limits the CPU time for a session. This value is expressed in hundredths of seconds.

CPU_PER_CALL	limits the CPU time for a call (a parse, execute, or fetch). This value is expressed in hundredths of seconds.

CONNECT_TIME	limits the total elapsed time of a session. This value is expressed in minutes.

IDLE_TIME	limits periods of continuous inactive time during a session. This value is expressed in minutes. Long-running queries and other operations are not subject to this limit.

LOGICAL_

READS_PER_

SESSION	limits the number of data blocks read in a session, including blocks read from memory and disk, to integer blocks.

LOGICAL_

READS_PER_

CALL	limits the number of data blocks read for a call to process a SQL statement (a parse, execute, or fetch) to integer blocks.

PRIVATE_SGA	limits the amount of private space a session can allocate in the shared pool of the System Global Area (SGA) to integer bytes. You can also use the K or M to specify this limit in kilobytes or megabytes. This limit only applies if you are using the multi-threaded server architecture. The private space for a session in the SGA includes private SQL and PL/SQL areas, but not shared SQL and PL/SQL areas.

COMPOSITE_

LIMIT	limits the total resource cost for a session. You must express the value of this parameter in service units.

ORACLE calculates the total resource cost as a weighted sum of these resources:

•	CPU_PER_SESSION

•	CONNECT_TIME

•	LOGICAL_READS_PER_SESSION

•	PRIVATE_SGA

For information on how to specify the weight for each session resource see the ALTER RESOURCE COST command earlier in this chapter.

UNLIMITED	indicates that a user assigned this profile can use an unlimited amount of this resource.

DEFAULT	omits a limit for this resource in this profile. A user assigned this profile is subject to the limit for this resource specified in the DEFAULT profile.

Usage Notes

 In Trusted ORACLE, the new profile is automatically labeled with your DBMS label.

 Using Profiles

A profile is a set of limits on database resources. You can use profiles to limit the database resources available to a user for a single call or a single session. ORACLE enforces resource limits in these ways:

•	If a user exceeds the CONNECT_TIME or IDLE_TIME session resource limit, ORACLE rolls back the current transaction and ends the session. When the user process next issues a call to ORACLE, an error message is returned.

•	If a user attempts to perform an operation that exceeds the limit for other session resources, ORACLE aborts the operation, rolls back the current statement, and immediately returns an error. The user can then commit or roll back the current transaction. The user must then end the session.

•	If a user attempts to perform an operation that exceeds the limit for a single call, ORACLE aborts the operation, rolls back the current statement, and returns an error message, leaving the current transaction intact.

 How to Limit Resources

To specify resource limits for a user, you must perform both of these operations:

Enable resource limits:   You can enable resource limits through one of these ways:

•	You can enable resources limits with the initialization parameter RESOURCE_LIMIT.

•	You can enable resource limits dynamically with the ALTER SYSTEM command. See the ALTER SYSTEM command earlier in this chapter.

Specify resource limits:      To specify a resource limit for a user, you must perform these steps:

1.	Create a profile that defines the limits using the CREATE PROFILE command.

2.	Assign the profile to the user using the CREATE USER or ALTER USER command.

Note that you can specify resource limits for users regardless of whether resource limits are enabled. However, ORACLE does not enforce these limits until you enable them.

 The DEFAULT Profile

ORACLE automatically creates a default profile named DEFAULT. This profile initially defines unlimited resources. You can change the limits defined in this profile with the ALTER PROFILE command.

Any user who is not explicitly assigned a profile is subject to the limits defined in the DEFAULT profile. Also, if the profile that is explicitly assigned to a user omits limits for some resources or specifies DEFAULT for some limits, the user is subject to the limits on those resources defined by the DEFAULT profile.

Example	This statement creates the profile SYSTEM_MANAGER:

CREATE PROFILE system_manager

LIMIT	SESSIONS_PER_USER                 UNLIMITED

CPU_PER_SESSION            UNLIMITED

CPU_PER_CALL               3000

CONNECT_TIME               45

LOGICAL_READS_PER_SESSION  DEFAULT

LOGICAL_READS_PER_CALL     1000

PRIVATE SGA             15K 	COMPOSITE_LIMIT            5000000

If you then assign the SYSTEM_MANAGER profile to a user, the user is subject to these limits in subsequent sessions:

•	The user can have any number of concurrent sessions.

•	In a single session, the user can consume an unlimited amount of CPU time.

•	A single call made by the user cannot consume more than 30 seconds of CPU time.

•	A single session cannot last for more than 45 minutes.

•	In a single session, the number of data blocks from memory and disk is subject to the limit specified in the DEFAULT profile.

•	A single call made by the user cannot read more than 1000 total data blocks from memory and disk.

•	A single session cannot allocate more than 15 kilobytes of memory in the SGA.

•	In a single session, the total resource cost cannot exceed 5 million service units. The formula for calculating the total resource cost is specified by the ALTER RESOURCE COST command.

•	Since the SYSTEM_MANAGER profile omits a limit for IDLE_TIME, the user is subject to the limit on this resource specified in the DEFAULT profile.

Related Topics

ALTER PROFILE, ALTER RESOURCE COST, ALTER SYSTEM, ALTER USER, and DROP PROFILE commands.

________________________________________

CREATE ROLE

Purpose

To create a role. A role is a set of privileges that can be granted to users or to other roles.

Prerequisites

You must have CREATE ROLE system privilege.

Syntax

Keywords and Parameters

role	is the name of the role to be created. Oracle Corporation recommends that the role contain at least one single-byte character regardless of whether the database character set also contains multi-byte characters.

NOT IDENTIFIED	indicates that a user granted the role need not be verified when enabling it.

IDENTIFIED	indicates that a user granted the role must be verified when enabling it with the SET ROLE command:

BY password	The user must specify the password to ORACLE when enabling the role. The password can only contain single-byte characters from your database character set regardless of whether this character set also contains multi-byte characters.

EXTERNALLY	The operating system verifies the user enabling to the role. Depending on the operating system, the user may have to specify a password to the operating system when enabling the role.

If you omit both the NOT IDENTIFIED option and the IDENTIFIED clause, the role defaults to NOT IDENTIFIED.

Usage Notes

In Trusted ORACLE, the new role is automatically labeled with your DBMS label.

 Using Roles

A role is a set of privileges that can be granted to users or to other roles. You can use roles to administer database privileges. You can add privileges to a role's privilege domain and then grant the role to a user. The user can then enable the role and exercise the privileges in the role's privilege domain. For information on enabling roles, see the ALTER USER command earlier in this chapter.

A role's privilege domain contains all privileges granted to the role and all privileges in the privilege domains of the other roles granted to it. A new role's privilege domain is initially empty. You can add privileges to a role's privilege domain with the GRANT command.

When you create a role, ORACLE grants you the role with ADMIN OPTION. The ADMIN OPTION allows you to perform these operations:

•	grant the role to another user or role

•	revoke the role from another user or role

•	alter the role to change the authorization needed to access it

•	drop the role

 Roles Defined by ORACLE

Some roles are defined by SQL scripts provided on your distribution media. These roles are predefined:

•	CONNECT

•	RESOURCE

•	DBA

•	EXP_FULL_DATABASE

•	IMP_FULL_DATABASE

The CONNECT, RESOURCE, and DBA roles are provided for compatibility with previous versions of ORACLE. Oracle encourages you to design your own roles for database security, rather rely on these roles. These roles may not be created automatically by future versions of ORACLE.

The EXP_FULL_DATABASE and IMP_FULL_DATABASE roles are provided for convenience in using the Import and Export utilities.

For more information on these roles, see Table 7 - 289 on page 7 - 289. ORACLE also creates other roles that authorize you to administer the database. On many operating systems, these roles are called OSOPER and OSDBA. Their names may be different on your operating system.

Example	This statement creates the role TELLER:

CREATE ROLE teller

IDENTIFIED BY cashflow

Users who are subsequently granted the TELLER role must specify the passwords CASHFLOW to enable the role.

Related Topics

ALTER ROLE, DROP ROLE, GRANT (System Privileges and Roles), REVOKE (System Privileges and Roles), and SET ROLE commands.


CHAPTER 6. COMMANDS - CREATE ROLLBACK SEGMENT TO DROP SYNONYM

________________________________________

CREATE ROLLBACK SEGMENT

Purpose

To create a rollback segment. A rollback segment is an object that is used by ORACLE to storedata necessary to reverse, or undo, changes made by transactions.

Prerequisites

You must have CREATE ROLLBACK SEGMENT system privilege. Also, you must have either space quota on the tablespace to contain the rollback segment or UNLIMITED TABLESPACE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the tablespace's label.

Syntax

Keyword and Parameters

PUBLIC	specifies that the rollback segment is public and is available to any instance. If you omit this option, the rollback segment is private and is only available to the instance naming it in its initialization parameter ROLLBACK_SEGMENTS.

rollback_segment	is the name of the rollback segment to be created.

TABLESPACE	identifies the tablespace in which the rollback segment is created. If you omit this option, ORACLE creates the rollback segment in the SYSTEM tablespace.

STORAGE	specifies the characteristics for the rollback segment. See the STORAGE clause on page 8 - 371.

Usage Notes

 The tablespace must be online for you to add a rollback segment toit.

When you create a rollback segment, it is initially offline. To make it available for transactions by your ORACLE instance, you must bring it online through one of these means:

•	ALTER ROLLBACK SEGMENT command

•	ROLLBACK_SEGMENTS initialization parameter

For more information on this command and the SQLCA, see the Programmer's Guide to the ORACLE Precompilers.

For more information on creating rollback segments and making them available, see Chapter 9 "Managing  of the ORACLE7 Server .

A tablespace can have multiple rollback segments. Generally, multiple rollback segments improve performance. When you create a rollback segment in Trusted ORACLE, it is labeled with your DBMS label.

Example

This statement creates a rollback segment in the SYSTEM tablespace:

CREATE PUBLIC ROLLBACK SEGMENT rbs_2

TABLESPACE system 	STORAGE (INITIAL 50K  NEXT 50K  OPTIMAL 150K  MAXEXTENTS 10)

Related Topics

CREATE TABLESPACE, CREATE DATABASE, ALTER ROLLBACK SEGMENT, and DROP ROLLBACK SEGMENT commands; STORAGE clause.

________________________________________

CREATE SCHEMA

Purpose

To create multiple tables and views and perform multiple grants in a single transaction.

Prerequisites

The CREATE SCHEMA statement can include CREATE TABLE, CREATE VIEW, and GRANT statements. To issue a CREATE SCHEMA statement, you must have the privileges necessary to issue the included statements.

Syntax

Keyword and Parameters

schema	is the name of the schema. The schema name must be the same as your ORACLE username.

CREATE TABLE command	is a CREATE TABLE statement to be issued as part of this CREATE SCHEMA statement. See the CREATE TABLE command on page 6 - 199.

CREATE VIEW command	is a CREATE VIEW statement to be issued as part of this CREATE SCHEMA statement. See the CREATE VIEW command on page 6 - 220.

GRANT command	is a GRANT statement (Objects Privileges) to be issued as part of this CREATE SCHEMA statement. See the GRANT command on page 7 - 292.

The CREATE SCHEMA statement only supports the syntax of these commands as defined by standard SQL, rather than the complete syntax supported by ORACLE. For information on which parts of the syntax for these commands are standard SQL and which are ORACLE extensions, see Appendix C  of this Manual.

Usage Notes

With the CREATE SCHEMA command, you can issue multiple Data Definition Language statements in a single transaction. To execute a CREATESCHEMA statement, ORACLE executes each included statement. If all statements execute successfully, ORACLE commits the transaction. If any statement results in an error, ORACLE rolls back all the statements.

Terminate a CREATE SCHEMA statement just as you would any other SQL statement using the terminator character specific to your tool. For example, if you issue a CREATE SCHEMA statement in SQL*Plus or SQL*DBA, terminate the statement with a semi-colon (;). Do not separate the individual statements within a CREATE SCHEMA statement with the terminator character.

The order in which you list the CREATE TABLE, CREATE VIEW, and GRANT statements is unimportant:

•	A CREATE VIEW statement can create a view that is based on a table that is created by a later CREATE TABLE statement.

•	A CREATE TABLE statement can create a table with a foreign key that depends on the primary key of a table that is created by a later CREATE TABLE statement.

•	A GRANT statement can grant privileges on a table or view that is created by a later CREATE TABLE or CREATE VIEW statement.

The statements within a CREATE SCHEMA statement can also reference existing objects:

•	A CREATE VIEW statement can create a view on a table that existed prior to the CREATE SCHEMA statement.

•	A GRANT statement can grant privileges on a previously existing object.

Example	This statement creates a schema named BLAIR for the user BLAIR:

CREATE SCHEMA AUTHORIZATION blair

CREATE TABLE sox (color  VARCHAR2(10)  PRIMARY KEY, quantity NUMBER)

CREATE VIEW red_sox

AS SELECT color, quantity FROM sox WHERE color = 'RED'

GRANT select ON red_sox TO waites

This statement creates the table SOX, creates the view RED_SOX, and grants SELECT privilege on the RED_SOX view to the user WAITES.

Related Topics

CREATE TABLE, CREATE VIEW, and GRANT commands.

________________________________________

CREATE SEQUENCE

Purpose

To create a sequence. A sequence is a database object from which multiple users may generate unique integers. You can use sequences to automatically generate primary key values.

Prerequisites

To create a sequence in your own schema, you must have CREATE SEQUENCE privilege.

To create a sequence in another user's schema, you must have CREATE ANY SEQUENCE privilege. If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of the owner of the schema to contain the sequence.

Syntax

Keywords and Parameters

schema	is the schema to contain the sequence. If you omit schema, ORACLE creates the sequence in your own schema.

sequence 	is the name of the sequence to be created.

INCREMENT BY	specifies the interval between sequence numbers. This value can be any positive or negative ORACLE integer, but it cannot be 0. If this value is negative, then the sequence descends. If the increment is positive, then the sequence ascends. If you omit this clause, the interval defaults to 1.

MINVALUE	specifies the sequence's minimum value.

NOMINVALUE	specifies a minimum value of 1 for an ascending sequence or -(10!!super!!26) for a descending sequence.

The default is NOMINVALUE.

MAXVALUE	specifies the maximum value the sequence can generate.

NOMAXVALUE	specifies a maximum value of 10<M^%-2>27 for an ascending sequence or -1 for a descending sequence.

The default is NOMAXVALUE.

START WITH	specifies the first sequence number to be generated. You can use this option to start an ascending sequence at a value greater than its minimum or to start a descending sequence at a value less than its maximum. For ascending sequences, the default value is the sequence's minimum value. For descending sequences, the default value is the sequence's maximum value.

CYCLE	specifies that the sequence continues to generate values after reaching either its maximum or minimum value. After an ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum.

NOCYCLE	specifies that the sequence cannot generate more values after reaching its maximum or minimum value.

The default is NOCYCLE.

CACHE	specifies how many values of the sequence ORACLE preallocates and keeps in memory for faster access. The minimum value for this parameter is 2. For sequences that cycle, this value must be less than the number of values in the cycle.

NOCACHE	specifies that values of the sequence are not preallocated.

If you omit both the CACHE parameter and the NOCACHE option, ORACLE caches 20 sequence numbers by default. However, if you are using ORACLE with the Parallel Server option in parallel mode and you specify the ORDER option, sequence values are never cached, regardless of whether you specify the CACHE parameter or the NOCACHE option.

ORDER	guarantees that sequence numbers are generated in order of request. You may want to use this option if you are using the sequence numbers as timestamps. Guaranteeing order is usually not important for sequences used to generate primary keys.

NOORDER	does not guarantee sequence numbers are generated in order of request.

If you omit both the ORDER and NOORDER options, ORACLE chooses NOORDER by default. Note that the ORDER option is only necessary to guarantee ordered generation if you are using ORACLE with the Parallel Server option in parallel mode. If you are using exclusive mode, sequence numbers are always generated in order.

Usage Notes

 If you are using Trusted ORACLE, the new sequence is automaticallylabeled with your DBMS label.

 Using Sequences

You can use sequence numbers to automatically generate unique primary key values for your data, and you can also coordinate the keys across multiple rows or tables.

Values for a given sequence are automatically generated by special ORACLE routines and, consequently, sequences avoid the performance bottleneck which results from implementation of sequences at the application level. For example, one common application-level implementation is to force each transaction to lock a sequence number table, increment the sequence, and then release the table. Under this implementation, only one sequence number may be generated at a time. In contrast, ORACLE sequences permit the simultaneous generation of multiple sequence numbers while guaranteeing that every sequence number is unique.

When a sequence number is generated, the sequence is incremented,  independent of the transaction committing or rolling back. If two users concurrently increment the same sequence, the sequence numbers each user sees may have gaps because sequence numbers are being generated by the other user. One user can never see the sequence number generated by another user. Once a sequence value is generated by one user, that user can continue to access that value regardless of whether the sequence is incremented by another user.

Because sequence numbers are generated independently of tables, the same sequence can be used for one or for multiple tables. It is possible that individual sequence numbers will appear to be skipped, because they were generated and used in a transaction that ultimately  rolled back. Additionally, a single user may not realize that other users are drawing from the same sequence.

 Sequence Defaults

The sequence defaults are designed so that if you specify none of the clauses, you create an ascending sequence that starts with 1 and increases by 1 with no upper limit. Specifying only INCREMENT BY -1 creates a descending sequence that starts with -1 and decreases with no lower limit.

 Incrementing Sequence Values

You can create a sequence so that its values increment in one of these fashions:

•	The sequence values increment without bound.

•	The sequence values increment to a predefined limit and then stop.

•	The sequence values increment to a predefined limit and then restart.

To create a sequence that increments without bound, omit the MAXVALUE parameter or specify the NOMAXVALUE option for ascending sequences or omit the MINVALUE parameter or specify the NOMINVALUE for descending sequences.

To create a sequence that stops at a predefined limit, specify a value for the MAXVALUE parameter for an ascending sequence or a value for the MINVALUE parameter for a descending sequence. Also specify the NOCYCLE option. Any attempt to generate a sequence number once the sequence has reached its limit results in an error.

To create a sequence that restarts after reaching a predefined limit, specify values for both the MAXVALUE and MINVALUE parameters. Also specify the CYCLE option.

The value of the START WITH parameter establishes the initial value generated after the sequence is created. Note that this value is not necessarily the value to which an ascending cycling sequence cycles after reaching its maximum or minimum value.

 Caching Sequence Numbers

The number of values cached in memory for a sequence is specified by the value of the sequence's CACHE parameter. Cached sequences allow faster generation of sequence numbers. A cache for a given sequence is populated at the first request for a number from that sequence. The cache is repopulated every CACHE requests. In the event of system failure, all cached sequence values that have not been used in committed Data Manipulation Language statements are lost. The potential number of lost values is equal to the value of the CACHE parameter.

A CACHE of 20 future sequence numbers is the default.

 Accessing and Incrementing Sequence Values

Once a sequence is created, you can access its values in SQL statements with these pseudocolumns:

CURRVAL 	returns the current value of the sequence.

NEXTVAL	increments the sequence and returns the new value.

For more information on using these pseudocolumns, see the section "Pseudocolumns" beginning on page 2 - 37.

Example	This statement creates the sequence ESEQ:

CREATE SEQUENCE eseq

INCREMENT BY 10

The first reference to ESEQ.NEXTVAL returns 1. The second returns 11. Each subsequent reference will return a value 10 greater than the one previous.

Related Topics

ALTER SEQUENCE and DROP SEQUENCE commands.

________________________________________

CREATE SNAPSHOT

Purpose

To create a snapshot. A snapshot is a table that contains the results of a query of one or more tables or views, often located on a remote database.

Prerequisites

To create a snapshot in your own schema, you must have CREATE SNAPSHOT system privilege. To create a snapshot in another user's schema, you must have CREATE ANY SNAPSHOT system privilege.

Before a snapshot can be created, the user SYS must run the SQL script DBMSSNAP.SQL on both the database to contain the snapshot and the database(s) containing the tables and views of the snapshot's query. This script creates the package SNAPSHOT which contains both public and private stored procedures used for refreshing the snapshot and purging the snapshot log. The exact name and location of this script may vary depending on your operating system.

When you create a snapshot, ORACLE creates a table, two views, and an index in the schema of the snapshot. ORACLE uses these objects to maintain the snapshot's data. You must have the privileges necessary to create these objects. For information on these privileges, see the CREATE TABLE, CREATE VIEW, and CREATE INDEX commands.

The owner of the schema containing the snapshot must have either space quota on the tablespace to contain the snapshot or UNLIMITED TABLESPACE system privilege. Also, both you (the creator) and the owner must also have the privileges necessary to issue the snapshot's query. For information on these privileges, see the SELECT command later in this chapter.

To create a snapshot, you must be using ORACLE with the procedural option. To create a snapshot on a remote table or view, you must also be using the distributed option.

Syntax

Keywords and Parameters

schema	is the schema to contain the snapshot. If you omit schema, ORACLE creates the snapshot in your schema.

snapshot	is the name of the snapshot to be created.

ORACLE chooses names for the table, views, and index used to maintain the snapshot by prefixing and suffixing the snapshot name. To limit these names to 30 bytes and allow them to contain the entire snapshot name, Oracle Corporation recommends that you limit your snapshot names to 19 bytes.

PCTFREE PCTUSED INITRANS MAXTRANS	establishes values for these parameters for the internal table ORACLE uses to maintain the snapshot's data.

TABLESPACE	specifies the tablespace in which the snapshot is to be created. If you omit this option, ORACLE creates the snapshot in the default tablespace of the owner of the snapshot's schema.

STORAGE	establishes storage characteristics for the table ORACLE uses to maintain the snapshot's data.

CLUSTER	creates the snapshot as part of the specified cluster. Since a clustered snapshot uses the cluster's space allocation, do not use the PCTFREE, PCTUSED, INITRANS, MAXTRANS, TABLESPACE, or STORAGE parameters in conjunction with the CLUSTER option.

USING INDEX	specifies parameters for the index ORACLE creates to maintain the snapshot. You can choose the values of the INITRANS, MAXTRANS, TABLESPACE, STORAGE, and PCTFREE parameters for the index.

For information on the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters, see the CREATE TABLE command later in this chapter. For information on the STORAGE clause, see page 8 - 371.

REFRESH	specifies how and when ORACLE automatically refreshes the snapshot:

FAST	specifies a fast refresh, or a refresh using only the updated data stored in the snapshot log associated with the master table.

COMPLETE	specifies a complete refresh, or a refresh that re-executes the snapshot's query.

FORCE	specifies a fast refresh if one is possible or complete refresh if a fast refresh is not possible. ORACLE decides whether a fast refresh is possible at refresh time.

If you omit the FAST, COMPLETE, and FORCE options, ORACLE uses FORCE by default.

START WITH	specifies a date expression for the first automatic refresh time.

NEXT	specifies a date expression for calculating the interval between automatic refreshes.

Both the START WITH and NEXT values must evaluate to a time in the future. If you omit the START WITH value, ORACLE determines the first automatic refresh time by evaluating the NEXT expression when you create the snapshot. If you specify a START WITH value but omit the NEXT value, ORACLE refreshes the snapshot only once. If you omit both the START WITH and NEXT values or if you omit the REFRESH clause entirely, ORACLE does not automatically refresh the snapshot.

AS subquery	specifies the snapshot query. When you create the snapshot, ORACLE executes this query and places the results in the snapshot. The select list can contain up to 253 expressions. For the syntax of a snapshot query, see the syntax description of subquery on page 8 - 362. The syntax of a snapshot query is subject to the same restrictions as a view query. For a list of these restrictions, see the CREATE VIEW command later in this chapter.

Oracle Corporation recommends that you qualify each table and view in the FROM clause of the snaphshot query with the schema containing it.

Usage Notes

 A snapshot is a table that containsthe results of a query of one or more tables or views, often locatedon a remote database. The tables or views in the query are called master tables. The databases containing the master tables are called the master databases. Note that a snapshot query cannot select from tables or views owned by the user SYS.

Snapshots are useful in distributed databases. Snapshots allow you to maintain read-only copies of remote data on your local node. You can select data from a snapshot as if it were a table or view. However, you cannot modify data in a snapshot.

For more information on the applications and advantages of snapshots, see Chapter 12 "Managing Table Snapshots"  of the ORACLE7 Server Application Developer's Guide.

Types of Snapshots

You can create these types of snapshots:

simple	A simple snapshot is one in which the snapshot query selects rows from only one master table. This master table must be a table, not a view. Each row of a simple snapshot must be based on a single row of this table. The query for a simple snapshot cannot contain any of these SQL constructs:

•	GROUP BY clause

•	CONNECT BY clause

•	subqueries

•	joins

•	set operations

complex	A complex snapshot is one in which the snapshot query contains one or more of the constructs not allowed in the query of a simple snapshot. A complex snapshot can be based on multiple master tables on multiple master databases.

Refreshing Snapshots

Because a snapshot's master tables can be modified, the data in a snapshot must occasionally be updated to ensure that the snapshot accurately reflects the data currently in its master tables. The process of updating a snapshot for this purpose is called refreshing the snapshot. With the REFRESH clause of the CREATE SNAPSHOT command, you can schedule the times and specify the mode for ORACLE to automatically refresh the snapshot.

After you create a snapshot, you can subsequently change its automatic refresh mode and time with the REFRESH clause of the ALTER SNAPSHOT command. You can also refresh a snapshot immediately with the DBMS_SNAPSHOT.REFRESH() procedure.

 Specifying Refresh Modes

You can use the FAST or COMPLETE options of the REFRESH clause to specify the refresh mode.

Fast      To perform a fast refresh, ORACLE updates the snapshot with the changes to the master table recorded in its snapshot log. For more information on snapshot logs, see the CREATE SNAPSHOT LOG command later in this chapter.

ORACLE can only perform a fast refresh if all of these conditions are true:

•	The snapshot is a simple snapshot.

•	The snapshot's master table has a snapshot log.

•	The snapshot log was created before the snapshot was last refreshed or created.

If you specify a fast refresh and all of these conditions are true, then ORACLE performs a fast refresh. If any of the conditions are not true, ORACLE returns an error at refresh time and does not refresh the snapshot.

Complete      To perform a complete refresh, ORACLE executes the snapshot query and places the results in the snapshot. If you specify a complete refresh, ORACLE performs a complete refresh regardless of whether a fast refresh is possible.

A fast refresh is often faster than a complete refresh because it sends less data from the master database across the network to the snapshot's database. A fast refresh sends only changes to master table data, while a complete refresh sends the complete result of the snapshot query.

You can also use the FORCE option of the REFRESH clause to allow ORACLE to decide how to refresh the snapshot at the scheduled refresh time. If a fast refresh is possible based on the fast refresh conditions, then ORACLE performs a fast refresh. If a fast refresh is not possible, then ORACLE performs a complete refresh.

 Specifying Automatic Refresh Times

To cause ORACLE to automatically refresh a snapshot, you must perform these tasks:

1.	Specify the START WITH and NEXT parameters in the REFRESH clause of the CREATE SNAPSHOT statement. These parameters establish the time of the first automatic refresh time and the interval between automatic refreshes.

2.	Enable one or more snapshot refresh processes using the initialization parameters SNAPSHOT_REFRESH_PROCESSES, SNAPSHOT_REFRESH_INTERVAL, SNAPSHOT_REFRESH_KEEP_CONNECTIONS. The snapshot refresh processes then examine the automatic refresh time of each snapshot in the database. For each snapshot that is scheduled to be refreshed at or before the current time, one of the snapshot refresh processes performs these operations:

•	re-evaluates the snapshot's NEXT value to determine the next automatic refresh time

•	refreshes the snapshot

•	stores the next automatic refresh time in the data dictionary

For information on these initialization parameters, see Appendix A "Initialization Parameter Files" of the ORACLE7 Server Administrator's Guide.

Example I	This statement creates the simple snapshot EMP_SF that contains the data from a SCOTT's employee table in New York:

CREATE SNAPSHOT emp_sf

PCTFREE 5  PCTUSED 60

TABLESPACE users

STORAGE  INITIAL 50K  NEXT 50K

REFRESH FAST NEXT sysdate + 7 	AS SELECT * FROM scott.emp@ny

Since this statement does not include a START WITH parameter, ORACLE determines the first automatic refresh time by evaluating the NEXT value using the current SYSDATE. Provided a snapshot log currently exists for the employee table in New York, ORACLE performs a fast refresh of the snapshot every 7 days, beginning 7 days after the snapshot is created.

This statement also establishes storage characteristics for the table that ORACLE uses to maintain the snapshot.

Example II	This statement creates the complex snapshot ALL_EMPS that queries the employee tables in Dallas and Baltimore:

CREATE SNAPSHOT all_emps

PCTFREE 5  PCTUSED 60

TABLESPACE users

STORAGE  INITIAL 50K  NEXT 50K

USING INDEX  STORAGE  INITIAL 25K  NEXT 25K

REFRESH START WITH ROUND(SYSDATE + 1) + 11/24

        NEXT NEXT_DAY(TRUNC(SYSDATE, 'MONDAY') + 15/24

AS SELECT * FROM fran.emp@dallas

UNION 	   SELECT * FROM marco.emp@balt

ORACLE automatically refreshes this snapshot tomorrow at 11:00am. and subsequently every Monday at 3:00pm. Since this command does not specify either fast or complete refreshes, ORACLE must decide how to refresh the snapshot. Since ALL_EMPS is a complex snapshot, ORACLE must perform a complete refresh.

This statement also establishes storage characteristics for both the table and the index that ORACLE uses to maintain the snapshot:

•	The first STORAGE clause establishes the sizes of the first and second extents of the table as 50 kilobytes each.

•	The second STORAGE clause (appearing with the USING INDEX option) establishes the sizes of the first and second extents of the index as 25 kilobytes each.

Related Topics

ALTER SNAPSHOT, CREATE SNAPSHOT LOG, and DROP SNAPSHOT commands.

________________________________________

CREATE SNAPSHOT LOG

Purpose

To create a snapshot log. A snapshot log is a table associated with the master table of a snapshot. ORACLE stores changes to the master table's data in the snapshot log and then uses the snapshot log to refresh the master table's snapshots.

Prerequisites

You must have the privileges necessary to create a table in the schema of the master table. For information on these privileges, see the CREATE TABLE command later in this chapter.

Before a snapshot log can be created, the user SYS must run the SQL script DBMSSNAP.SQL on the database containing the master table. This script creates the package SNAPSHOT which contains both public and private stored procedures used for refreshing the snapshot and purging the snapshot log. The exact name and location of this script may vary depending on your operating system.

You must also have the privileges to create a trigger on the master table. For information on these privileges, see the CREATE TRIGGER command later in this chapter.

To create a snapshot log, you must be using ORACLE with the procedural option.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the label of the tablespace in which the snapshot log is to be stored.

Syntax

Keywords and Parameters

schema	is the schema containing the snapshot log's master table. If you omit schema, ORACLE assumes the master table is contained in your own schema. ORACLE creates the snapshot log in the schema of its master table. You cannot create a snapshot log for a table in the schema of the user SYS.

table	is the name of the master table for which the snapshot log is to be created. You cannot create a snapshot log for a view.

ORACLE chooses names for the table and trigger used to maintain the snapshot log by prefixing and suffixing the master table name. To limit these names to 30 bytes and allow them to contain the entire master table name, Oracle Corporation recommends that you limit master table names to 20 bytes.

PCTFREE PCTUSED INITRANS MAXTRANS	establishes values for these parameters for the snapshot log. See the descriptions of these parameters in the CREATE TABLE command later in this chapter.

TABLESPACE	specifies the tablespace in which the snapshot log is to be created. If you omit this option, ORACLE creates the snapshot log in the default tablespace the owner of the snapshot log's schema.

STORAGE	establishes storage characteristics for the snapshot log. See the STORAGE clause on page 8 - 371.

Usage Notes

If you are using Trusted ORACLE, the new snapshot log is automaticallylabeled with your DBMS label.

 Using Snapshot Logs

A snapshot log is a table that is associated with the master table of a snapshot. When changes are made to the master table's data, ORACLE adds rows describing these changes to the snapshot log. Later ORACLE can use these rows to refresh snapshots based on the master table. This process is called a fast refresh. Without a snapshot log, ORACLE must execute the snapshot query to refresh the snapshot. This process is called a complete refresh. In most cases, a fast refresh takes less time than a complete refresh.

A snapshot log is located in the master database in the same schema as the master table. You can create only a single snapshot log for a master table. ORACLE can use this snapshot log to perform fast refreshes for all simple snapshots based on the master table. ORACLE records changes in the snapshot log only if there is a simple snapshot based on the master table. For more information on snapshots, including how ORACLE refreshes snapshots, see the CREATE SNAPSHOT command earlier in this chapter and Chapter 12 "Managing Table Snapshots" of the ORACLE7 Server Application Developer's Guide.

Example	This statement creates a snapshot log on the employee table:

CREATE SNAPSHOT LOG ON emp

PCTFREE 5

TABLESPACE users

STORAGE (INITIAL 10K  NEXT 10K  PCTINCREASE 50)

ORACLE can use this snapshot log to perform a fast refresh on any simple snapshot subsequently created on the EMP table.

Related Topics

ALTER SNAPSHOT LOG, CREATE SNAPSHOT, and DROP SNAPSHOT LOG commands.

________________________________________

CREATE SYNONYM

Purpose

To create a synonym. A synonym is an alternative name for a table, view, sequence, procedure, stored function, package, snapshot, or another synonym.

Prerequisites

To create a private synonym in your own schema, you must have CREATE SYNONYM system privilege.

To create a private synonym in another user's schema, you must have CREATE ANY SYNONYM system privilege. If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of the owner of schema to contain the synonym.

To create a PUBLIC synonym, you must have CREATE PUBLIC SYNONYM system privilege.

Syntax

Keywords and Parameters

PUBLIC	creates a public synonym. Public synonyms are accessible to all users. If you omit this option, the synonym is private and is accessible only within its schema.

schema	is the schema to contain the synonym. If you omit schema, ORACLE creates the synonym in your own schema.

synonym	is the name of the synonym to be created.

FOR	identifies the object for which the synonym is created. If you do not qualify object with schema, ORACLE assumes that the object is in your own schema. The object can be of these types:

•	table

•	view

•	sequence

•	stored procedure, function, or package

•	snapshot

•	synonym

The object cannot be contained in a package. Note that the object need not currently exist and you need not have privileges to access the object.

You can use a complete or partial dblink to create a synonym for an object on a remote database where the object is located. For more information on referring to database links, see the section "Referring to Objects in Remote  on page 2 - 13. If you specify dblink and omit schema, the synonym refers to an object in the schema specified by the database link. Oracle Corporation recommends that you specify the schema containing the object in the remote database.

If you omit dblink, ORACLE assumes the object is located on the local database.

Usage Notes

In Trusted ORACLE, the new synonym is automatically labeled with your DBMS label.

A synonym can be used to stand for its base object in any Data Manipulation Language statement:

•	SELECT

•	INSERT

•	UPDATE

•	DELETE

•	EXPLAIN PLAN

•	LOCK TABLE

Synonyms can also be used in these Data Definition Language statements:

•	AUDIT

•	NOAUDIT

•	GRANT

•	REVOKE

•	COMMENT

Synonyms are used for security and convenience. Creating a synonym for an object allows you to:

•	reference the object without specifying its owner

•	reference the object without specifying the database on which it is located

•	provide another name for the object

Synonyms provide both data independence and location transparency; synonyms permit applications to function without modification regardless of which user owns the table or view and regardless of which database holds the table or view.

Scope of Synonyms

A private synonym name must be distinct from all other objects in its schema. ORACLE attempts to resolve references to objects at the schema level before resolving them at the PUBLIC synonym level. ORACLE only uses a public synonym when resolving references to an object if both of these cases are true:

•	the object is not prefaced by a schema

•	the object is not followed by a database link

For example, assume the schemas SCOTT and BLAKE each contain tables named DEPT and the user SYSTEM creates a PUBLIC synonym named DEPT for BLAKE.DEPT. If the user SCOTT then issues the following statement, ORACLE returns rows from SCOTT.DEPT:

SELECT *

FROM dept

To retrieve rows from BLAKE.DEPT, the user SCOTT must preface DEPT with the schema name:

SELECT *

 	FROM blake.dept

If the user ADAM's schema does not contain an object named DEPT, then ADAM can access the DEPT table in BLAKE's schema by using the public synonym DEPT:

SELECT *

FROM dept

Example I	To define the synonym MARKET for the table MARKET_RESEARCH in the schema SCOTT, issue this statement:

CREATE SYNONYM market

FOR scott.market_research

Example II	To create a PUBLIC synonym for the EMP table in the schema SCOTT on the remote SALES database, you could issue this statement:

CREATE PUBLIC SYNONYM emp

FOR scott.emp@sales

Note that a synonym may have the same name as the base table provided the base table is contained in another schema.

Related Topics

CREATE DATABASE LINK, CREATE TABLE, and CREATE VIEW commands.

________________________________________

CREATE TABLE

Purpose

To create a table, the basic structure to hold user data, specifying this information:

•	column definitions

•	integrity constraints

•	the table's tablespace

•	storage characteristics

•	an optional cluster

•	data from an arbitrary query

Prerequisites

To create a table in your own schema, you must have CREATE TABLE system privilege. To create a table in another user's schema, you must have CREATE ANY TABLE system privilege. Also, the owner of the schema to contain the table must have either space quota on the tablespace to contain the table or UNLIMITED TABLESPACE system privilege.

Syntax

Keywords and Parameters

schema	is the schema to contain the table. If you omit schema, ORACLE creates the table in your own schema.

table	is the name of the table to be created.

column	specifies the name of a column of the table. A table can have up to 254 columns.

datatype	is the datatype of a column. Datatypes are defined on page 2 - 21.

You can omit the datatype only if the statement also designates the column as part of a foreign key in a referential integrity constraint. ORACLE automatically assigns the column the datatype of the corresponding column of the referenced key of the referential integrity constraint.

DEFAULT	specifies a value to be assigned to the column if a subsequent INSERT statement omits a value for the column. The datatype of the expression must match the datatype of the column. The column must also be long enough to hold this expression. For the syntax of expr, see page NO TAG. A DEFAULT expression cannot contain references to other columns, the pseudocolumns CURRVAL, NEXTVAL, LEVEL, and ROWNUM, or date constants that are not fully specified.

column_constraint	defines an integrity constraint as part of the column definition. See the syntax description of column_constraint on page 5 - 119.

table_constraint	defines an integrity constraint as part of the table definition. See the syntax description of table_constraint on page 5 - 119.

PCTFREE	specifies the percentage of space in each of the table's data blocks reserved for future updates to the table's rows. The value of PCTFREE must be a positive integer from 1 to 99. A value of 0 allows the entire block to be filled by inserts of new rows. The default value is 10. This value reserves 10% of each block for updates to existing rows and allows inserts of new rows to fill a maximum of 90% of each block.

PCTFREE has the same function in the commands that create and alter clusters, indexes, snapshots, and snapshot logs. The combination of PCTFREE and PCTUSED determines whether inserted rows will go into existing data blocks or into new blocks.

PCTUSED	specifies the minimum percentage of used space that ORACLE maintains for each data block of the table. A block becomes a candidate for row insertion when its used space falls below PCTUSED. PCTUSED is specified as a positive integer from 1 to 99 and defaults to 40.

PCTUSED has the same function in the commands that create and alter clusters, snapshots, and snapshot logs.

The sum of PCTFREE and PCTUSED must be less than 100. You can use PCTFREE and PCTUSED together use space within a table more efficiently. For information on the performance effects of different values PCTUSED and PCTFREE, see Chapter 22 "Tuning I/O" of the ORACLE7 Server Administrator's Guide.

INITRANS	specifies the initial number of transaction entries allocated within each data block allocated to the table. This value can range from 1 to 255 and defaults to 1. In general, you should not change the INITRANS value from its default.

Each transaction that updates a block requires a transaction entry in the block. The size of a transaction entry depends on your operating system.

This parameter ensures that a minimum number of concurrent transactions can update the block and helps avoid the overhead of dynamically allocating a transaction entry.

The INITRANS parameter serves the same purpose in clusters, indexes, snapshots, and snapshot logs as in tables. The minimum and default INITRANS value for a cluster or index is 2, rather than 1.

MAXTRANS	specifies the maximum number of concurrent transactions that can update a data block allocated to the table. This limit does not apply to queries. This value can range from 1 to 255 and the default is a function of the data block size. You should not change the MAXTRANS value from its default.

If the number concurrent transactions updating a block exceeds the INITRANS value, ORACLE dynamically allocates transaction entries in the block until either the MAXTRANS value is exceeded or the block has no more free space.

The MAXTRANS parameter serves the same purpose in clusters, snapshots, and snapshot logs as in tables.

TABLESPACE	specifies the tablespace in which ORACLE creates the table. If you omit this option, then ORACLE creates the table in the default tablespace of the owner of the schema containing the table.

STORAGE	specifies the storage characteristics for the table. This clause has performance ramifications for large tables. Storage should be allocated to minimize dynamic allocation of additional space. See the STORAGE clause on page 8 - 371.

CLUSTER	specifies that the table is to be part of the cluster. The columns listed in this clause are the table columns that correspond to the cluster's columns. Generally, the cluster columns of a table are the column or columns that comprise its primary key or a portion of its primary key.

Specify one column from the table for each column in the cluster key. The columns are matched by position, not by name. Since a clustered table uses the cluster's space allocation, do not use the PCTFREE, PCTUSED, INITRANS, or MAXTRANS parameters, the TABLESPACE option, or the STORAGE clause in conjunction with the CLUSTER option.

ENABLE	enables an integrity constraint. See the ENABLE clause on page 7 - 263.

DISABLE	disables an integrity constraint. See the DISABLE clause on page 6 - 235.

Constraints specified in the ENABLE and DISABLE clauses of a CREATE TABLE statement must be defined in the statement. You can also enable and disable constraints with the ENABLE and DISABLE keywords of the CONSTRAINT clause. If you define a constraint but do not explicitly enable or disable it, ORACLE enables it by default.

You cannot use the ENABLE and DISABLE clauses in a CREATE TABLE statement to enable and disable triggers.

AS subquery	inserts the rows returned by the subquery into the table upon its creation. See the syntax description of subquery on page 8 - 357.

The number of columns in the table must equal the number of expressions in the subquery. The column definitions can only specify column names, default values, and integrity constraints, not datatypes. ORACLE derives datatypes and lengths from the subquery. ORACLE also follows these rules for integrity constraints:

•	ORACLE also automatically defines any NOT NULL constraints on columns in the new table that existed on the corresponding columns of the selected table if the subquery selects the column rather than an expression containing the column.

•	A CREATE TABLE statement cannot contain both the AS clause and a referential integrity constraint definition.

•	If a CREATE TABLE statement contains both the AS clause and a CONSTRAINT clause or an ENABLE clause with the EXCEPTIONS option, ORACLE ignores the EXCEPTIONS option. If any rows violate the constraint, ORACLE does not create the table and returns an error message.

If all expressions in the subquery are columns, rather than expressions, you can omit the columns from the table definition entirely. In this case, the names of the columns of table are the same as the columns in the subquery.

Usage Notes

Tables are created with no data unless a query is specified. Youcan add rows to a table with the INSERT command.

After creating a table, you can define additional columns and integrity constraints with the ADD clause of the ALTER TABLE command. You can change the definition of an existing column with the MODIFY clause of the ALTER TABLE command. To modify an integrity constraint, you must drop the constraint and redefine it.

Example I

To define the EMP table owned by SCOTT, you could issue this statement:

CREATE TABLE scott.emp

(empno     NUMBER        CONSTRAINT pk_emp PRIMARY KEY,

 ename     VARCHAR2(10)  CONSTRAINT nn_ename NOT NULL

                         CONSTRAINT upper_ename

                              CHECK (ename = UPPER(ename)),

 job       VARCHAR2(9),

 mgr       NUMBER        CONSTRAINT fk_mgr

                              REFERENCES scott.emp(empno),

 hiredate  DATE          DEFAULT SYSDATE,

 sal       NUMBER(10,2)  CONSTRAINT ck_sal CHECK (sal > 500),

 comm      NUMBER(9,0)   DEFAULT NULL,

 deptno    NUMBER(2)     CONSTRAINT nn_deptno NOT NULL

                         CONSTRAINT fk_deptno

REFERENCES scott.dept(deptno) )

PCTFREE 5 PCTUSED 75

This table contains 8 columns. For example, the EMPNO column is of datatype NUMBER and has an associated integrity constraint named PK_EMP. The HIRDEDATE column is of datatype DATE and has a default value of SYSDATE.

This table definition specifies a PCTFREE of 5 and a PCTUSED of 75, which is appropriate for a relatively static table. The definition also defines integrity constraints on the columns of the EMP table.

Example II	To define the sample table SALGRADE in the HUMAN_RESOURCE tablespace with a small storage and limited allocation potential, issue this statement:

CREATE TABLE salgrade

( grade  NUMBER  CONSTRAINT pk_salgrade

                   PRIMARY KEY

                   USING INDEX TABLESPACE users_a,

  losal  NUMBER,

  hisal  NUMBER )

TABLESPACE human_resource

STORAGE (INITIAL 6144  NEXT 6144

 MINEXTENTS 1  MAXEXTENTS 5

 PCTINCREASE 5)

This statement also defines a PRIMARY KEY constraint on the GRADE column and specifies that the index ORACLE creates to enforce this constraint is created in the USERS_A tablespace.

For more examples of defining integrity constraints, see the CONSTRAINT clause on page 5 - 119. For examples of enabling and disabling integrity constraints, see the ENABLE and DISABLE clauses on pages 7 - 263 and 6 - 235, respectively.

Related Topics

ALTER TABLE, CREATE CLUSTER, CREATE INDEX, CREATE TABLESPACE, and DROP TABLE commands; CONSTRAINT, DISABLE, ENABLE, and STORAGE clauses.

________________________________________

CREATE TABLESPACE

Purpose

To create a tablespace. A tablespace is an allocation of space in the database that can contain objects.

Prerequisites

You must have CREATE TABLESPACE system privilege. Also, the SYSTEM tablespace must containat least two rollback segments including the SYSTEM rollback segment.

Syntax

Keywords and Parameters

tablespace	is the name of the tablespace to be created.

DATAFILE 	specifies the data file or files to comprise the tablespace. See the syntax description of filespec  on page 7 - 279.

DEFAULT STORAGE	specifies the default storage parameters for all objects created in the tablespace. For information on storage parameters, see the STORAGE clause on page 8 - 371.

ONLINE	makes the tablespace available immediately after creation to users who have been granted access to the tablespace.

OFFLINE	makes the tablespace unavailable immediately after creation.

If you omit both the ONLINE and OFFLINE options, ORACLE creates the tablespace online by default. The data dictionary view DBA_TABLESPACES indicates whether each tablespace is online or offline.

Usage Notes

A tablespace is an allocation of space in the database thatcan contain any of these segments:

•	data segments

•	index segments

•	rollback segments

•	temporary segments

All databases have at least one tablespace, SYSTEM, which ORACLE creates automatically when you create the database.

When you create a tablespace, it is initially a read-write tablespace. After creating the tablespace, you can subsequently use the ALTER TABLESPACE command to take it offline or online, add data files to it, or make it a read-only tablespace.

Many schema objects have associated segments that occupy space in the database. These objects are located in tablespaces. The user creating such an object can optionally specify the tablespace to contain the object. The owner of the schema containing the object must have space quota on the object's tablespace. You can assign space quota on a tablespace to a user with the QUOTA clause of the CREATE USER or ALTER USER commands.

Example	This command creates a tablespace named TABSPACE_2 with one database:

CREATE TABLESPACE tabspace_2

DATAFILE 'diska:tabspace_file2.dat' SIZE 20M

DEFAULT STORAGE (INITIAL 10K  NEXT 50K

                 MINEXTENTS 1  MAXEXTENTS 999

                 PCTINCREASE 10)

ONLINE

Related Topics

ALTER TABLESPACE and DROP TABLESPACE commands.

________________________________________

CREATE TRIGGER

Purpose

To create and enable a database trigger. A database trigger is a stored PL/SQL block that is associated with a table. ORACLE automatically executes a trigger when a specified SQL statement is issued against the table.

Prerequisites

Before a trigger can be created, the user SYS must run the SQL script DBMSSTDX.SQL. The exact name and location of this script may vary depending on your operating system.

To issue this statement, you must have one of these system privileges:

CREATE  TRIGGER	This system privilege allows you to create a trigger in your own schema on a table in your own schema.

CREATE ANY TRIGGER	This system privilege allows you to create a trigger in any user's schema on a table in any user's schema.

If the trigger issues SQL statements or calls procedures or functions, then the owner of the schema to contain the trigger must have the privileges necessary to perform these operations. These privileges must be granted directly to the owner, rather than acquired through roles.

To create a trigger, you must be using ORACLE with the procedural option.

Syntax

Keywords and Parameters

OR REPLACE	recreates the trigger if it already exists. You can use this option to change the definition of an existing trigger without first dropping it.

schema	is the schema to contain the trigger. If you omit schema, ORACLE creates the trigger in your own schema.

trigger	is the name of the trigger to be created.

BEFORE	indicates that ORACLE fires the trigger before executing the triggering statement.

AFTER	indicates that ORACLE fires the trigger after executing the triggering statement.

DELETE	indicates that ORACLE fires the trigger whenever a DELETE statement removes a row from the table.

INSERT	indicates that ORACLE fires the trigger whenever an INSERT statement adds a row to table.

UPDATE  OF	indicates that ORACLE fires the trigger whenever an UPDATE statement changes a value in one of the columns specified in the OF clause. If you omit the OF clause, ORACLE fires the trigger whenever an UPDATE statement changes a value in any column of the table.

ON	specifies the schema and name of the table on which the trigger is to be created. If you omit schema, ORACLE assumes the table is in your own schema. You cannot create a trigger on a table in the schema SYS.

REFERENCING	specifies correlation names. You can use correlation names in the PL/SQL block and WHEN clause of a row trigger to refer specifically to old and new values of the current row. The default correlation names are OLD and NEW. If your row trigger is associated with a table named OLD or NEW, you can use this clause to specify different correlation names to avoid confusion between the table name and the correlation name.

FOR EACH ROW	designates the trigger to be a row trigger. ORACLE fires a row trigger once for each row that is affected by the triggering statement and meets the optional trigger constraint defined in the WHEN clause.

If you omit this clause, the trigger is a statement trigger. ORACLE fires a statement trigger only once when the triggering statement is issued if the optional trigger constraint is met.

WHEN	specifies the trigger restriction. The trigger restriction contains a SQL condition that must be satisfied for ORACLE to fire the trigger. See the syntax description of condition on page NO TAG. This condition must contain correlation names and cannot contain a query.

You can only specify a trigger restriction for a row trigger. ORACLE evaluates this condition for each row affected by the triggering statement.

pl/sql_block	is the PL/SQL block that ORACLE executes to fire the trigger.  For information on PL/SQL, including how to write PL/SQL blocks, see the PL/SQL User's Guide and Reference.

Note that the PL/SQL block of a trigger cannot contain transaction control SQL statements (COMMIT, ROLLBACK, and SAVEPOINT).

To embed a CREATE TRIGGER statement inside an ORACLE Precompiler program, you must terminate the statement with the keyword END-EXEC followed by the embedded SQL statement terminator for the specific language.

Triggers

A database trigger is a storedprocedure that is associated with a table. ORACLE automatically fires,or executes, a trigger when a triggering statement is issued.

You can use triggers for these purposes:

•	to provide sophisticated auditing and transparent event logging

•	to automatically generate derived column values

•	to enforce complex security authorizations and business constraints

•	to maintain replicate asynchronous tables

For more information on how to design triggers for these purposes, see Chapter 8 "Using Database Triggers" of the ORACLE7 Server Application Developer's Guide.

Parts of a Trigger

The syntax of the CREATE TRIGGER statement includes these parts of the trigger:

Triggering statement      The definition of the triggering statement specifies what SQL statements cause ORACLE to fire the trigger.

DELETE

 INSERT

 UPDATE 	You must specify at least one of these commands that causes ORACLE to fire the trigger. You can specify as many as three.

ON	You must also specify the table with which the trigger is associated. The triggering statement is one that modifies this table.

Trigger restriction      The trigger restriction specifies an additional condition that must be satisfied for a row trigger to be fired. You can specify this condition with the WHEN clause. This condition must be a SQL condition, rather than a PL/SQL condition.

Trigger action      The trigger action specifies the PL/SQL block ORACLE executes to fire the trigger.

ORACLE evaluates the condition of the trigger restriction whenever a triggering statement is issued. If this condition is satisfied, then ORACLE fires the trigger using the trigger action.

Types of Triggers

You can create different types of triggers. The type of a trigger determines these things:

•	when ORACLE fires the trigger in relation to executing the triggering statement

•	how many times ORACLE fires the trigger

The type of a trigger is based on the use of these options of the CREATE TRIGGER command:

•	BEFORE

•	AFTER

•	FOR EACH ROW

Using all combinations of the options for these parts, you can create four basic types of triggers. Table 5 - 1 describes each type of trigger, its properties, and the options used to create it.

FOR EACH ROW

option

BEFORE statement 	BEFORE row trigger:

BEFORE	trigger: ORACLE 	ORACLE fires the

Option	fires the trigger once 	trgger before modify

before executing the 	ing each row affected

trigering statement.	by the triggering

statement.

AFTER statement 	AFTER row trigger:

AFTER	trigger: ORACLE 	ORACLE fires the

Option	fires the trigger once 	trigger after modify

after executing the 	ing each row affected

triggering statement.	by the triggering

statement.

Table 5 - 1.  Types of Triggers

For a single table, you can create each type of trigger for each of these commands:

•	DELETE

•	INSERT

•	UPDATE

You can also create triggers that fire for more than one command.

If you create multiple triggers of the same type that fire for the same command on the same table, the order in which ORACLE fires these triggers is indeterminate. If your application requires that one trigger be fired before another of the same type for the same command, combine these triggers into a single trigger whose trigger action performs the trigger actions of the original triggers in the appropriate order.

Enabling and Disabling Triggers

An existing trigger must be in one of these states:

enabled	If a trigger is enabled, ORACLE fires the trigger whenever a triggering statement is issued and the condition of the trigger restriction is met.

disabled	If a trigger is disabled, ORACLE does not fire the trigger when a triggering statement is issued and the condition of the trigger restriction is met.

When you create a trigger, ORACLE enables it automatically.

You can subsequently disable and enable a trigger with one of these commands:

•	the ALTER TRIGGER command with the DISABLE and ENABLE options

•	the ALTER TABLE command with the DISABLE and ENABLE clauses

For information on how to enable and disable triggers, see the ALTER TRIGGER and ALTER TABLE commands and the ENABLE and DISABLE clauses.

Example I	This example creates a BEFORE statement trigger named EMP_PERMIT_CHANGES in the schema SCOTT. This trigger ensures that changes to employee records are only made during business hours on working days:

CREATE TRIGGER scott.emp_permit_changes

BEFORE

DELETE OR INSERT OR UPDATE

ON scott.emp

DECLARE

dummy	INTEGER;

BEGIN

/*	If today is a Saturday or Sunday, then return an error.*/

IF (TO_CHAR(SYSDATE, 'DY') = 'SAT' OR

TO_CHAR(SYSDATE, 'DY') = 'SUN')

THEN raise_application_error( -20501,

'May not change employee table during the weekend');

END IF;

/*	Compare today's date with the dates of all

company holidays. If today is a company holiday,

then return an error.	*/

SELECT COUNT(*)

INTO dummy

FROM company_holidays

WHERE day = TRUNC(SYSDATE);

IF dummy > 0

THEN raise_application_error( -20501,

'May not change employee table during a holiday');

END IF;

/*	If the current time is before 8:00AM or after

6:00PM, then return an error.	*/

IF (TO_CHAR(SYSDATE, 'HH24') < 8 OR

TO_CHAR(SYSDATE, 'HH24') >= 18)

THEN raise_application_error( -20502,

'May only change employee table during working hours');

END IF;

END;

ORACLE fires this trigger whenever a DELETE, INSERT, or UPDATE statement affects the EMP table in the schema SCOTT.

Since EMP_PERMIT_CHANGES is a BEFORE statement trigger, ORACLE fires it once before executing the triggering statement.

The trigger performs these operations:

1.	If the current day is a Saturday or Sunday, the trigger raises an application error with a message that the employee table cannot be changed during weekends.

2.	The trigger compares the current date with the dates listed in the table of company holidays.

3.	If the current date is a company holiday, the trigger raises an application error with a message that the employee table cannot be changed during holidays.

4.	If the current time is not between 8:00AM and 6:00PM, the trigger raises an application error with a message that the employee table can only be changed during business hours.

Example II	This example creates a BEFORE row trigger named SALARY_CHECK in the schema SCOTT. Whenever a new employee is added to the employee table or an existing employee's salary or job is changed, this trigger guarantees that the employee's salary falls within the established salary range for the employee's job:

CREATE TRIGGER scott.salary_check

BEFORE

INSERT OR UPDATE OF sal, job

ON scott.emp

FOR EACH ROW

WHEN (new.job <> 'PRESIDENT')

DECLARE

minsal	NUMBER;

maxsal	NUMBER;

BEGIN

/* Get the minimum and maximum salaries for the	*/

/* employee's job from the SAL_GUIDE table.	*/

SELECT minsal, maxsal

INTO minsal, maxsal

FROM sal_guide

WHERE job = :new.job;

/* If the employee's salary is below the minimum or	*/

/* above the maximum for the job, then generate an 	*/

/* error.	*/

IF (:new.sal < minsal OR :new.sal > maxsal)

THEN raise_application_error( -20601,

'Salary ' || :new.sal || ' out of range for job '

|| :new.job || ' for employee ' || :new.ename );

END IF;

END;

ORACLE fires this trigger whenever one of these statements is issued:

•	an INSERT statement that adds rows to the EMP table

•	an UPDATE statement that changes values of the SAL or JOB columns of the EMP table

Since SALARY_CHECK is a BEFORE row trigger, ORACLE fires it before changing each row that is updated by the UPDATE statement or before adding each row that is inserted by the INSERT statement.

SALARY_CHECK has a trigger restriction that prevents it from checking the salary of the company president. For each new or modified employee row that meets this condition, the trigger performs these steps:

1.	The trigger queries the salary guide table for the minimum and maximum salaries for the employee's job.

2.	The trigger compares the employee's salary with these minimum and maximum values.

3.	If the employee's salary does not fall within the acceptable range, the trigger raises an application error with a message that the employee's salary is not within the established range for the employee's job.

Related Topics

ALTER TRIGGER and DROP TRIGGER commands;  ENABLE and DISABLE clauses.

________________________________________

CREATE USER

Purpose

To create a database user, or an account through which you can log in to the database, and establish the means by which ORACLE permits access by the user. You can optionally assign these properties to the user:

•	default tablespace

•	temporary tablespace

•	quotas for allocating space in tablespaces

•	profile containing resource limits

Prerequisites

You must have CREATE USER system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, you must meet additional prerequisites to perform the optional assignments of this statement:

•	To assign a default or temporary tablespace, your DBMS label must dominate the tablespace's creation label.

•	To assign a profile, your DBMS label must dominate the profile's creation label.

Syntax

Keywords and Parameters

user	is the name of the user to be created. This name can only contain characters from your database character set and must follow the rules described in the section "Object Naming  on page 2 - 3. Oracle Corporation recommends that the user contain at least one single-byte character regardless of whether the database character set also contains multi-byte characters.

IDENTIFIED 	indicates how ORACLE permits user access:

BY password 	The user must specify this password to logon. Password must follow the rules described in the section "Object Naming Rules" on page 2 - 3 and can only contain single-byte characters from your database character set regardless of whether this character set also contains multi-byte characters.

EXTERNALLY	ORACLE verifies user access through the operating system.

DEFAULT TABLESPACE	identifies the default tablespace for objects that the user creates. If you omit this clause, objects default to the SYSTEM tablespace.

TEMPORARY TABLESPACE	identifies the tablespace for the user's temporary segments. If you omit this clause, temporary segments default to the SYSTEM tablespace.

QUOTA	allows the user to allocate space in the tablespace and optionally establishes a quota of integer bytes. This quota is the maximum space in the tablespace the user can allocate. You can also use the K or M to specify the quota in kilobytes or megabytes.

Note that a CREATE USER command can have multiple QUOTA clauses for multiple tablespaces.

UNLIMITED	allows the user to allocate space in the tablespace without bound.

PROFILE	assigns the profile named profile to the user. The profile limits the amount of database resources the user can use. If you omit this clause, ORACLE assigns the DEFAULT profile to the user.

Usage Notes

 If you create a new user in Trusted ORACLE, the user's creation labelis your DBMS label.

 Verifying Users Through Your Operating System

The EXTERNALLY option causes ORACLE to verify access to the user through the operating system, rather than with a password. Such a user can only be accessed from a single operating system account. At logon, ORACLE compares the username and the current operating system account name. The username must match the account name prefixed by the value of the initialization parameter OS_AUTHENT_PREFIX.

 Establishing Tablespace Quotas for Users

To create an object or a temporary segment, the user must allocate space in some tablespace. To allow the user to allocate space, use the QUOTA clause. A CREATE USER statement can have multiple QUOTA clauses, each for a different tablespace. Other clauses can appear only once.

Note that you must use QUOTA clauses to allow the user to allocate space in the default and temporary tablespaces. Note also that you need not have a quota on a tablespace in order to establish a quota for another user on that tablespace.

 Granting Privileges to a User

For a user to perform any database operation, the user's privilege domain must contain a privilege that authorizes that operation. A user's privilege domain contains all privileges granted to the user and all privileges in the privilege domains of the user's enabled roles. When you create a user with the CREATE USER command, the user's privilege domain is empty.

Note: To logon to ORACLE, a user must have CREATE SESSION system privilege. After creating a user, you should grant the user this privilege.

Example I	You can create the user SIDNEY by issuing this statement:

CREATE USER sidney

IDENTIFIED BY carton

DEFAULT TABLESPACE cases_ts

TEMPORARY TABLESPACE temp_ts

QUOTA 10M ON cases_ts

QUOTA 5M ON temp_ts

QUOTA 5M ON system 	PROFILE engineer

The user SIDNEY has these characteristics:

•	the password CARTON

•	default tablespace CASES_TS, with a quota of 10 megabytes

•	temporary tablespace TEMP_TS, with a quota of 5 megabytes

•	access to the tablespace SYSTEM, with a quota of 5 megabytes

•	limits on database resources defined by the profile ENGINEER

Example II	To create a user accessible only by the operating system account GEORGE, prefix GEORGE by the value of the initialization parameter OS_AUTHENT_PREFIX. For example, if this value is "OPS$", you can create the user OPS$GEORGE with this statement:

CREATE USER ops$george

IDENTIFIED EXTERNALLY

DEFAULT TABLESPACE accs_ts

TEMPORARY TABLESPACE temp_ts

QUOTA UNLIMITED ON accs_ts

 	QUOTA UNLIMITED ON temp_ts

The user OPS$GEORGE has these other characteristics:

•	default tablespace ACCS_TS

•	default temporary tablespace TEMP_TS

•	unlimited space on the tablespaces ACCS_TS and TEMP_TS

•	limits on database resources defined by the DEFAULT profile

Related Topics

ALTER USER, CREATE PROFILE, CREATE TABLESPACE, and GRANT commands.

________________________________________

CREATE VIEW

Purpose

To define a view, a logical table based on one or more tables or views.

Prerequisites

To create a view in your own schema, you must have CREATE VIEW system privilege. To create a view in another user's schema, you must have CREATE ANY VIEW system privilege.

The owner of the schema containing the view must have the privileges necessary to either select, insert, update, or delete rows from all the tables or views on which the view is based. For information on these privileges, see the SELECT, INSERT, UPDATE, and DELETE commands in this chapter. The owner must be granted these privileges directly, rather than through a role.

Syntax

Keywords and Parameters

OR REPLACE	recreates the view if it already exists. You can use this option to change the definition of an existing view without dropping, recreating, and regranting object privileges previously granted on it.

FORCE	creates the view regardless of whether the view's base tables exist or the owner of the schema containing the view has privileges on them. Note that both of these conditions must be true before any SELECT, INSERT, UPDATE, or DELETE statements can be issued against the view.

NOFORCE	creates the view only if the base tables exist and the owner of the schema containing the view has privileges on them.

The default is NOFORCE.

schema	is the schema to contain the view. If you omit schema, ORACLE creates the view in your own schema.

view 	is the name of the view.

alias	specifies names for the expressions selected by the view's query. The number of aliases must match the number of expressions selected by the view. Aliases must follow the rules for naming schema objects in the section "Naming  on page 2 - 3. Aliases must be unique within the view.

If you omit the aliases, ORACLE derives them from the columns or column aliases in the view's query. For this reason, you must use aliases if the view's query contains expressions rather than only column names.

AS subquery	identifies columns and rows of the table(s) that the view is based on. A view's query can be any SELECT statement without the ORDER BY or FOR UPDATE clauses. Its select list can contain up to 254 expressions. See the syntax description of subquery on page 8 - 362.

WITH CHECK OPTION	specifies that inserts and updates performed through the view must result in rows that the view query can select. The CHECK OPTION cannot make this guarantee if there is a subquery in the query of this view or any view on which this view is based.

CONSTRAINT	is the name assigned to the CHECK OPTION constraint. If you omit this identifier, ORACLE automatically assigns the constraint a name of this form:

 SYS_Cn 	where n is an integer that makes the constraint name unique within the database.

Usage Notes

 A view is a logical table that allowsyou to access data from other tables and views. A view contains nodata itself. The tables upon which a view is based are called base tables.

Views are used for these purposes:

•	To provide an additional level of table security, by restricting access to a predetermined set of rows and/or columns of a base table.

•	To hide data complexity. For example, a view may be used to act as one table when actually several tables are used to construct the result.

•	To present data from another perspective. For example, views provide a means of renaming columns without actually changing the base table's definition.

•	To cause ORACLE to perform some operations, such as joins, on the database containing the view, rather than another database referenced in the same SQL statement.

You can use a view anywhere you can use a table in any of these SQL statements:

•	COMMENT

•	DELETE

•	INSERT

•	LOCK TABLE

•	UPDATE

•	SELECT

The View Query

For the syntax of the view's query, see the syntax description of subquery on page 8 - 362. Note these caveats:

•	A view's query cannot select the CURRVAL or NEXTVAL pseudocolumns.

•	If a view's query selects the ROWID, ROWNUM, or LEVEL pseudocolumns, they must have aliases in the view's query.

•	You can define a view with a query that uses an asterisk (*) to select all the columns of a table:

  CREATE VIEW emp_vu

 	  	AS SELECT * FROM emp

ORACLE translates the asterisk into a list of all the columns in the table at the time the CREATE VIEW statement is issued. If you subsequently add new columns to the table, the view will not contain these columns unless you recreate the view by issuing another CREATE VIEW statement with the OR REPLACE option. Oracle Corporation recommends that you explicitly specify all columns in the select list of a view query, rather than use the asterisk.

•	You can create views that refer to remote tables and views by using database links in the view query. Oracle Corporation recommends that any remote table or view referenced in the view query be qualified with the name of the schema containing it. Oracle Corporation also recommends that any database links used in the view query be defined using the CONNECT TO clause of the CREATE DATABASE LINK command.

These caveats also apply to the query for a snapshot.

If the view query contains any of the following constructs, you cannot perform inserts, updates, or deletes on the view:

•	joins

•	set operators

•	group functions

•	GROUP BY, CONNECT BY, or START WITH clauses

•	the DISTINCT operator

Note that if a view contains pseudocolumns or expressions, you can only update the view with an UPDATE statement that does not refer to any of the pseudocolumns or expressions.

Example I	This statement creates a view of the EMP table named DEPT20. The view shows the employees in department 20 and their annual salary:

CREATE VIEW dept20

AS SELECT ename, sal*12 annual_salary

FROM emp

WHERE deptno = 20

Note that the view declaration need not define a name for the column based on the expression SAL*12 because the subquery uses a column alias (ANNUAL_SALARY) for this expression.

Example II	This statement creates a view named CLERKS of all clerks in the employee table. The view shows only the employees' IDs, names, and department numbers:

CREATE VIEW clerk (id_number, person, department, position)

AS SELECT empno, ename, deptno, job

FROM emp

WHERE job = 'CLERK'

 	WITH CHECK OPTION CONSTRAINT wco

Because of the CHECK OPTION, you cannot subsequently insert a new row into CLERK if the new employee is not a clerk .

Related Topics

CREATE TABLE, CREATE SYNONYM, DROP VIEW, and RENAME commands.

________________________________________

DECLARE CURSOR (Embedded SQL)

Purpose

To declare a cursor, giving it a name and associating it with a SQL statement or a PL/SQL block.

Prerequisites

If you associate the cursor with an identifier for a SQL statement or PL/SQL block, you must have declared this identifier in a previous DECLARE STATEMENT statement.

Syntax

Keywords and Parameters

AT	identifies the database on which the cursor is declared. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, ORACLE declares the cursor on your default database.

cursor	is the name of the cursor to be declared.

SELECT command	is a SELECT statement to be associated with the cursor. This statement cannot contain an INTO clause.

statement_name block_name	identifies a SQL statement or PL/SQL block to be associated with the cursor. The statement_name  or block_name  must be previously declared in a DECLARE STATEMENT statement.

Usage Notes

 You must declare a cursor before referencing it in other embeddedSQL statements. The scope of a cursor declaration is global withinits precompilation unit and the name of each cursor must be unique in its scope. You cannot declare two cursors with the same name in a single precompilation unit.

You can reference the cursor in the WHERE clause of an UPDATE or DELETE statement using the CURRENT OF syntax, provided that the cursor has been opened with an OPEN statement and positioned on a row with a FETCH statement. For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example	This example illustrates the use of a DECLARE CURSOR:

EXEC SQL DECLARE emp_cursor CURSOR

FOR SELECT ename, empno, job, sal

FROM emp

WHERE deptno = :deptno

FOR UPDATE OF sal

Related Topics

CLOSE, DECLARE DATABASE, DECLARE STATEMENT, DELETE, FETCH, OPEN, PREPARE, SELECT, and UPDATE commands.

________________________________________

DECLARE DATABASE (Embedded SQL)

Purpose

To declare an identifier for a non-default database to be accessed in subsequent embedded SQL statements.

Prerequisites

You must have access to a username on the non-default database.

Syntax

Keywords and Parameters

db_name	is the identifier established for the non-default database.

Usage Notes

You declare a db_name for a non-default database so that otherembedded SQL statements can refer to that database using the AT clause. Beforeissuing a CONNECT statement with an AT clause, you must declare a db_name for the non-default database with a DECLARE DATABASE statement.

For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example	This example illustrates the use of a DECLARE DATABASE statement:

EXEC SQL DECLARE oracle3 DATABASE

Related Topics

COMMIT, CONNECT, DECLARE CURSOR, DECLARE STATEMENT, DELETE, EXECUTE, EXECUTE IMMEDIATE, INSERT, SELECT, and UPDATE commands.

________________________________________

DECLARE STATEMENT (Embedded SQL)

Purpose

To declare an identifier for a SQL statement or PL/SQL block to be used in other embedded SQL statements.

Prerequisites

None.

Syntax

Keywords and Parameters

AT	identifies the database on which the SQL statement or PL/SQL block is declared. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, ORACLE declares the SQL statement or PL/SQL block on your default database.

statement_name block_name	is the declared identifier for the statement.

Usage Notes

You must declare an identifier for a SQL statement or PL/SQL blockwith a DECLARE STATEMENT statement only if a DECLARE CURSOR statementreferencing the identifier appears physically (not logically) in the embedded SQL program before the PREPARE statement that parses the statement or block and associates it with its identifier.

The scope of a statement declaration is global within its precompilation unit, like a cursor declaration. For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example I	This example illustrates the use of the DECLARE STATEMENT statement:

EXEC SQL AT remote_db

DECLARE my_statement STATEMENT

EXEC SQL PREPARE my_statement FROM :my_string

EXEC SQL EXECUTE my_statement

Example II	In this example from a Pro*C embedded SQL program, the DECLARE STATEMENT statement is required because the DECLARE CURSOR statement precedes the PREPARE statement:

EXEC SQL DECLARE my_statement STATEMENT;

call prepare_my_statement;

EXEC SQL DECLARE emp_cursor CURSOR FOR my_statement;

...

PROCEDURE prepare_my_statement

BEGIN

EXEC SQL PREPARE my_statement FROM :my_string;

END;

Related Topics

DECLARE DATABASE, PREPARE, OPEN, FETCH, and CLOSE commands.

________________________________________

DECLARE TABLE (Embedded SQL)

Purpose

To define the structure of a table or view, including each column's datatype, default value, and NULL or NOT NULL specification for semantic checking by the ORACLE Precompilers.

Prerequisites

None.

Syntax

Keywords and Parameters

table	is the name of the declared table.

column 	is a column of the table.

datatype	is the datatype of a column. For information on ORACLE datatypes, see the section "Datatypes" on page 2 - 21.

DEFAULT	specifies the default value of a column.

NULL	specifies that a column can contain nulls.

NOT NULL	specifies that a column cannot contain nulls.

WITH DEFAULT	is supported for compatibility with IBM's DB2 database.

Usage Notes

 For information on using this command, see the Programmer's Guide to the ORACLE .

Example	This statement declares the PARTS table with the PARTNO, BIN, and QTY columns:

EXEC SQL DECLARE parts TABLE

(partno  NUMBER  NOT NULL,

 bin     NUMBER,

 qty     NUMBER)

Related Topics

None.

________________________________________

DELETE

Purpose

To remove rows from a table or from a view's base table.

Prerequisites

For you to delete rows from a table, the table must be in your own schema or you must have DELETE privilege on the table.

For you to delete rows from the base table of a view, the owner of the schema containing the view must have DELETE privilege on the base table. Also, if the view is in a schema other than your own, you must be granted DELETE privilege on the view.

The DELETE ANY TABLE system privilege also allows you to delete rows from any table or any view's base table.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of the table or view or you must meet one of these criteria:

•	If the creation label of the table or view is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the creation label of your table or view is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

In addition, for each row to be deleted, your DBMS label must match the row's label or you must meet one of these criteria:

•	If the row's label is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the row's label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the row's label is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the table or view. If you omit schema, ORACLE assumes the table or view is in your own schema.

table view	is the name of a table from which the rows are to be deleted. If you specify view, ORACLE deletes rows from the view's base table.

dblink	is the complete or partial name of a database link to a remote database where the table or view is located. For information on referring to database links, see the section "Referring to Objects in Remote Databases" on page 2 - 13. You can only delete rows from a remote table or view if you are using ORACLE with the distributed option.

If you omit dblink, ORACLE assumes that the table or view is located on the local database.

alias	is an alias assigned to the table. Aliases are generally used in DELETE statements with correlated queries.

WHERE	deletes only rows that satisfy the condition. The condition can reference the table and can contain a subquery. See the syntax description of condition on on page 2 - 13. You can only delete rows from a remote table or view if you are using ORACLE with the distributed option.

If you omit dblink, ORACLE assumes that the table or view is located on the local database.

alias	is an alias assigned to the table and is generally  used in DELETE statements with correlated queries.

WHERE	specifies which rows are deleted:

condition	deletes only rows that satisfy the condition. This condition can contain host variables and optional indicator variables. See the syntax description of condition on page NO TAG.

CURRENT OF	deletes only the row most recently fetched by the cursor. The cursor cannot be associated with a SELECT statement that performs a join, unless its FOR UPDATE clause specifically locks only one table.

If you omit this clause entirely, ORACLE deletes all rows from the table or view.

Usage Notes

The host variables in the WHERE clause must be either all scalarsor all arrays. If they are scalars, ORACLE executes the DELETE statementonly once. If they are arrays, ORACLE executes the statement once for each set of array components. Each execution may delete zero, one, or multiple rows.

Array host variables in the WHERE clause can have different sizes. In this case, the number of times ORACLE executes the statement is determined by the smaller of these values:

•	the size of the smallest array

•	the value of the :host_integer in the optional FOR clause

If no rows satisfy the condition, no rows are deleted and the SQLCODE returns a NOT_FOUND condition.

The cumulative number of rows deleted is returned through the SQLCA. If the WHERE clause contains array host variables, this value reflects the total number of rows deleted for all components of the array processed by the DELETE statement.

If no rows satisfy the condition, ORACLE returns an error through the SQLCODE of the SQLCA. If you omit the WHERE clause, ORACLE raises a warning flag in the 5th component of SQLWARN in the SQLCA. For more information on this command and the SQLCA, see the Programmer's Guide to the ORACLE Precompilers.

You can use comments in a DELETE statement to pass instructions, or hints, to the ORACLE optimizer. The optimizer uses hints to choose an execution plan for the statement. For more information on hints, see Chapter 5  of the ORACLE7 Server Aministrator's Guide.

Examples	This example illustrates the use of the DELETE statement within a Pro*C embedded SQL program:

EXEC SQL DELETE FROM emp

WHERE deptno = :deptno

AND job = :job;

...

EXEC SQL DECLARE emp_cursor CURSOR

FOR SELECT empno, comm

FROM emp;

EXEC SQL OPEN emp_cursor;

EXEC SQL FETCH c1

INTO :emp_number, :commission;

EXEC SQL DELETE FROM emp

WHERE CURRENT OF emp_cursor;

Related Topics

DECLARE DATABASE, DECLARE STATEMENT, and TRUNCATE commands.

________________________________________

DESCRIBE (Embedded SQL)

Purpose

To initialize a descriptor to hold descriptions of host variables for a dynamic SQL statement or PL/SQL block.

Prerequisites

You must have prepared the SQL statement or PL/SQL block in a previous embedded SQL PREPARE statement.

Syntax

Keywords and Parameters

BIND VARIABLES	initializes the descriptor to hold information about the input variables for the SQL statement or PL/SQL block.

SELECT LIST	initializes the descriptor to hold information about the select list of a SELECT statement.

The default is SELECT LIST FOR.

statement_name block_name	identifies a SQL statement or PL/SQL block previously prepared with a PREPARE statement.

descriptor	is the name of the descriptor to be initialized.

Usage Notes

You must issue a DESCRIBE statement before manipulating the bind orselect descriptor within an embedded SQL program.

You cannot describe both input variables and output variables into the same descriptor.

The number of variables found by a DESCRIBE statement is the total number of placeholders in the prepare SQL statement or PL/SQL block, rather than the total number of uniquely named placeholders.  For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example	This example illustrates the use of the DESCRIBE statement in a Pro*C embedded SQL program:

EXEC SQL PREPARE my_statement 	FROM :my_string;

EXEC SQL DECLARE emp_cursor

FOR SELECT empno, ename, sal, comm

FROM emp

WHERE deptno = :dept_number

EXEC SQL DESCRIBE BIND VARIABLES FOR my_statement

INTO bind_descriptor;

EXEC SQL OPEN emp_cursor

USING bind_descriptor;

EXEC SQL DESCRIBE SELECT LIST FOR my_statement

INTO select_descriptor;

EXEC SQL FETCH emp_cursor

INTO select_descriptor;

Related Topics

PREPARE command.

________________________________________

DISABLE clause

Purpose

To disable an integrity constraint or all triggers associated with a table:

•	If you disable an integrity constraint, ORACLE does not enforce it. However, disabled integrity constraints appear in the data dictionary along with enabled integrity constraints.

•	If you disable a trigger, ORACLE does not fire it if its triggering condition is satisfied.

Prerequisites

A DISABLE clause that disables an integrity constraint can appear in either a CREATE TABLE or ALTER TABLE command. To disable an integrity constraint, you must have the privileges necessary to issue one of these commands. For information on these privileges, see the CREATE TABLE and ALTER TABLE commands in this chapter.

For an integrity constraint to appear in a DISABLE clause, one of these conditions must be true:

•	the integrity constraint must be defined in the containing statement

•	the integrity constraint must already have been defined and enabled in previously issued statements

A DISABLE clause that disables triggers can only appear in an ALTER TABLE statement. To disable triggers with a DISABLE clause, you must have the privileges necessary to issue this statement. For information on these privileges, see the ALTER TABLE command earlier in this chapter. Also, the triggers must be in your own schema or you must have ALTER ANY TRIGGER system privilege.

Syntax

Keywords and Parameters

UNIQUE	disables the UNIQUE constraint defined on the specified column or combination of columns.

PRIMARY KEY	disables the table's PRIMARY KEY constraint.

CONSTRAINT	disables the integrity constraint with the name constraint.

CASCADE	disables any integrity constraints that depend on the specified integrity constraint. To disable a primary or unique key that is part of a referential integrity constraint, you must specify this option.

ALL TRIGGERS	disables all triggers associated with the table. This option can only appear in a DISABLE clause in an ALTER TABLE statement, not a CREATE TABLE statement.

Usage Notes

 You can use the DISABLE clause to disable:

•	a single integrity constraint

•	all triggers associated with a table

To disable a single trigger, use the DISABLE option of the ALTER TRIGGER command.

 How to Disable Integrity Constraints

You can disable an integrity constraint by naming it in a DISABLE clause of either a CREATE TABLE or ALTER TABLE statement. You can define an integrity constraint with a CONSTRAINT clause and disable it with a DISABLE clause together in the same statement. You can also define an integrity constraint in one statement and subsequently disable it in another.

You can also disable an integrity constraint with the DISABLE keyword in the CONSTRAINT clause that defines the integrity constraint. For information on this keyword, see the CONSTRAINT clause on page 5 - 119.

How ORACLE Disables Integrity Constraints      If you disable an integrity constraint, ORACLE does not enforce it. If you define an integrity constraint and disable it, ORACLE does not apply it to existing rows of the table, although ORACLE does store it in the data dictionary along with enabled integrity constraints. Also, ORACLE can execute Data Manipulation Language statements that change table data and violate a disabled integrity constraint.

If you disable a UNIQUE or PRIMARY KEY constraint that was previously enabled, ORACLE drops the index that enforces the constraint.

You can enable a disabled integrity constraint with the ENABLE clause.

Disabling Referenced Keys in Referential Integrity Constraints      To disable a UNIQUE or PRIMARY KEY constraint that identifies the referenced key of a referential integrity constraint, you must also disable the foreign key. To disable a constraint and all its dependent constraints, use the CASCADE option of the DISABLE clause.

You cannot enable a foreign key that references a unique or primary key that is disabled.

Example I	This statement creates the DEPT table and defines a disabled PRIMARY KEY constraint:

CREATE TABLE dept

(deptno  NUMBER(2)  PRIMARY KEY,

 dname   VARCHAR2(10),

 loc     VARCHAR2(9) )

DISABLE PRIMARY KEY

Since the primary key is disabled, you can add rows to the table that violate the primary key. You can add departments with null department numbers or multiple departments with the same department number.

Example II	This statement defines and disables a CHECK constraint on the EMP table:

ALTER TABLE emp

ADD (CONSTRAINT check_comp  CHECK (sal + comm <= 5000) )

 	DISABLE CONSTRAINT check_comp

The constraint CHECK_COMP ensures that no employee's total compensation exceeds $5000. Since the constraint is disabled, you can increase an employee's compensation above this limit.

Example III	Consider a referential integrity constraint involving a foreign key on the combination of the AREACO and PHONENO columns of the PHONE_CALLS table. The foreign key references a unique key on the combination of the AREACO and PHONENO columns of the CUSTOMERS table. This statement disables the unique key on the combination of the AREACO and PHONENO columns of the CUSTOMERS table:

ALTER TABLE customers

DISABLE UNIQUE KEY (areaco, phoneno) CASCADE

Since the unique key in the CUSTOMERS table is referenced by the foreign key in the PHONE_CALLS table, you must use the CASCADE option to disable the unique key. This option disables the foreign key as well.

 How to Disable Triggers

You can disable all triggers associated with the table by using the ALL TRIGGERS option in a DISABLE clause of an ALTER TABLE statement. After you disable a trigger, ORACLE does not fire the trigger when a triggering statement meets the condition of the trigger restriction.

Example IV	This statement disables all triggers associated with the EMP table:

ALTER TABLE emp

DISABLE ALL TRIGGERS

Related Topics

ALTER TABLE, ALTER TRIGGER, CREATE TABLE, and CREATE TRIGGER commands;  CONSTRAINT and ENABLE clauses.

________________________________________

DROP clause

Purpose

To remove an integrity constraint from the database.

Prerequisites

The DROP clause can appear in an ALTER TABLE statement. To drop an integrity constraint, you must have the privileges necessary to issue an ALTER TABLE statement. For information on these privileges, see the ALTER TABLE command earlier in this chapter.

Syntax

Keywords and Parameters

PRIMARY KEY	drops the table's PRIMARY KEY constraint.

UNIQUE	drops the UNIQUE constraint on the specified columns.

CONSTRAINT	drops the integrity constraint named constraint.

CASCADE	drops all other integrity constraints that depend on the dropped integrity constraint.

Usage Notes

You can drop an integrity constraint by naming it in a DROP clauseof an ALTER TABLE statement. When you drop an integrity constraint,ORACLE stops enforcing the integrity constraint and removes it from the data dictionary.

You cannot drop a unique or primary key that is part of a referential integrity constraint without also dropping the foreign key. You can drop the referenced key and the foreign key together by specifying the referenced key with the CASCADE option in the DROP clause.

Example I	This statement drops the primary key of the DEPT table:

ALTER TABLE dept

DROP PRIMARY KEY CASCADE

If you know that the name of the PRIMARY KEY constraint is PK_DEPT, you could also drop it with this statement:

ALTER TABLE dept

DROP CONSTRAINT pk_dept CASCADE

The CASCADE option drops any foreign keys that reference the primary key.

Example II	This statement drops the unique key on the DNAME column of the DEPT table:

ALTER TABLE dept

DROP UNIQUE (dname)

Note that the DROP clause in this example omits the CASCADE option. Because of this omission, ORACLE does not drop the unique key if any foreign key references it.

Related Topics

ALTER TABLE command; CONSTRAINT clause.

________________________________________

DROP CLUSTER

Purpose

To remove a cluster from the database.

Prerequisites

The cluster must be in your own schema or you must have DROP ANY CLUSTER system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the cluster's creation label or you must satisfy one of these criteria:

•	If the cluster's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the cluster's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the cluster's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the cluster. If you omit schema, ORACLE assumes the cluster is in your own schema.

cluster 	is the name of the cluster to be dropped.

INCLUDING TABLES	drops all tables that belong to the cluster. If you omit this clause, and the cluster still contains tables, ORACLE returns an error and does not drop the cluster.

CASCADE CONSTRAINTS	drops all referential integrity constraints from tables outside the cluster that refer to primary and unique keys in the tables of the cluster. If you omit this option and such referential integrity constraints exist, ORACLE returns an error message and does not drop the cluster.

Usage Notes

Dropping a cluster also drops the cluster index and returns all clusterspace, including data blocks for the index, to the appropriate tablespace(s).

You cannot uncluster an individual table. To create an unclustered table identical to an existing clustered table, follow these steps:

1.	Create a new table with the same structure and contents as the old one but with no CLUSTER option.

2.	Drop the old table.

3.	Use the RENAME command to give the new table the name of the old one.

Grants on the old clustered table do not apply to the new unclustered table and must be regranted.

Example	This command drops a cluster named GEOGRAPHY, all its tables, and any referential integrity constraints that refer to primary or unique keys in those tables:

DROP CLUSTER geography

INCLUDING TABLES

CASCADE CONSTRAINTS

Related Topic

DROP TABLE command.

________________________________________

DROP DATABASE LINK

Purpose

To remove a database link from the database.

Prerequisites

To drop a private database link, the database link must be in your own schema. To drop a PUBLIC database link, you must have DROP PUBLIC DATABASE LINK system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the database link's creation label or you must satisfy one of these criteria:

•	If the database link's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the database link's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the database link's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

PUBLIC	must be specified to drop a PUBLIC database link.

dblink 	specifies the database link to be dropped.

Usage Notes

You cannot drop a database link in another user's schema and you cannotqualify dblink with the name of a schema. Since periods arepermitted in names of database links, ORACLE interprets the entire name, such as RALPH.LINKTOSALES, as the name of a database link in your schema rather than as a database link named LINKTOSALES in the schema RALPH.

Example	This statement drops a private database link named BOSTON:

DROP DATABASE LINK boston

Related Topics

CREATE DATABASE LINK command.

________________________________________

DROP FUNCTION

Purpose

To remove a stand-alone stored function from the database.

Prerequisites

The function must be in your own schema or you must have DROP ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the function's creation label or you must satisfy one of these criteria:

•	If the function's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the function's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the function's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the function. If you omit schema, ORACLE assumes the function is in your own schema.

function	is the name of the function to be dropped.

Usage Notes

When you drop a function, ORACLE invalidates any local objects thatdepend on, or call, the dropped function. If you subsequently referenceone of these objects, ORACLE tries to recompile the object and returns an error message if you have not recreated the dropped function. For more information on how ORACLE maintains dependencies among schema objects, including remote objects, see Chapter 16 "Dependencies Among Schema Objects" of the ORACLE7 Server Concepts Manual.

You can only use this command to drop a stand-alone function. To remove a function that is part of a package, use one of these means:

•	Drop the entire package using the DROP PACKAGE command.

•	Redefine the package without the function using the CREATE PACKAGE command with the OR REPLACE option.

Example	This statement drops the function NEW_ACCT in the schema RIDDLEY:

DROP FUNCTION riddley.new_acct

When you drop the NEW_ACCT function, ORACLE invalidates all objects that depend upon NEW_ACCT.

Related Topics

CREATE FUNCTION command.

________________________________________

DROP INDEX

Purpose

To remove an index from the database.

Prerequisites

The index must be in your own schema or you must have DROP ANY INDEX system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the index's creation label or you must satisfy one of these criteria:

•	If the index's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the index's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the index's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the index. If you omit schema, ORACLE assumes the index is in your own schema.

index	is the name of the index to be dropped.

Usage Notes

When the index is dropped all data blocks allocated to the index arereturned to the index's tablespace.

Example	This command drops an index named MONOLITH:

DROP INDEX monolith

Related Topics

ALTER INDEX, CREATE INDEX, and CREATE TABLE commands.

________________________________________

DROP PACKAGE

Purpose

To remove a stored package from the database.

Prerequisites

The package must be in your own schema or you must have DROP ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the cluster's creation label or you must satisfy one of these criteria:

•	If the package's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the package's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the package's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

BODY	drops only the body of the package. If you omit this option, ORACLE drops both the body and specification of the package.

schema	is the schema containing the package. If you omit schema, ORACLE assumes the package is in your own schema.

package	is the name of the package to be dropped.

Usage Notes

When you drop the body and specification of a package, ORACLE invalidatesany local objects that depend on the package specification. If yousubsequently reference one of these objects, ORACLE tries to recompile the object and returns an error if you have not recreated the dropped package. For information on how ORACLE maintains dependencies among schema objects, including remote objects, see Chapter 16 "Dependencies Among Schema Objects" of the ORACLE7 Server Concepts Manual.

When you drop only the body of a package but not its specification, ORACLE does not invalidate dependent objects. However, you cannot call one of the procedures or stored functions declared in the package specification until you recreate the package body.

The DROP PACKAGE command drops the package and all its objects together. To remove a single object from a package, you can recreate the package without the object using the CREATE PACKAGE and CREATE PACKAGE BODY commands with the OR REPLACE option.

Example

This statement drops the specification and body of the BANKING package, invalidating all objects that depend on the specification:

DROP PACKAGE banking

Related Topics

CREATE PACKAGE command.

________________________________________

DROP PROCEDURE

Purpose

To remove a stand-alone stored procedure from the database.

Prerequisites

The procedure must be in your own schema or you must have DROP ANY PROCEDURE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the cluster's creation label or you must satisfy one of these criteria:

•	If the procedure's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the procedure's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the procedure's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the procedure. If you omit schema, ORACLE assumes the procedure is in your own schema.

procedure	is the name of the procedure to be dropped.

Usage Notes

When you drop a procedure, ORACLE invalidates any local objects thatdepend upon the dropped procedure. If you subsequently referenceone of these objects, ORACLE tries to recompile the object and returns an error message if you have not recreated the dropped procedure.

For information on how ORACLE maintains dependencies among schema objects, including remote objects, see Chapter 16 "Dependencies Among Schema Objects" of the ORACLE7 Server Concepts Manual.

You can only use this command to drop a stand-alone procedure. To remove a procedure that is part of a package, use one of these means:

•	Drop the entire package using the DROP PACKAGE command.

•	Redefine the package without the procedure using the CREATE PACKAGE command with the OR REPLACE option.

Example	This statement drops the procedure TRANSFER owned by the user KERNER:

DROP PROCEDURE kerner.transfer

When you drop the TRANSFER procedure, ORACLE invalidates all objects that depend upon TRANSFER.

Related Topics

CREATE PROCEDURE command.

________________________________________

DROP PROFILE

Purpose

To remove a profile from the database.

Prerequisites

You must have DROP PROFILE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the profile's creation label or you must satisfy one of these criteria:

•	If the profile's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the profile's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the profile's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

profile	is the name of the profile to be dropped.

CASCADE	deassigns the profile from any users to whom it is assigned. ORACLE automatically assigns the DEFAULT profile to such users. You must specify this option to drop a profile that is currently assigned to users.

Usage Notes

 You cannot drop the DEFAULT profile.

Example	This statement drops the profile ENGINEER:

DROP PROFILE engineer

CASCADE

ORACLE assigns the DEFAULT profile to any users currently assigned the ENGINEER profile.

Related Topics

CREATE PROFILE command.

________________________________________

DROP ROLE

Purpose

To remove a role from the database.

Prerequisites

You must have been granted the role with the ADMIN OPTION or have DROP ANY ROLE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the role's creation label or you must satisfy one of these criteria:

•	If the role's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the role's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

If the role's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

role	is the role to be dropped.

Usage Notes

When you drop a role, ORACLE revokes it from all users and roles towhom it has been granted and removes it from the database.

Example	To drop the role FLORIST, issue this statement:

DROP ROLE florist

Related Topics

CREATE ROLE and SET ROLE commands.

________________________________________

DROP ROLLBACK SEGMENT

Purpose

To remove a rollback segment from the database.

Prerequisites

You must have DROP ROLLBACK SEGMENT system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the rollback segment's creation label or you must satisfy one of these criteria:

•	If the rollback segment's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the rollback segment's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the rollback segment's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

rollback_segment	is the name the rollback segment to be dropped.

Usage Notes

When you drop a rollback segment, all space allocated to the rollbacksegment returns to the tablespace.

You can only drop a rollback segment that is offline. To determine whether a rollback segment is offline, query the data dictionary view DBA_ROLLBACK_SEGS. Offline rollback segments have the value 'AVAILABLE' in the STATUS column. You can take a rollback segment offline with the OFFLINE option of the ALTER ROLLBACK SEGMENT command.

You cannot drop the SYSTEM rollback segment.

Example	This statement drops the rollback segment ACCOUNTING:

DROP ROLLBACK SEGMENT accounting

Related Topics

ALTER ROLLBACK SEGMENT, CREATE ROLLBACK SEGMENT, and CREATE TABLESPACE commands.

________________________________________

DROP SEQUENCE

Purpose

To remove a sequence from the database.

Prerequisites

The sequence must be in your own schema or you must have DROP ANY SEQUENCE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the sequence's creation label or you must satisfy one of these criteria:

•	If the sequence's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the sequence's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the sequence's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the sequence. If you omit schema, ORACLE assumes the sequence is in your own schema.

sequence	is the name of the sequence to be dropped.

Usage Notes

One method for restarting a sequence is to drop and recreate it. Forexample, if you have a sequence with a current value of 150 and youwould like to restart the sequence with a value of 27, you would:

1.	Drop the sequence.

2.	Create it with the same name and a START WITH value of 27.

Example	This statement drops the sequence ESEQ owned by the user ELLY:

DROP SEQUENCE elly.eseq

To issue this statement, you must either be connected as the user ELLY or have DROP ANY SEQUENCE system privilege.

Related Topics

ALTER SEQUENCE and CREATE SEQUENCE commands.

________________________________________

DROP SNAPSHOT

Purpose

To remove a snapshot from the database.

Prerequisites

The snapshot must be in your own schema or you must have DROP ANY SNAPSHOT system privilege. You must also have the privileges to drop the internal table, views, and index that ORACLE uses to maintain the snapshot's data. For information on these privileges, see the DROP TABLE, DROP VIEW, and DROP INDEX commands in this chapter.

Syntax

Keywords and Parameters

schema	is the schema containing the snapshot. If you omit schema, ORACLE assumes the snapshot is in your own schema.

snapshot 	is the name of the snapshot to be dropped.

Usage Notes

When you drop a simple snapshot, if it is the least recently refreshedsnapshot of a master table, ORACLE automatically purges the mastertable's snapshot log of the rows needed only to refresh the dropped snapshot.

When you drop a master table, ORACLE does not automatically drop snapshots based on the table. However, ORACLE returns an error message when it tries to refresh a snapshot based on a master table that has been dropped.

Example	This statement drops the snapshot PARTS owned by the user HQ:

DROP SNAPSHOT hq.parts

Related Topics

CREATE SNAPSHOT command.

________________________________________

DROP SNAPSHOT LOG

Purpose

To remove a snapshot log from the database.

Prerequisites

Since a snapshot log consists of a table and a trigger, the privileges that authorize operations on it are the same as for a table. To drop a snapshot log, you must have the privileges listed for the DROP TABLE command later in this chapter. You must also have the privileges to drop a trigger from the snapshot log's master table. For information on these privileges, see the DROP TRIGGER command later in this chapter.

Syntax

Keywords and Parameters

schema	is the schema containing the snapshot log and its master table. If you omit schema, ORACLE assumes the snapshot log and master table are in your own schema.

table	is the name of the master table associated with the snapshot log to be dropped.

Usage Notes

After you drop a snapshot log, snapshots based on the snapshot log'smaster table can no longer be refreshed fast. They must be refreshedcompletely. For more information on refreshing snapshots, see the CREATE SNAPSHOT command earlier in this chapter.

Example	This statement drops the snapshot log on the PARTS master table:

DROP SNAPSHOT LOG ON parts

Related Topics

CREATE SNAPSHOT LOG command.

________________________________________

DROP SYNONYM

Purpose

To remove a synonym from the database.

Prerequisites

If you want to drop a private synonym, either the synonym must be in your own schema or you must have DROP ANY SYNONYM system privilege. If you want to drop a PUBLIC synonym, either the synonym must be in your own schema or you must have DROP ANY PUBLIC SYNONYM system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the synonym's creation label or you must satisfy one of these criteria:

•	If the synonym's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the synonym's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the synonym's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

PUBLIC	must be specified to drop a public synonym.

schema	is the schema containing the synonym. If you omit schema, ORACLE assumes the synonym is in your own schema.

synonym	is the name of the synonym to be dropped.

Usage Notes

You can change the definition of a synonym by dropping and recreating it.

Example	To drop a synonym named MARKET, issue this statement:

DROP SYNONYM market

Related Topic

CREATE SYNONYM command.


CHAPTER 7. COMMANDS - DROP TABLE TO ROLLBACK

________________________________________

DROP TABLE

Purpose

To remove a table and all its data from the database.

Prerequisites

The table must be in your own schema or you must have DROP ANY TABLE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the table's creation label or you must satisfy one of these criteria:

•	If the table's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the table's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the table's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the table. If you omit schema, ORACLE assumes the table is in your own schema.

table 	is the name of the table to be dropped.

CASCADE CONSTRAINTS	drops all referential integrity constraints that refer to primary and unique keys in the dropped table. If you omit this option, and such referential integrity constraints exist, ORACLE returns an error message and does not drop the table.

Usage Notes

When you drop a table, ORACLE also performs these operations automatically:

•	ORACLE effectively deletes all rows from the table.

•	ORACLE drops all the table's indexes, regardless of who created them or whose schema contains them.

•	If the table is not part of a cluster, ORACLE returns all data blocks allocated to the table and its indexes to the tablespaces containing the table and indexes.

•	If the table is a base table for views or if it is referenced in stored procedures, functions, or packages, ORACLE invalidates these objects but does not drop them. You cannot use these objects unless you recreate the table or drop and recreate the objects so that they no longer depend on the table.

If you choose to recreate the table, it must contain all the columns selected by the queries originally used to define the views and all the columns referenced in the stored procedures, functions, or packages. Note that any users previously granted object privileges on the views, synonyms, stored procedures, functions, or packages need not be regranted these privileges.

•	If the table is a master table for snapshots, ORACLE does not drop the snapshots. Such a snapshot can still be queried, but it cannot be refreshed unless the table is recreated so that it contains all the columns selected by the snapshot's query.

•	If the table has a snapshot log, ORACLE  drops the snapshot log.

You can drop a cluster and all of its tables using the DROP CLUSTER command with the INCLUDING TABLES clause and avoid dropping each table individually.

Example	This statement drops the TEST_DATA table:

DROP TABLE test_data

Related Topics

DROP CLUSTER, ALTER TABLE, CREATE INDEX, and CREATE TABLE commands.

________________________________________

DROP TABLESPACE

Purpose

To remove a tablespace from the database.

Prerequisites

You must have DROP TABLESPACE system privilege. No rollback segments in the tablespace can be assigned active transactions.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the tablespace's creation label or you must satisfy one of these criteria:

•	If the tablespace's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the tablespace's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the tablespace's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

INCLUDING

CONTENTS 	drops all the contents of the tablespace. You must specify this clause to drop a tablespace that contains any database objects. If you omit this clause, and the tablespace is not empty, ORACLE returns an error message and does not drop the tablespace.

tablespace	is the name of the tablespace to be dropped.

CASCADE CONSTRAINTS	drops all referential integrity constraints from tables outside the tablespace that refer to primary and unique keys in the tables of the tablespace. If you omit this option and such referential integrity constraints exist, ORACLE returns an error message and does not drop the tablespace.

Usage Notes

You can drop a tablespace regardless of whether it is online or offline. OracleCorporation recommends that you take the tablespace offline beforedropping it to ensure that no SQL statements in currently running transactions access any of the objects in the tablespace.

You may want to alter any users who have been assigned the tablespace as either a default or temporary tablespace. After the tablespace has been dropped, these users cannot allocate space for objects or sort areas in the tablespace. You can reassign users new default and temporary tablespaces with the ALTER USER command.

You cannot drop the SYSTEM tablespace.

Example	This statement drops the MFRG tablespace and all its contents:

DROP TABLESPACE mfrg

INCLUDING CONTENTS

CASCADE CONSTRAINTS

Related Topics

ALTER TABLESPACE, CREATE DATABASE, and CREATE TABLESPACE commands.

________________________________________

DROP TRIGGER

Purpose

To remove a database trigger from the database.

Prerequisites

The trigger must be in your own schema or you must have DROP ANY TRIGGER system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the trigger's creation label or you must satisfy one of these criteria:

•	If the trigger's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the trigger's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the trigger's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the trigger. If you omit schema, ORACLE assumes the trigger is in your own schema.

trigger	is the name of the trigger to be dropped.

Usage Notes

When you drop a database trigger, ORACLE removes it from the database and does not fire it again.

Example	This statement drops the REORDER trigger in the schema RUTH:

DROP TRIGGER ruth.reorder

Related Topics

CREATE TRIGGER command.

________________________________________

DROP USER

Purpose

To remove a database user and optionally remove the user's objects.

Prerequisites

You must have DROP USER system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the user's creation label or you must satisfy one of these criteria:

•	If the user's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the user's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the user's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

user	is the user to be dropped.

 CASCADE 	drops all objects in the user's schema before dropping the user. You must specify this option to drop a user whose schema contains any objects.

Usage Notes

ORACLE does not drop users whose schemas contain objects. To dropsuch a user, you must perform one of these actions:

•	explicitly drop the user's objects before dropping the user

•	drop the user and objects together using the CASCADE option

If you specify the CASCADE option and drop tables in the user's schema, ORACLE also automatically drops any referential integrity constraints on tables in other schemas that refer to primary and unique keys on these tables. The CASCADE option causes ORACLE to invalidate, but not drop, these objects in other schemas:

•	views or synonyms for objects in the dropped user's schema

•	stored procedures, functions, or packages that query objects in the dropped user's schema

ORACLE does not drop snapshots on tables or views in the user's schema or roles created by the user.

Example I	If BRADLEY's schema contains no objects, you can drop BRADLEY by issuing the statement:

DROP USER bradley

Example II	If BRADLEY's schema contains objects, you must use the CASCADE option to drop BRADLEY and the objects:

DROP USER bradley CASCADE

Related Topics

CREATE USER and other DROP commands.

________________________________________

DROP VIEW

Purpose

To remove a view from the database.

Prerequisites

The view must be in your own schema or you must have DROP ANY VIEW system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the view's creation label or you must satisfy one of these criteria:

Syntax

Keywords and Parameters

•	If the view's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the view's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the view's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

schema	is the schema containing the view. If you omit schema, ORACLE assumes the view is in your own schema.

view	is the name of the view to be dropped.

Usage Notes

When you drop a view, views and synonyms that refer to the view arenot dropped, but become invalid. Drop them or redefine them, or (re)defineother views in such a way that the invalid views and synonyms become valid again.

You can change the definition of a view by dropping and recreating it.

Example	This statement drops the VIEW_DATA view:

DROP VIEW view_data

Related Topics

CREATE TABLE, CREATE VIEW, and CREATE SYNONYM commands.

________________________________________

ENABLE clause

Purpose

To enable an integrity constraint or all triggers associated with a table:

•	If you enable a constraint, ORACLE enforces it by applying it to all data in the table. All table data must satisfy an enabled constraint.

•	If you enable a trigger, ORACLE fires the trigger whenever its triggering condition is satisfied.

Prerequisites

An ENABLE clause that enables an integrity constraint can appear in either a CREATE TABLE or ALTER TABLE statement. To enable a constraint in this manner, you must have the privileges necessary to issue one of these statements. For information on these privileges, see the CREATE TABLE or ALTER TABLE command earlier in this chapter.

If you enable a UNIQUE or PRIMARY KEY constraint, ORACLE creates an index on the columns of the unique or primary key in the schema containing the table. To enable such a constraint, you must have the privileges necessary to create the index. For information on these privileges, see the CREATE INDEX command earlier in this chapter.

If you enable a referential integrity constraint, the referenced UNIQUE or PRIMARY KEY constraint must already be enabled.

For an integrity constraint to appear in an ENABLE clause, one of these conditions must be true:

•	the integrity constraint must be defined in the containing statement

•	the integrity constraint must already have been defined and disabled in a previously issued statement

An ENABLE clause that enables triggers can appear in an ALTER TABLE statement. To enable triggers with the ENABLE clause, you must have the privileges necessary to issue this statement. For information on these privileges, see the ALTER TABLE command earlier in this chapter. Also, the triggers must be in your own schema or you must have ALTER ANY TRIGGER system privilege.

Syntax

Keywords and Parameters

UNIQUE	enables the UNIQUE constraint defined on the specified column or combination of columns.

PRIMARY KEY	enables the table's PRIMARY KEY constraint.

CONSTRAINT	enables the integrity constraint named constraint.

USING INDEX	specifies parameters for the index ORACLE creates to enforce a UNIQUE or PRIMARY KEY constraint. ORACLE gives the index the same name as the constraint. You can choose the values of the INITRANS, MAXTRANS, TABLESPACE, STORAGE, and PCTFREE parameters for the index. For information on these parameters, see the CREATE TABLE command earlier in this chapter.

Only use these parameters when enabling UNIQUE and PRIMARY KEY constraints.

EXCEPTIONS INTO	identifies a table into which ORACLE places information about rows that violate the integrity constraint. The table must exist before you use this option. If you omit schema, ORACLE assumes the exception table is in your own schema. The exception table must be on your local database.

ALL TRIGGERS	enables all triggers associated with the table. You can only use this option in an ENABLE clause in an ALTER TABLE statement, not a CREATE TABLE statement.

Usage Notes

 You can use the ENABLE clause to enable either:

•	a single integrity constraint

•	all triggers associated with a table

To enable a single trigger, use the ENABLE option of the ALTER TRIGGER command.

 How to Enable Integrity Constraints

You can enable an integrity constraint by including an ENABLE clause in either a CREATE TABLE or ALTER TABLE statement. You can define an integrity constraint with a CONSTRAINT clause and enable it with an ENABLE clause together in the same statement. You can also define an integrity constraint in one statement and subsequently enable it in another.

You can also enable an integrity constraint by including the ENABLE keyword in CONSTRAINT clause that defines the integrity constraint. For information on this keyword, see the CONSTRAINT clause earlier in this chapter.

If you define an integrity constraint and do not explicitly enable or disable it, ORACLE enables it by default.

How ORACLE Enforces Integrity Constraints      When you attempt to enable an integrity constraint, ORACLE applies the integrity constraint to any existing rows in the table:

•	If all rows in the table satisfy the integrity constraint, then ORACLE enables the integrity constraint.

•	If any row in the table violates the integrity constraint, the integrity constraint remains disabled. ORACLE returns an error message indicating the integrity constraint is still disabled.

Once an integrity constraint is enabled, ORACLE applies the integrity constraint whenever an INSERT, UPDATE, or DELETE statement tries to change table data:

•	If the new data satisfies the integrity constraint, then ORACLE executes the statement.

•	If the new data violates the integrity constraint, then ORACLE does not execute the statement. Instead, ORACLE generates an error message indicating the integrity constraint violation.

How to Identify Exceptions      An exception is a row in a table that violates an integrity constraint. You can request that ORACLE identify exceptions to an integrity constraint. If you specify an exception table in your ENABLE clause, ORACLE inserts a row into the exception table for each exception. A row of the exception table contains this information:

•	the ROWID of the exception

•	the name of the integrity constraint

•	the schema and name of the table

A definition of a sample exception table named EXCEPTIONS appears in a SQL script available on your distribution media. Your exception table must have the same column datatypes and lengths as the sample. The common name of this script is UTLEXCPT.SQL, although its exact name and location may vary depending on your operating system. You can request that ORACLE send exceptions from multiple enabled integrity constraints to the same exception table.

To specify an exception table in an ENABLE clause, you must have the privileges necessary to insert rows into the table. For information on these privileges, see the INSERT command later in this chapter. To examine the identified exceptions, you must have the privileges necessary to query the exceptions table. For information on these privileges, see the SELECT command later in this chapter.

If a CREATE TABLE statement contains both the AS clause and an ENABLE clause with the EXCEPTIONS option, ORACLE ignores the EXCEPTIONS option. If there are any exceptions, ORACLE does not create the table and returns an error message.

Example I	This statement creates the DEPT table and defines and enables a PRIMARY KEY constraint:

CREATE TABLE dept

(deptno  NUMBER(2)      PRIMARY KEY,

 dname   VARCHAR2(10),

 loc     VARCHAR2(9) )

TABLESPACE user_a

ENABLE PRIMARY KEY USING INDEX INITRANS 3

                   STORAGE (INITIAL 10K   NEXT 10K 	                                    MINEXTENTS 2  MAXEXTENTS 10)

                            TABLESPACE user_b 	                                           PCTFREE 5

ORACLE enforces the PRIMARY KEY constraint with an index. The ENABLE clause specifies INITRANS, STORAGE parameters, TABLESPACE, and PCTFREE values for the data blocks of the index.

Example II	This statement enables an integrity constraint named FK_DEPTNO in the EMP table:

ALTER TABLE emp

ENABLE CONSTRAINT fk_deptno

EXCEPTIONS INTO except_table

Each row of the EMP table must satisfy the constraint for ORACLE to enable the constraint. If any row violates the constraint, the constraint remains disabled. ORACLE lists any exceptions in the table EXCEPT_TABLE. You can query this table with this statement:

SELECT *

FROM except_table

The output of this query might look like this:

ROW_ID              OWNER  TABLE_NAME  CONSTRAINT

------------------  -----  ----------  ---------- 0000346A.0001.0003  SCOTT  EMP         FK_DEPTNO

You can also identify the exceptions in the EMP table with this statement:

SELECT emp.*

FROM emp, except_table

WHERE emp.row_id except_table.row_id

  AND except_table.table_name = 'EMP'

  AND except_table.constraint = 'FK_DEPTNO'

If there are exceptions to the FK_DEPTNO constraint, the output of this query might look like this:

EMPNO ENAME    JOB    MGR      HIREDATE   SAL      COMM    DEPTNO

---- -------- ------ -------- ---------- -------- -------- ------- 8001 JACK     CLERK       7788 25-AUG-92     1100               70

Example III	This statement tries to enable two constraints on the EMP table:

ALTER TABLE emp

ENABLE UNIQUE (ename)

 	ENABLE CONSTRAINT nn_ename

This statement has two ENABLE clauses:

•	The first enables a UNIQUE constraint on the ENAME column.

•	The second enables the constraint named NN_ENAME.

In this case, ORACLE only enables the constraints if both are satisfied by each row in the table. If any row violates either constraint, ORACLE returns an error message and both constraints remain disabled.

 How to Enable Triggers

You can enable all triggers associated with the table by including the ALL TRIGGERS option in an ENABLE clause of an ALTER TABLE statement. After you enable a trigger, ORACLE fires the trigger whenever a triggering statement is issued that meets the condition of the trigger restriction. When you create a trigger, ORACLE enables it automatically.

Example IV

This statement enables all triggers associated with the EMP table:

ALTER TABLE emp

ENABLE ALL TRIGGERS

Related Topics

ALTER TABLE, ALTER TRIGGER, CREATE TABLE, and CREATE TRIGGER commands; CONSTRAINT, DISABLE, and STORAGE clauses.

________________________________________

EXECUTE (Prepared SQL Statements and PL/SQL Blocks) (Embedded SQL)

Purpose

To execute a DELETE, INSERT, or UPDATE statement or a PL/SQL block that has been previously prepared with an embedded SQL PREPARE statement.

Prerequisites

You must first prepare the SQL statement or PL/SQL block with an embedded SQL PREPARE statement.

Syntax

Keywords and Parameters

FOR :host_integer	limits the number of times the statement is executed when the USING clause contains array host variables  If you omit this clause, ORACLE executes the statement once for each component of the smallest array.

statement_name block_name	identifies the SQL statement or PL/SQL block to be executed. The SQL statement can only be a DELETE, INSERT, or UPDATE statement. You must use the embedded SQL PREPARE command to associate this identifier with the statement.

USING	specifies a list of host variables with optional indicator variables that ORACLE substitutes as input variables into the statement to be executed. The host and indicator variables must be either all scalars or all arrays.

Usage Notes

Example	This example illustrates the use of the EXECUTE statement in a Pro*C embedded SQL program:

EXEC SQL PREPARE my_statement

FROM :my_string;

EXEC SQL EXECUTE my_statement

 	USING :my_var;

Related Topics

DECLARE DATABASE, PREPARE command.

________________________________________

EXECUTE (Anonymous PL/SQL Blocks) (Embedded SQL)

Purpose

To embed an anonymous PL/SQL block into an ORACLE Precompiler program.

Prerequisites

None.

Syntax

Keywords and Parameters

AT	identifies the database on which the PL/SQL block is executed. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, the PL/SQL block is executed on your default database.

pl/sql_block	For information on PL/SQL, including how to write PL/SQL blocks, see the PL/SQL User's Guide and Reference.

END-EXEC	must appear after the embedded PL/SQL block, regardless of which programming language your ORACLE Precompiler program uses. Of course, the keyword END-EXEC must be followed by the embedded SQL statement terminator for the specific language.

Usage Notes

Since the ORACLE Precompilers treat an embedded PL/SQL block like a single embedded SQL statement, you can embed a PL/SQL block anywherein an ORACLE Precompiler program that you can embed a SQL statement. For more information on embedding PL/SQL blocks in ORACLE Precompiler programs, see the Programmer's Guide to the ORACLE Precompilers.

Example	Placing this EXECUTE statement in an ORACLE Precompiler program embeds a PL/SQL block in the program:

EXEC SQL EXECUTE

BEGIN

SELECT ename, job, sal

INTO :emp_name:ind_name, :job_title, :salary

FROM emp

WHERE empno = :emp_number;

IF :emp_name:ind_name IS NULL

   THEN RAISE name_missing;

END IF;

END;

END-EXEC

Related Topics

EXECUTE and EXECUTE IMMEDIATE embedded SQL commands.

________________________________________

EXECUTE IMMEDIATE (Embedded SQL)

Purpose

To prepare and execute a DELETE, INSERT, or UPDATE statement or a PL/SQL block containing no host variables.

Prerequisites

None.

Syntax

Keywords and Parameters

AT	identifies the database on which the SQL statement or PL/SQL block is executed. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, the statement or block is executed on your default database.

:host_string	is a host variable whose value is the SQL statement or PL/SQL block to be executed.

'text'	is a quoted text literal containing the SQL statement or PL/SQL block to be executed.

The SQL statement can only be a DELETE, INSERT, or UPDATE statement.

Usage Notes

When you issue an EXECUTE IMMEDIATE statement, ORACLE parses the specifiedSQL statement or PL/SQL block, checking for errors, and executes it. Ifany errors are encountered, they are returned in the SQLCODE component of the SQLCA.

For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example	This example illustrates the use of the EXECUTE IMMEDIATE statement:

EXEC SQL EXECUTE IMMEDIATE 'DELETE FROM emp WHERE empno = 9460'

Related Topics

PREPARE and EXECUTE commands.

________________________________________

EXPLAIN PLAN

Purpose

To determine the execution plan ORACLE follows to execute a specified SQL statement. This command inserts a row describing each step of the execution plan into a specified table. If you are using cost-based optimization, this command also determines the cost of executing the statement.

Prerequisites

To issue an EXPLAIN PLAN statement, you must have the privileges necessary to insert rows into an existing output table that you specify to hold the execution plan. For information on these privileges, see the INSERT command later in this chapter.

You must also have the privileges necessary to execute the SQL statement for which you are determining the execution plan. If the SQL statement accesses a view, you must have privileges to access any tables and views on which the view is based. If the view is based on another view that is based on a table, you must have privileges to access both the other view and its underlying table. You should not use the EXPLAIN PLAN command to determine the execution plans of SQL statements that access data dictionary views or dynamic performance tables.

To examine the execution plan produced by an EXPLAIN PLAN statement, you must have the privileges necessary to query the output table. For more information on these privileges, see the SELECT command later in this chapter.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the output table's creation label or you must satisfy one of these criteria:

•	If the output table's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the output table's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

SET	specifies the value of the STATEMENT_ID column for the rows of the execution plan in the output table. If you omit this clause, the STATEMENT_ID value defaults to null.

INTO 	specifies the schema, name, and database containing the output table. This table must exist before you use the EXPLAIN PLAN command. If you omit schema, ORACLE assumes the table is in your own schema.

The dblink can be a complete or partial name of a database link to a remote ORACLE7 database where the output table is located. For information on referring to database links, see the section "Referring to Objects in Remote  on page 2 - 13. You can only specify a remote output table if you are using ORACLE with the distributed option. If you omit dblink, ORACLE assumes the table is on your local database.

If you omit the INTO clause altogether, ORACLE assumes an output table named PLAN_TABLE in your own schema on your local database.

FOR	specifies a SELECT, INSERT, UPDATE, or DELETE statement for which the execution plan is generated.

Usage Notes

 The definition of a sample output table PLAN_TABLE is available ina SQL script on your distribution media. Your output table must havethe same column names and datatypes as this table. The common name of this script is UTLXPLAN.SQL, although the exact name and location may vary depending on your operating system.

The value you specify in the SET clause appears in the STATEMENT_ID column in the rows of the execution plan. You can then use this value to identify these rows among others in the output table. Be sure to specify a STATEMENT_ID value if your output table contains rows from many execution plans.

Since the EXPLAIN PLAN command is a Data Manipulation Language command, rather than a Data Definition Language command, ORACLE does not implicitly commit the changes made by an EXPLAIN PLAN statement. If you want to keep the rows generated by an EXPLAIN PLAN statement in the output table, you must commit the transaction containing the statement.

You can also issue the EXPLAIN PLAN command as part of the SQL trace facility. For information on how to use the SQL trace facility and how to interpret execution plans, see Appendix B  of the ORACLE7 Server Application Developer's Guide.

Example	This EXPLAIN PLAN statement determines the execution plan and cost for an UPDATE statement and inserts rows describing the execution plan into the specified OUTPUT table with the STATEMENT_ID value of 'Raise in Chicago':

EXPLAIN PLAN

SET STATEMENT_ID = 'Raise in Chicago'

INTO output

FOR UPDATE emp

SET sal = sal * 1.10

WHERE deptno =  (SELECT deptno

  	     FROM dept 	     WHERE loc = 'CHICAGO')

This SELECT statement queries the OUTPUT table and returns the execution plan and the cost:

SELECT LPAD(' ',2*(LEVEL-1))||operation operation, options,

object_name, position

FROM output

START WITH id = 0 AND statement_id = 'Raise in Chicago'

 	CONNECT BY PRIOR id = parent_id AND

statement_id = 'Raise in Chicago'

The query returns this execution plan:

OPERATION	OPTIONS	OBJECT_NAME	POSITION

----------------------------------------------------------------

UPDATE STATEMENT	       1

FILTER	       0

TABLE ACCESS	FULL	EMP	       1   TABLE ACCESS	FULL	DEPT	       2

The value in the POSITION column of the first row shows that the statement has a cost of 1.

Related Topics

Appendix B "Performance Diagnostic Tools" of the ORACLE7 Server Application Developer's Guide.

________________________________________

FETCH (Embedded SQL)

Purpose

To retrieve one or more rows returned by a query, assigning the select list values to host variables.

Prerequisites

You must first open the cursor with an the OPEN statement.

Syntax

Keywords and Parameters

FOR :host_integer	limits the number of rows fetched if you are using array host variables. If you omit this clause, ORACLE fetches enough rows to fill the smallest array.

cursor	is a cursor that has been declared by a DECLARE CURSOR statement. The FETCH statement returns one of the rows selected by the query associated with the cursor.

INTO	specifies a list of host variables and optional indicator variables into which data is fetched. These host variables and indicator variables must be declared within the program.

USING	specifies the descriptor referenced in a previous DESCRIBE statement. Only use this clause with dynamic embedded SQL, method 4.

Usage Notes

 The FETCH statement reads the rows of the active set and names theoutput variables which contain the results. Indicator values areset to -1 if their associated host variable is null. The first FETCH statement for a cursor also sorts the rows of the active set, if necessary.

The number of rows retrieved is specified by the size of the output host variables and the value specified in the FOR clause. The host variables to receive the data must be either all scalars or all arrays. If they are scalars, ORACLE fetches only one row. If they are arrays, ORACLE fetches enough rows to fill the arrays.

Array host variables can have different sizes. In this case, the number of rows ORACLE fetches is determined by the smaller of these values:

•	the size of the smallest array

•	the value of the :host_integer in the optional FOR clause

Of course, the number of rows fetched can be further limited by the number of rows that actually satisfy the query.

If a FETCH statement does not retrieve all rows returned by the query, the cursor is positioned on the next returned row. When the last row returned by the query has been retrieved, the next FETCH statement results in an error code returned in the SQLCODE element of the SQLCA.

Note that the FETCH command does not contain an AT clause. You must specify the database accessed by the cursor in the DECLARE CURSOR statement.

You can only move forward through the active set with FETCH statements. If you want to revisit any of the previously fetched rows, you must re-open the cursor and fetch each row in turn. If you want to change the active set, you must assign new values to the input host variables in the cursor's query and reopen the cursor.

Example	This example illustrates the FETCH command in a pseudo-code embedded SQL program:

EXEC SQL DECLARE emp_cursor CURSOR FOR 	SELECT job, sal FROM emp WHERE deptno = 30;

...

EXEC SQL WHENEVER NOT FOUND GOTO ...

LOOP

EXEC SQL FETCH emp_cursor INTO :job_title1, :salary1;

EXEC SQL FETCH emp_cursor INTO :job_title2, :salary2;

...

ENDLOOP;

...

Related Topics

PREPARE, DECLARE CURSOR, OPEN, and CLOSE commands.

________________________________________

Filespec

Purpose

To either specify a file as a data file or specify a group of one or more files as a redo log file group.

Prerequisites

A filespec can appear in either CREATE DATABASE, ALTER DATABASE, CREATE TABLESPACE, or ALTER TABLESPACE commands. You must have the privileges necessary to issue one of these commands. For information on these privileges, see the CREATE DATABASE, ALTER DATABASE, CREATE TABLESPACE, and ALTER TABLESPACE commands earlier in this chapter.

Syntax

Keywords and Parameters

'filename'	is the name of either a data file or a redo log file member. A redo log file group can have one or more members, or copies. Each 'filename' must be fully specified according to the conventions for your operating system.

SIZE	specifies the size of the file. If you omit this parameter, the file must already exist.

K	specifies the size in kilobytes.

M	specifies the size in megabytes.

If you omit K and M, the size is specified in bytes.

REUSE	allows ORACLE to reuse an existing file. If the file already exists, ORACLE verifies that its size matches the value of the SIZE parameter. If the file does not exist, ORACLE creates it. If you omit this option, the file must not already exist and ORACLE creates the file.

The REUSE option is only significant when used with the SIZE option. If you omit the SIZE option, ORACLE expects the file to exist already. Note that whenever ORACLE uses an existing file, the file's previous contents are lost.

Example I	This statement creates a database named PAYABLE that has two redo log file groups, each with two members, and one data file:

CREATE DATABASE payable

LOGFILE GROUP 1 ('diska:log1.log', 'diskb:log1.log') SIZE 50K,

GROUP 2 ('diska:log2.log', 'diskb:log2.log') SIZE 50K

DATAFILE 'diskc:dbone.dat' SIZE 30M

The first filespec in the LOGFILE clause specifies a redo log file group with the GROUP value 1. This group has members named 'DISKA:LOG1.LOG' and 'DISKB:LOG1.LOG' each with size 50 kilobytes.

The second filespec in the LOGFILE clause specifies a redo log file group with the GROUP value 2. This group has members named 'DISKA:LOG2.LOG' and 'DISKB:LOG2.LOG', also with sizes of 50 kilobytes.

The filespec in the DATAFILE clause specifies a data file named 'DISKC:DBONE.DAT' of size 30 megabytes.

Since all of these filespecs specify a value for the SIZE parameter and omit the REUSE option, these files must not already exist. ORACLE must create them.

Example II	This statement adds another redo log file group with two members to the PAYABLE database:

ALTER DATABASE payable

ADD LOGFILE GROUP 3 ('diska:log3.log', 'diskb:log3.log')

SIZE 50K REUSE

The filespec in the ADD LOGFILE clause specifies a new redo log file group with the GROUP value 3. This new group has members named 'DISKA:LOG3.LOG' and 'DISKB:LOG3.LOG' with sizes of 50 kilobytes each. Since the filespec specifies the REUSE option, each member can already exist. If a member exists, it must have a size of 50 kilobytes. If it does not exist, ORACLE creates it with that size.

Example III	This statement creates a tablespace named STOCKS that has three data files:

CREATE TABLESPACE stocks

DATAFILE 'diskc:stock1.dat',

         'diskc:stock2.dat',

 	         'diskc:stock3.dat'

The filespecs for the data files specifies files named 'DISKC:STOCK1.DAT', 'DISKC:STOCK2.DAT', 'DISKC:STOCK3.DAT'. Since each filespec omits the SIZE parameter, each file must already exist.

Example IV	This statement alters the STOCKS tablespace and adds a new data file:

ALTER TABLESPACE stocks

ADD DATAFILE 'diskc:stock4.dat' REUSE

The filespec specifies a data file named 'DISKC:STOCK4.DAT'. Since the filespec omits the SIZE parameter, the file must already exist and the REUSE option is not significant.

Related Topics

 CREATE DATABASE, ALTER DATABASE, CREATE TABLESPACE, and ALTER TABLESPACEcommands.

________________________________________

GRANT (System Privileges and Roles)

Purpose

To grant system privileges and roles to users and roles. To grant object privileges, use the GRANT command (Object Privileges) described in the next section of this chapter.

Prerequisites

To grant a system privilege, you must either have been granted the system privilege with the ADMIN OPTION or have been granted GRANT ANY PRIVILEGE system privilege.

To grant a role, you must either have been granted the role with the ADMIN OPTION or have been granted GRANT ANY ROLE system privilege or have created the role.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate both the label at which the system privilege or role was granted to you and the creation label of the grantee user or role.

Syntax

Keywords and Parameters

system_priv	is a system privilege to be granted.

role	is a role to be granted.

TO 	identifies users or roles to which system privileges and roles are granted.

PUBLIC	grants system privileges or roles to all users.

WITH ADMIN OPTION	allows the grantee to grant the system privilege or role to other users or roles. If you grant a role with ADMIN OPTION, the grantee can also alter or drop the role.

Usage Notes

You can use this form of the GRANT command to grant both system privileges and roles to users, roles, and PUBLIC:

If you grant a privilege to a user:      ORACLE adds the privilege to the user's privilege domain. The user can immediately exercise the privilege.

If you grant a privilege to a role:      ORACLE adds the privilege to the role's privilege domain. Users who have been granted and have enabled the role can immediately exercise the privilege. Other users who have been granted the role can enable the role and exercise the privilege.

If you grant a privilege to PUBLIC:      ORACLE adds the privilege to the privilege domains of each user. All users can immediately perform operations authorized by the privilege.

If you grant a role to a user:      ORACLE makes the role available to the user. The user can immediately enable the role and exercise the privileges in the role's privilege domain.

If you grant a role to another role:      ORACLE adds the granted role's privilege domain to the grantee role's privilege domain. Users who have been granted the grantee role can enable it and exercise the privileges in the granted role's privilege domain.

If you grant a role to PUBLIC:      ORACLE makes the role available to all users. All users can immediately enable the role and exercise the privileges in the roles privilege domain.

A privilege or role cannot appear more than once in the list of privileges and roles to be granted. A user, role, or PUBLIC cannot appear more than once in the TO clause.

You cannot grant roles circularly. For example, if you grant the role BANKER to the role TELLER, you cannot subsequently grant TELLER to BANKER. Also, you cannot grant a role to itself.

System Privileges

Table 6 - 1 lists system privileges and the operations that they authorize. You can grant any of these system privileges with the GRANT command.

System Privilege	Operations Authorized

ALTER ANY 	Allows grantee to alter any cluster in any

CLUSTER	schema.

ALTER ANY INDEX	Allows grantee to alter any index in any sche

ma

ALTER ANY 	Allows grantee to alter any stored procedure,

PROCEDURE	function, or package in any schema.

ALTER ANY ROLE	Allows grantee to alter any role in the data

base.

ALTER ANY 	Allows grantee to alter any sequence in the

SEQUENCE	database.

ALTER ANY 	Allows grantee to alter any snapshot in the

SNAPSHOT	database.

ALTER ANY TABLE	Allows grantee to alter any table or view in

the schema.

ALTER ANY 	Allows grantee to enable, disable, or compile

TRIGGER	any database trigger in any schema.

ALTER DATABASE	Allows grantee to alter the database.

ALTER PROFILE	Allows grantee to alter profiles.

ALTER RESOURCE 	Allows grantee to set costs for session re

COST	sources.

ALTER ROLLBACK 	Allows grantee to alter rollback segments.

SEGMENT

ALTER SESSION	Allows grantee to issue ALTER SESSION

statements.

ALTER SYSTEM	Allows grantee to issue ALTER SYSTEM

statements.

ALTER TABLESPACE	Allows grantee to alter tablespaces.

ALTER USER	Allows grantee to alter any user. This privi

lege authorizes the grantee to change another

user's password or authentication method,

assign quotas on any tablespace, set default

and temporary tablespaces, and assign a pro

file and default roles.

ANALYZE ANY	Allows grantee to analyze any table, cluster,

or index in any schema.

AUDIT ANY	Allows grantee to audit any object in any

schema using AUDIT (Schema Objects) state

ments.

AUDIT SYSTEM	Allows grantee to issue AUDIT (SQL State

ments) statements.

BECOME USER	Allows grantee to use the Import utility to

import objects in the schemas of other users.

BACKUP ANY 	Allows grantee to use the Export utility to

TABLE	export objects in the schemas of other users.

COMMENT ANY 	Allows grantee to comment on any table,

TABLE	view, or column in any schema.

CREATE ANY 	Allows grantee to create a cluster in any sche

CLUSTER	ma. Behaves similarly to CREATE ANY

TABLE.

CREATE ANY 	Allows grantee to create an index in any

INDEX	schema on any table in any schema.

CREATE ANY 	Allows grantee to create stored procedures,

PROCEDURE	functions, and packages in any schema.

CREATE ANY 	Allows grantee to create a sequence in any

SEQUENCE	schema.

CREATE ANY S	Allows grantee to create snapshots in any

NAPSHOT	schema.

CREATE ANY 	Allows grantee to create private synonyms in

SYNONYM	any schema.

CREATE ANY 	Allows grantee to create tables in any sche

TABLE	ma. The owner of the schema containing the

table must have space quota on the table

space to contain the table.

CREATE ANY 	Allows grantee to create a database trigger in

TRIGGER	any schema associated with a table in any

schema.

CREATE ANY VIEW	Allows grantee to create views in any sche

ma.

CREATE CLUSTER	Allows grantee to create clusters in own sche

ma.

CREATE DATABASE 	Allows grantee to create private database

LINK	links in own schema.

CREATE PROCE	Allows grantee to create stored procedures,

DURE	functions, and packages in own schema.

CREATE PROFILE	Allows grantee to create profiles.

CREATE PUBLIC 	Allows grantee to create public database

DATABASE LINK	links.

CREATE PUBLIC 	Allows grantee to create public synonyms.

SYNONYM

CREATE ROLE	Allows grantee to create roles.

CREATE ROLLBACK 	Allows grantee to create rollback segments.

SEGMENT

CREATE SESSION	Allows grantee to connect to the database.

CREATE SNAPSHOT	Allows grantee to create snapshots in own

schema.

CREATE SYNONYM	Allows grantee to create synonyms in own

schema.

CREATE TABLE	Allows grantee to create tables in own sche

ma. To create a table, the grantee must also

have space quota on the tablespace to contain

the table.

CREATE 	Allows grantee to create tablespaces.

TABLESPACE

CREATE TRIGGER	Allows grantee to create a database trigger in

own schema.

CREATE USER	Allows grantee to create users. This privilege

also allows the creator to assign quotas on

any tablespace, set default and temporary

tablespaces, and assign a profile as part of a

CREATE USER statement.

CREATE VIEW	Allows grantee to create views in own sche

ma.

DELETE ANY TABLE	Allows grantee to delete rows from tables or

views in any schema or truncate tables in any

schema.

DROP ANY 	Allows grantee to drop clusters in any sche

CLUSTER	ma.

DROP ANY INDEX	Allows grantee to drop indexes in any sche

ma.

DROP ANY 	Allows grantee to drop stored procedures,

PROCEDURE	functions, or packages in any schema.

DROP ANY ROLE	Allows grantee to drop roles.

DROP ANY 	Allows grantee to drop sequences in any

SEQUENCE	schema.

DROP ANY 	Allows grantee to drop snapshots in any

SNAPSHOT	schema.

DROP ANY 	Allows grantee to drop private synonyms in

SYNONYM	any schema.

DROP ANY TABLE	Allows grantee to drop tables in any schema.

DROP ANY 	Allows grantee to drop database triggers in

TRIGGER	any schema.

DROP ANY VIEW	Allows grantee to drop views in any schema

DROP PROFILE	Allows grantee to drop profiles.

DROP PUBLIC 	Allows grantee to drop public database links.

DATABASE LINK

DROP PUBLIC 	Allows grantee to drop public synonyms.

SYNONYM

DROP ROLLBACK 	Allows grantee to drop rollback segments.

SEGMENT

DROP TABLESPACE	Allows grantee to drop tablespaces.

DROP USER	Allows grantee to drop users.

EXECUTE ANY 	Allows grantee to execute procedures or

PROCEDURE	functions (stand-alone or packaged) or refer

ence public package variables in any schema.

FORCE ANY 	Allows grantee to for the commit or rollback

TRANSACTION	of any in-doubt distributed transaction in the

local database. Also allows the grantee to in

duce the failure of a distributed transaction.

FORCE 	Allows grantee to force the commit or roll

TRANSACTION	back of own in-doubt distributed transac

tions in the local database.

GRANT ANY 	Allows grantee to grant any system privilege.

PRIVILEDGE

GRANT ANY ROLE	Allows grantee to grant any role in the data

base.

INSERT ANY TABLE	Allows grantee to insert rows into tables and

views in any schema.

LOCK ANY TABLE	Allows grantee to lock tables and views in

any schema.

MANAGE TABLE	Allows grantee to take tablespaces offline

SPACE	and online and begin and end tablespace

backups.

READUP	Allows grantee to query data having an ac

cess class higher than the grantee's session

label. This privilege is only available in

Trusted ORACLE.

RESTRICTED 	Allows grantee to logon after the instance is

SESSION	started using the SQL*DBA STARTUP RE

STRICT command.

SELECT ANY 	Allows grantee to reference sequences in any

SEQUENCE	schema.

SELECT ANY TABLE	Allows grantee to query tables, views,. or

snapshots in any schema.

UNLIMITED TABLE	Allows grantee to use an unlimited amount

SPACE	of anytablespace. This privilege overrides

any specific quotas assigned. If you revoke

this privilege from a user, the grantee's sche

ma objects remain but further tablespace al

location is denied unless authorized by spe

cific tablespace quotas. You cannot grant this

system privilege to roles.

UPDATE ANY 	Allows grantee to update rows in tables and

TABLE	views in any schema.

WRITEDOWN	Allows grantee to create, alter, and drop

schema objects and to insert, update, and de

lete rows having access classes lower than the

grantee's session label. This privilege is only

available in Trusted ORACLE.

WRITEUP	Allows grantee to create, alter, and drop

schema objects and to insert, update, and de

lete rows having access classes higher than

the grantee's session label. This privilege is

only available in Trusted ORACLE.

Table 6 - 1.  System Privileges

Roles Defined by ORACLE

Some roles are created automatically by ORACLE. When you create a database, ORACLE creates these roles and grants them certain system privileges. Table 6 - 2 lists each predefinedrole and its system privileges.

Role	System Privileges and Roles Granted

CONNECT	ALTER SESSION

CREATE CLUSTER

CREATE DATABASE LINK

CREATE SEQUENCE

CREATE SESSION

CREATE SYNONYM

CREATE TABLE

CREATE VIEW

RESOURCE	CREATE CLUSTER

CREATE PROCEDURE

CREATE SEQUENCE

CREATE TABLE

CREATE TRIGGER

DBA	All systems privileges

WITH ADMIN OPTION

EXP_FULL_DATABASE role

IMP_FULL_DATABASE role

EXP_FULL_DATA	SELECT ANY TABLE

BASE	BACKUP ANY TABLE

INSERT, UPDATE, DELETE

ON sys.incexp

sys.incvid

sys.incfil

IMP_FULL_DATA	BECOME USER

BASE	WRITEDOWN (in Trusted ORACLE)

Table 6 - 2.  Roles defined by ORACLE

Note: If you grant or revoke the RESOURCE or DBA role to or from a user, ORACLE implicitly grants or revokes the UNLIMITED TABLESPACE system privilege to or from the user.

The CONNECT, RESOURCE, and DBA are provided for compatibility with previous versions of ORACLE. The SQL script SQL.BSQ creates these roles, grants privileges to them, and grants the DBA role with ADMIN OPTION to the users SYS and SYSTEM. This script is available on your distribution media, although its exact name and location may vary depending on your operating system. Oracle Corporation encourages you to design your own roles for database security, rather than rely on these roles. These roles may not be automatically created by future versions of ORACLE.

The EXP_FULL_DATABASE and IMP_FULL_DATABASE roles are provided for convenience in using the Import and Export utilities. The SQL script CATEXP.SQL creates these roles, grants privileges to them, and grants them to the DBA role. This script is available on your distribution media, although its exact name and location may vary depending on your operating system.

ADMIN OPTION

A grant with the ADMIN OPTION supersedes a previous identical grant without the ADMIN OPTION. If you grant a system privilege or role to user without the ADMIN OPTION, and then subsequently grant the privilege or role to the user with the ADMIN OPTION, the user has the ADMIN OPTION on the privilege or role.

A grant without the ADMIN OPTION does not supersede a previous grant with the ADMIN OPTION. To revoke the ADMIN OPTION on a system privilege or role from a user, you must revoke the privilege or role from the user altogether and then grant the privilege or role to the user without the ADMIN OPTION.

Granting Roles Through Your Operating System

Some operating systems have facilities that grant operating system privileges to operating system users. You can use such facilities to grant roles to ORACLE users with the initialization parameter OS_ROLES. If you choose to grant roles to users through operating system facilities, you cannot also grant roles to users with the GRANT command, although you can use the GRANT command to grant system privileges to users and system privileges and roles to other roles.

Example I	To grant the CREATE SESSION system privilege to RICHARD, allowing RICHARD to logon to ORACLE, issue this statement:

GRANT CREATE SESSION

TO richard

Example II	To grant the CREATE TABLE system privilege to the role TRAVEL_AGENT, issue this statement:

GRANT CREATE TABLE

TO travel_agent

TRAVEL_AGENT's privilege domain now contains the CREATE TABLE system privilege.

This statement grants the TRAVEL_AGENT role to the EXECUTIVE role:

GRANT travel_agent

TO executive

TRAVEL_AGENT is now granted to EXECUTIVE. EXECUTIVE's privilege domain contains the CREATE TABLE system privilege.

To grant the EXECUTIVE role with the ADMIN OPTION to THOMAS, issue this statement:

GRANT executive

TO thomas

WITH ADMIN OPTION

THOMAS can now perform these operations with the EXECUTIVE role:

•	enable the role and exercise any privileges in the role's privilege domain, including the CREATE TABLE system privilege

•	grant and revoke the role to and from other users

•	drop the role

Related Topics

ALTER USER, CREATE USER, GRANT (Object Privileges), and REVOKE (System Privileges and Roles) commands.

________________________________________

GRANT (Object Privileges)

Purpose

To grant privileges for a particular object to users and roles. To grant system privileges and roles, use the GRANT command (System Privileges and Roles) described in the previous section of this chapter.

Prerequisites

The object must be in your own schema or you must have been granted the object privileges with the GRANT OPTION.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the label at which the object privilege was granted to you and the creation label of the grantee user or role.

Syntax

Keywords and Parameters

object_priv	is an object privilege to be granted. You can substitute any of these values:

•	ALTER

•	DELETE

•	EXECUTE

•	INDEX

•	INSERT

•	REFERENCES

•	SELECT

•	UPDATE

ALL PRIVILEGES	grants all the privileges for the object that you have been granted with the GRANT OPTION. The user who owns the schema containing an object automatically has all privileges on the object with the GRANT OPTION.

column	specifies a table or view column on which privileges are granted. You can only specify columns when granting the INSERT, REFERENCES, or UPDATE privilege. If you do not list columns, the grantee has the specified privilege on all columns in the table or view.

ON	identifies the object on which the privileges are granted. If you do not qualify object with schema, ORACLE assumes the object is in your own schema. The object can be one of these types:

•	table

•	view

•	sequence

•	procedure, function, or package

•	snapshots

•	synonym for a table, view, sequence, snapshot, procedure, function, or package

TO	identifies users or roles to which the object privilege is granted.

PUBLIC	grants object privileges to all users.

WITH GRANT OPTION	allows the grantee to grant the object privileges to other users and roles. The grantee must be a user or PUBLIC, rather than a role.

Usage Notes

 You can use this form of the GRANT statement to grant object privileges to users, roles, and PUBLIC:

If you grant a privilege to a user:      ORACLE adds the privilege to the user's privilege domain. The user can immediately exercise the privilege.

If you grant a privilege to a role:      ORACLE adds the privilege to the role's privilege domain. Users who have been granted and have enabled the role can immediately exercise the privilege. Other users who have been granted the role can enable the role and exercise the privilege.

If you grant a privilege to PUBLIC:      ORACLE adds the privilege to the privilege domain of each user. All users can immediately exercise the privilege.

A privilege cannot appear more than once in the list of privileges to be granted. A user or role cannot appear more than once in the TO clause.

Object Privileges

Each object privilege that you grant authorizes the grantee to perform some operation on the object. Table 6 - 3 summarizes the object privileges that you can grant on each type of object.

Procedure

Functions

Object Privilege	Tables	Views	Sequences	Packages	Snapshots

ALTER	3	3

DELETE	3	3

EXECUTE	3

INDEX	3

INSERT	3	3

REFERENCES	3

SELECT	3	3	3	3

UPDATE	3	3

Table 6 - 3.  Object Privileges

 Table Privileges

These object privileges authorize operations on a table:

ALTER	allows the grantee to change the table definition with the ALTER TABLE command.

DELETE	allows the grantee to remove rows from the table with the DELETE command.

INDEX	allows the grantee to create an index on the table with the CREATE INDEX command.

INSERT	allows the grantee to add new rows to the table with the INSERT command.

REFERENCES	allows the grantee to create a constraint that refers to the table. You cannot grant this privilege to a role.

SELECT	allows the grantee to query the table with the SELECT command.

UPDATE	allows the grantee to change data in the table with the UPDATE command.

Any one of these object privileges allows the grantee to lock the table in any lockmode with the LOCK TABLE command.

 View Privileges

These object privileges authorize operations on a view:

DELETE	allows the grantee to remove rows from the view with the DELETE command.

INSERT	allows the grantee to add new rows to the view with the INSERT command.

SELECT	allows the grantee to query the view with the SELECT command.

UPDATE	allows the grantee to change data in the view with the UPDATE command.

Any one of these object privileges allows the grantee to lock the view in any lockmode with the LOCK TABLE command.

To grant a privilege on a view, you must have that privilege with the GRANT OPTION on all of the view's base tables.

 Sequence Privileges

These object privileges authorize operations on a sequence:

ALTER	allows the grantee to change the sequence definition with the ALTER SEQUENCE command.

SELECT	allows the grantee to examine and increment values of the sequence with the CURRVAL and NEXTVAL pseudocolumns.

 Procedure, Function, and Package Privileges

This object privilege authorizes operations on a procedure, function, or package:

EXECUTE	allows the grantee to execute the procedure or function or to access any program object declared in the specification of a package.

 Snapshot Privileges

This object privilege authorizes operations on a snapshot:

SELECT	allows the grantee to query the snapshot with the SELECT command.

 Synonym Privileges

The object privileges available for a synonym are the same as the privileges for the synonym's base object. Granting a privilege on a synonym is equivalent to granting the privilege on the base object. If you grant a user a privilege on a synonym, the user can use either the synonym name or the base object name in the SQL statement that exercises the privilege.

Example I	To grant all privileges on the table BONUS to the user JONES with the GRANT OPTION, issue this statement:

GRANT ALL

ON bonus

TO jones

WITH GRANT OPTION

JONES can subsequently perform these operations:

•	exercise any privilege on the BONUS table

•	grant any privilege on the BONUS table to another user or role

Example II	To grant SELECT and UPDATE privileges on the view GOLF_HANDICAP to all users, issue this statement:

GRANT SELECT, UPDATE

ON golf_handicap

TO PUBLIC

All users can subsequently query and update the view of golf handicaps.

Example III	To grant SELECT privilege on the ESEQ sequence in the schema ELLY to the user BLAKE, issue this statement:

GRANT SELECT

ON elly.eseq

TO blake

BLAKE can subsequently generate the next value of the sequence with this statement:

SELECT elly.eseq.NEXTVAL

FROM DUAL

Example IV	To grant BLAKE the REFERENCES privilege on the EMPNO column and the UPDATE privilege on the EMPNO, SAL, and COMM columns of the EMP table in the schema SCOTT, issue this statement:

GRANT REFERENCES (empno), UPDATE (empno, sal, comm)

ON scott.emp

 	TO blake

BLAKE can subsequently update values of the EMPNO, SAL, and COMM columns. BLAKE can also define referential integrity constraints that refer to the EMPNO column. However, since the GRANT statement lists only these columns, BLAKE cannot perform operations on any of the other columns of the EMP table.

For example, BLAKE can create a table with a constraint:

CREATE TABLE dependent

 (dependno   NUMBER,

  dependname VARCHAR2(10),

  employee   NUMBER

             CONSTRAINT in_emp REFERENCES scott.emp(empno) )

The constraint IN_EMP ensures that all dependents in the DEPENDENT table correspond to an employee in the EMP table in the schema SCOTT.

Related Topics

GRANT (System Privileges and Roles) and REVOKE (Object Privileges) commands.

________________________________________

INSERT

Purpose

To add rows to a table or to a view's base table.

Prerequisites

For you to insert rows into a table, the table must be in your own schema or you must have INSERT privilege on the table.

For you to insert rows into the base table of a view, the owner of the schema containing the view must have INSERT privilege on the base table. Also, if the view is in a schema other than your own, you must have INSERT privilege on the view.

The INSERT ANY TABLE system privilege also allows you to insert rows into any table or any view's base table.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of the table or view:

•	If the creation label of the table or view is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the creation label of the table or view is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the creation label of your table or view is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the table or view. If you omit schema, ORACLE assumes the table or view is in your own schema.

table view	is the name of the table into which rows are to be inserted. If you specify view, ORACLE inserts rows into the view's base table.

dblink	is a complete or partial name of a database link to a remote database where the table or view is located. For information on referring to database links, see the section "Referring to Objects  on page 2 - 13. You can only insert rows into a remote table or view if you are using ORACLE with the distributed option.

If you omit dblink, ORACLE assumes that the table or view is on the local database.

column	is a column of the table or view. In the inserted row, each column in this list is assigned a value from the VALUES clause or the subquery.

If you omit one of the table's columns from this list, the column's value for the inserted row is the column's default value as specified when the table was created. If you omit the column list altogether, the VALUES clause or query must specify values for all columns in the table.

VALUES	specifies a row of values to be inserted into the table or view. See the syntax description of expr on page NO TAG. You must specify a value in the VALUES clause for each column in the column list.

subquery	is a SELECT statement that returns rows that are inserted into the table. The select list of this subquery must have the same number of columns as the column list of the INSERT statement. For the syntax description of subquery, see page 8 - 362.

Usage Notes

An INSERT statement with a VALUES clause adds a single row to the table. This row contains the values specified in the VALUES clause.

An INSERT statement with a subquery instead of a VALUES clause adds to the table all rows returned by the subquery. ORACLE processes the subquery and inserts each returned row into the table. If the subquery selects no rows, ORACLE inserts no rows into the table. The subquery can refer to any table, view, or snapshot, including the target table of the INSERT statement.

The number of columns in the column list of the INSERT statement must be the same as the number of values in the VALUES clause or the number of columns selected by the subquery. If you omit the column list, then the VALUES clause or the subquery must provide values for every column in the table. If you are using Trusted ORACLE in DBMS MAC mode and you omit a value for the ROWLABEL column, the new row is automatically labeled with your DBMS label.

ORACLE assigns values to fields in new rows based on the internal position of the columns in the table and the order of the values in the VALUES clause or in the select list of the query. You can determine the position of each column in the table by examining the data dictionary. For information on the data dictionary views containing this information, see Appendix D "Data  of the ORACLE7 Server .

If you omit any columns from the column list, ORACLE assigns them their default values as specified when the table was created. For more information on the default column values, see the CREATE TABLE command earlier in this chapter. If any of these columns has a NOT NULL constraint, then ORACLE returns an error indicating that the constraint has been violated and rolls back the INSERT statement.

Issuing an INSERT statement against a table fires any INSERT triggers defined on the table.

Inserting Into Views

If a view was created using the WITH CHECK OPTION, then you can only insert rows into the view that satisfy the view's defining query.

You cannot insert rows into a view if the view's defining query contains one of these constructs:

•	join

•	set operator

•	GROUP BY clause

•	group function

•	DISTINCT operator

Example I	This statement inserts a row into the DEPT table:

INSERT INTO dept

VALUES (50, 'PRODUCTION', 'SAN FRANCISCO')

Example II	This statement inserts a row with six columns into the EMP table. One of these columns is assigned NULL and another is assigned a number in scientific notation:

INSERT INTO emp (empno, ename, job, sal, comm, deptno)

VALUES (7890, 'JINKS', 'CLERK', 1.2E3, NULL, 40)

Example III	This statement copies managers and presidents or employees whose commission exceeds 25% of their salary into the BONUS table:

INSERT INTO bonus

SELECT ename, job, sal, comm

FROM emp

WHERE comm > 0.25 * sal

   OR job IN ('PRESIDENT', 'MANAGER')

Example IV	This statement inserts a row into the ACCOUNTS table owned by the user SCOTT on the database accessible by the database link SALES:

INSERT INTO scott.accounts@sales (acc_no, acc_name) 	VALUES (5001, 'BOWER')

Assuming that the ACCOUNTS table has a BALANCE column, the newly inserted row is assigned the default value for this column because this INSERT statement does not specify a BALANCE value.

Example V	This statement inserts a new row containing the next value of the employee sequence into the EMP table:

INSERT INTO emp

VALUES	(empseq.nextval, 'LEWIS', 'CLERK',

 7902, SYSDATE, 1200, NULL, 20)

Related Topics

DELETE and UPDATE commands.

________________________________________

INSERT (Embedded SQL)

Purpose

To add rows to a table or to a view's base table.

Prerequisites

For you to insert rows into a table, the table must be in your own schema or you must have INSERT privilege on the table.

For you to insert rows into the base table of a view, the owner of the schema containing the view must have INSERT privilege on the base table. Also, if the view is in a schema other than your own, you must have INSERT privilege on the view.

The INSERT ANY TABLE system privilege also allows you to insert rows into any table or any view's base table.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of the table or view:

•	If the creation label of the table or view is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the creation label of the table or view is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the creation label of your table or view is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

AT	identifies the database on which the INSERT statement is executed. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name

If you omit this clause, the INSERT statement is executed on your default database.

FOR :host_integer	limits the number of times the statement is executed if the VALUES clause contains array host variables. If you omit this clause, ORACLE executes the statement once for each component in the smallest array.

schema	is the schema containing the table or view. If you omit schema, ORACLE assumes the table or view is in your own schema.

table view	is the name of the table into which rows are to be inserted. If you specify view, ORACLE inserts rows into the view's base table.

dblink	is a complete or partial name of a database link to a remote database where the table or view is located. For information on referring to database links, see the section "Referring to Objects  on page 2 - 13. You can only insert rows into a remote table or view if you are using ORACLE with the distributed option.

If you omit dblink, ORACLE assumes that the table or view is on the local database.

column	is a column of the table or view. In the inserted row, each column in this list is assigned a value from the VALUES clause or the query.

If you omit one of the table's columns from this list, the column's value for the inserted row is the column's default value as specified when the table was created. If you omit the column list altogether, the VALUES clause or query must specify values for all columns in the table.

VALUES	specifies a row of values to be inserted into the table or view. See the syntax description of expr on page NO TAG. Note that the expressions can be host variables with optional indicator variables. You must specify an expression in the VALUES clause for each column in the column list.

query	is a SELECT statement that returns rows that are inserted into the table. The select list of this query must have the same number of columns as the column list of the INSERT statement. See the syntax description of query on page 8 - 357.

Usage Notes

Any host variables that appear in the WHERE clause must be eitherall scalars or all arrays. If they are scalars, ORACLE executesthe INSERT statement once. If they are arrays, ORACLE executes the INSERT statement once for each set of array components, inserting one row each time.

Array host variables in the WHERE clause can have different sizes. In this case, the number of times ORACLE executes the statement is determined by the smaller of these values:

•	size of the smallest array

•	the value of the :host_integer in the optional FOR clause.

For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example I	This example illustrates the use of the embedded SQL INSERT command:

EXEC SQL INSERT INTO emp (ename, empno, sal)

        VALUES (:ename, :empno, :sal);

Example II	This example shows an embedded SQL INSERT command with a subquery:

EXEC SQL INSERT INTO new_emp (ename, empno, sal)

SELECT ename, empno, sal FROM emp

 	WHERE deptno = :deptno;

Related Topics

DECLARE DATABASE and INSERT commands.

________________________________________

LOCK TABLE

Purpose

To lock one or more tables in a specified mode. This lock manually overrides automatic locking and permits or denies access to a table or view by other users for the duration of your operation.

Prerequisites

The table or view must be in your own schema or you must have LOCK ANY TABLE system privilege or you must have any object privilege on the table or view.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of the table or view or you must have READUP system privilege.

Syntax

Keywords and Parameters

schema	is the schema containing the table or view. If you omit schema, ORACLE assumes the table or view is in your own schema.

table view	is the name of the table to be locked. If you specify view, ORACLE locks the view's base tables.

dblink	is a database link to a remote ORACLE7 database where the table or view is located. For information on specifying database links, see the section "Referring to Objects in Remote  on page 2 - 13. You can only lock tables and views on a remote database if you are using ORACLE with the distributed option. All tables locked by a LOCK TABLE statement must be on the same database.

If you omit dblink, ORACLE assumes the table or view is on the local database.

lockmode	is one of these:

•	ROW SHARE

•	ROW EXCLUSIVE

•	SHARE UPDATE

•	SHARE

•	SHARE ROW EXCLUSIVE

•	EXCLUSIVE

NOWAIT	specifies that ORACLE returns control to you immediately if the specified table is already locked by another user. In this case, ORACLE returns a message indicating that the table is already locked by another user.

If you omit this clause, ORACLE waits until the table is available, locks it, and returns control to you.

Usage Notes

 Exclusive locks allow querieson the locked table but prohibit any other activity on it.

Share locks allow concurrent queries but prohibit updates to the locked table.

Row Share locks allow concurrent access to the locked table. They prohibit users from locking the entire table for exclusive access. ROW SHARE is synonymous with SHARE UPDATE.

Row Exclusive locks are the same as ROW SHARE locks, but also prohibit locking in SHARE mode. Row Exclusive locks are automatically obtained when updating, inserting, or deleting.

Share Row Exclusive locks are used to look at a whole table and to allow others to look at rows in the table but to prohibit others from locking the table in SHARE mode or updating rows.

Share Update locks are synonymous with ROW SHARE and included for compatibility with earlier versions of the ORACLE RDBMS.

Some forms of locks can be placed on the same table at the same time, other locks only allow one lock per table. For example, multiple users can place SHARE locks on the same table at the same time, but only one user can place an EXCLUSIVE lock on a table at a time. For a complete description of the interaction of lock modes, see Chapter 9 "Data Concurrency" of the ORACLE7 Server Concepts Manual.

When you lock a table, you choose how other users can access it. A locked table remains locked until you either commit your transaction or roll it back entirely or to a savepoint before you locked the table.

A lock never prevents other users from querying the table. A query never places a lock on a table. Readers never block writers and writers never block readers.

Example I	This statement locks the EMP table in exclusive mode, but does not wait if another user already has locked the table:

LOCK TABLE emp

IN EXCLUSIVE MODE

NOWAIT

Example II	This statement locks the remote ACCOUNTS table that is accessible through the database link BOSTON:

LOCK TABLE accounts@boston

IN SHARE MODE

Related Topics

DELETE, INSERT, UPDATE, COMMIT, ROLLBACK, and SAVEPOINT commands.

________________________________________

NOAUDIT (SQL Statements)

Purpose

To stop auditing chosen by the AUDIT command (SQL Statements). To stop auditing chosen by the AUDIT command (Schema Objects), use the NOAUDIT command (Schema Objects) described in the next section of this chapter.

Prerequisites

You must have AUDIT SYSTEM system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the label at which the auditing option was set or you must satisfy one of these criteria:

•	If the auditing option was set at a label higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the auditing option was set at a label lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the auditing option was set at a label noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

statement_opt	is a statement option for which auditing is stopped. For a list of the statement options and the SQL statements they audit, see Table 4 - 7 beginning on page 4 - 98 and Table 4 - 8 on page 4 - 100.

system_priv	is a system privilege for which auditing is stopped. For a list of the system privileges and the statements they authorize, see Table 4 - 7 on page 4 - 98.

BY	stops auditing only for SQL statements issued by specified users in their subsequent sessions. If you omit this clause, ORACLE stops auditing for all users' statements.

WHENEVER SUCCESSFUL	stops auditing only for SQL statements that complete successfully.

NOT	stops auditing only for statements that result in ORACLE errors.

If you omit the WHENEVER clause entirely, ORACLE stops auditing for all statements, regardless of success or failure.

Usage Notes

A NOAUDIT statement (SQL Statements) reverses the effect of a previous AUDIT statement (SQL Statements). Note that the NOAUDIT statementmust have the same syntax as the previous AUDIT statement. For information on auditing specific SQL commands, see the AUDIT command (SQL Statements) earlier in this chapter.

Example I	If you have chosen auditing for every SQL statement that creates or drops a role, you can stop auditing of such statements by issuing this statement:

NOAUDIT ROLE

Example II	If you have chosen auditing for any statement that queries or updates any table issued by the users SCOTT and BLAKE, you can stop auditing for SCOTT's queries by issuing this statement:

NOAUDIT SELECT TABLE

BY scott

Since this statement only stops auditing SCOTT's queries, ORACLE continues to audit BLAKE's queries and updates and SCOTT's updates.

Example III	To stop auditing on all statements that are authorized by DELETE ANY TABLE system privileges chosen for auditing, issue this statement:

NOAUDIT ALL

Related Topics

AUDIT (SQL Statements) and NOAUDIT (Schema Objects) commands.

________________________________________

NOAUDIT (Schema Objects)

Purpose

To stop auditing chosen by the AUDIT command (Schema Objects). To stop auditing chosen by the AUDIT command (SQL Statements), use the NOAUDIT command (SQL Statements) described in the previous section of this chapter.

Prerequisites

The object on which you stop auditing must be in your own schema or you must have AUDIT ANY system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the label at which the auditing option was set or you must satisfy one of these criteria:

•	If the auditing option was set at a label higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the auditing option was set at a label lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the auditing option was set at a label noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

object_opt	stops auditing for particular operations on the object. For a list of these options, see Table 4 - 9 on page 4 - 104.

ON	identifies the object on which auditing is stopped. If you do not qualify object with schema, ORACLE assumes the object is in your own schema.

WHENEVER SUCCESSFUL	stops auditing only for SQL statements that complete successfully.

NOT	option stops auditing only for statements that result in ORACLE errors.

If you omit the WHENEVER clause entirely, ORACLE stops auditing for all statements, regardless of success or failure.

Usage Notes

For information on auditing specific schema objects, see the AUDIT command (Schema Objects) earlier in this chapter.

Example	If you have chosen auditing for every SQL statement that queries the EMP table in the schema SCOTT, you can stop auditing for such queries by issuing this statement:

NOAUDIT SELECT

ON scott.emp

You can stop auditing for such queries that complete successfully by issuing this statement:

NOAUDIT SELECT

ON scott.emp

 	WHENEVER SUCCESSFUL

Since you only stopped auditing for successful queries, ORACLE continues to audit queries resulting in ORACLE errors.

Related Topics

AUDIT (Schema Objects) and NOAUDIT (SQL Statements) commands.

________________________________________

OPEN (Embedded SQL)

Purpose

To open a cursor, evaluating the associated query and substituting the host variable names supplied by the USING clause into the WHERE clause of the query.

Prerequisites

You must declare the cursor with a DECLARE CURSORembedded SQL statement before opening it.

Syntax

Keywords and Parameters

cursor	is the cursor to be opened.

USING 	specifies the host variables to be substituted into the WHERE clause of the associated query.

:host_variable 	specifies a host variable with an optional indicator variable to be substituted into the statement associated with the cursor.

DESCRIPTOR	specifies a descriptor that describes the host variables to be substituted into the WHERE clause of the associated query. The descriptor must be initialized in a previous DESCRIBE statement.

The substitution is based on position. The host variable names specified in this statement can be different from the variable names in the associated query.

Usage Notes

The OPEN command defines the active set of rows andinitializes the cursor just before the first row of the active set. Thevalues of the host variables at the time of the OPEN are substituted in the statement. This command does not actually retrieve rows;  rows are retrieved by the FETCH command.

Once you have opened a cursor, its input host variables are not reexamined until you re-open the cursor. To change any input host variables and therefore the active set, you must re-open the cursor.

All cursors in a program are in a closed state when the program is initiated or when they have been explicitly closed using the CLOSE command.

You can re-opened a cursor without first closing it. For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example	This example illustrates the use of the OPEN command in a Pro*C embedded SQL program:

EXEC SQL DECLARE emp_cursor CURSOR FOR

SELECT ename, empno, job, sal

FROM emp

WHERE deptno = :deptno;

EXEC SQL OPEN emp_cursor;

Related Topics

PREPARE, DECLARE CURSOR, FETCH, and CLOSE commands.

________________________________________

PREPARE (Embedded SQL)

Purpose

To parse a SQL statement or PL/SQL block specified by a host variable and associate it with an identifier.

Prerequisites

None.

Syntax

Keywords and Parameters

statement_name block_name	is the identifier to be associated with the prepared SQL statement or PL/SQL block. If this name has been previously assigned to another statement or block, the prior assignment is superseded.

:host_string	is a host variable whose value is the text of a SQL statement or PL/SQL block to be prepared.

'text'	is a string literal containing a SQL statement or PL/SQL block to be prepared.

Usage Notes

Any variables that appear in the :host_string or 'text'are placeholders. The actual host variable names are assigned inthe USING clause of the OPEN command (input host variables) or in the INTO clause of the FETCH command (output host variables).

A SQL statement is prepared only once, but can be executed any number of times.

Example	This example illustrates the use of a PREPARE statement in a Pro*C embedded SQL program:

EXEC SQL PREPARE my_statement FROM :my_string;

EXEC SQL EXECUTE my_statement

Related Topics

DECLARE CURSOR, OPEN, FETCH, and CLOSE commands.

________________________________________

RECOVER clause

Purpose

To perform media recovery.

Prerequisites

The RECOVER clause must appear in an ALTER DATABASE statement. You must have the privileges necessary to issue this statement. For information on these privileges, see the ALTER DATABASE command earlier in this chapter.

You must also have the OSDBA role enabled. You cannot be connected to ORACLE through the multi-threaded server architecture. Your instance must have the database mounted in exclusive mode.

Syntax

Keywords and Parameters

AUTOMATIC	automatically generates the names of the redo log files to apply during media recovery. If you omit this option, ORACLE prompts you for names of redo log files and you must specify them by issuing ALTER DATABASE statements with the LOGFILE parameter.

FROM	specifies the location from which the archived redo log file group is read. The value of this parameter must be a fully-specified file location following the conventions of your operating system. If you omit this parameter, ORACLE assumes the archived redo log file group is in the location specified by the initialization parameter LOG_ARCHIVE_DEST.

DATABASE	recovers the entire database. This is the default option. You can only use this option when the database is closed.

UNTIL CANCEL	performs cancel-based recovery. This option recovers the database until you cancel recovery by issuing an ALTER DATABASE statement with a RECOVER clause containing the CANCEL option.

UNTIL TIME	performs time-based recovery. This parameter recovers the database to the time specified by the date. The date must be a character literal in the format 'YYYY-MM-DD:HH24:MI:SS'.

UNTIL CHANGE	performs change-based recovery. This parameter recovers the database to a transaction consistent state immediately prior to the system change number (SCN) specified by integer.

USING BACKUP CONTROLFILE	specifies that a backup control file is being used instead of the current control file.

TABLESPACE	recovers only the specified tablespaces. You can use this option if the database is open or closed, provided the tablespaces to be recovered are not being used.

DATAFILE	recovers the specified data files. You can use this option when the database is open or closed, provided the data files to be recovered are not being used.

LOGFILE	continues media recovery by applying the specified redo log file.

CONTINUE	continues multi-instance recovery after it has been interrupted to disable a thread.

CONTINUE DEFAULT	continues recovery by applying the redo log file that ORACLE has automatically generated.

CANCEL	terminates cancel-based recovery.

Usage Notes

Oracle Corporation recommends that you use the SQL*DBA RECOVER command rather than the ALTER DATABASE command with the RECOVER clause toperform media recovery.

For most purposes, the RECOVER command is easier to use than the ALTER DATABASE command. For information on this command, see the ORACLE7 Server Utilities User's Guide.

For more information on media recovery, see Chapter 19 "Recovering a Database"  of the ORACLE7 Server Administrator's Guide.

You can use the ALTER DATABASE command with the RECOVER clause if you want to write your own specialized media recovery application using SQL.

Example I	This statement performs complete recovery of the entire database:

ALTER DATABASE

RECOVER AUTOMATIC DATABASE

ORACLE automatically generates the names of redo log files to apply and prompts you with them. This statement applies a suggested file:

ALTER DATABASE 	RECOVER CONTINUE DEFAULT

This statement explicitly names a redo log file for ORACLE to apply:

ALTER DATABASE

RECOVER LOGFILE 'diska:arch0006.arc'

Example II	This statement performs time-based recovery of the database:

ALTER DATABASE AUTOMATIC

RECOVER UNTIL TIME '1992-10-27:14:00:00'

ORACLE recovers the database until 2:00pm on October 27, 1992.

Example III	This statement performs cancel-based recovery:

ALTER DATABASE

RECOVER UNTIL CANCEL

ORACLE subsequently prompts you with the names of generated redo log files. You can terminate recovery with this statement:

ALTER DATABASE

RECOVER CANCEL

Example IV	This statement recovers the tablespace USER5:

ALTER DATABASE

RECOVER TABLESPACE user5

Related Topics

ALTER DATABASE command.

________________________________________

RENAME

Purpose

To rename a table, view, sequence, or private synonym.

Prerequisites

The object must be in your own schema.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the object's creation label or you must satisfy one of these criteria:

•	If the object's creation label is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the object's creation label is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the object's creation label and your DBMS label are noncomparable, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Oracle Corporation recommends that you use the SQL*DBA RECOVER command rather than the ALTER DATABASE command with the RECOVER clause toperform media recovery.

Syntax

Keywords and Parameters

old	is the current name of an existing table, view, sequence, or private synonym.

new 	is the new name to be given to the existing object.

Usage Notes

This command changes the name of a table, view, sequence, or private synonym for a table, view, or sequence. The new name must not alreadybe used by another schema object in the same namespace and must follow the rules for naming schema objects defined in the section "Object Naming Rules" on page 2 - 3.

Integrity constraints, indexes, and grants on the old object are automatically transferred to the new object. ORACLE invalidates all objects that depend on the renamed object, such as views, synonyms, and stored procedures and functions that refer to a renamed table.

You cannot use this command to rename public synonyms. To rename a public synonym, you must first drop it with the DROP SYNONYM command and then create another public synonym with the new name using the CREATE SYNONYM command.

You cannot use this command to rename columns. You can rename a column using the CREATE TABLE command with the AS clause. This example recreates the table STATIC, renaming a column from OLDNAME to NEWNAME:

CREATE TABLE temporary (newname, col2, col3)

AS SELECT oldname, col2, col3 FROM static

DROP TABLE static

RENAME temporary TO static

Example	To change the name of table DEPT to EMP_DEPT:

RENAME dept TO emp_dept

Related Topics

CREATE SEQUENCE, CREATE SYNONYM, CREATE TABLE, and CREATE VIEW commands.

________________________________________

REVOKE (System Privileges and Roles)

Purpose

To revoke system privileges and roles from users and roles. To revoke object privileges from users and roles, use the REVOKE command (Object Privileges) described in the next section of this chapter.

Prerequisites

You must have been granted the system privilege or role with the ADMIN OPTION. Also, you can revoke any role if you have the GRANT ANY ROLE system privilege.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the label at which the system privilege or role was granted or you must satisfy one of these criteria:

•	If the label at which the system privilege or role was granted is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the label at which the system privilege or role was granted is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the label at which the system privilege or role is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Oracle Corporation recommends that you use the SQL*DBA RECOVER command rather than the ALTER DATABASE command with the RECOVER clause toperform media recovery.

Syntax

Keywords and Parameters

system_priv	is a system privilege to be revoked. For a list of the system privileges, see Table 6 - 1 on page 7 - 289.

role 	is a role to be revoked. For a list of the roles predefined by ORACLE, see Table 6 - 2 on page 7 - 290.

FROM	identifies users and roles from which the system privileges or roles are revoked.

PUBLIC	revokes the system privilege or role from all users.

Usage Notes

You can use this form of the REVOKE command to revoke both systemprivileges and roles from users, roles, and PUBLIC:

If you revoke a privilege from a user:      ORACLE removes the privilege from the user's privilege domain. Effective immediately, the user cannot exercise the privilege.

If you revoke a privilege from a role:      ORACLE removes the privilege from the role's privilege domain. Effective immediately, users with the role enabled cannot exercise the privilege. Also, other users who have been granted the role and subsequently enable the role cannot exercise the privilege.

If you revoke a privilege from PUBLIC:      ORACLE removes the privilege from the privilege domain of each user who has been granted the privilege through PUBLIC. Effective immediately, such users can no longer exercise the privilege. Note that the privilege is not revoked from users who have been granted the privilege directly or through roles.

If you revoke a role from a user:      ORACLE makes the role unavailable to the user. If the role is currently enabled for the user, the user can continue to exercise the privileges in the role's privilege domain as long as it remains enabled. However, the user cannot subsequently enable the role.

If you revoke a role from another role:      ORACLE removes the revoked role's privilege domain from the revokee role's privilege domain. Users who have been granted and have enabled the revokee role can continue to exercise the privileges in the revoked role's privilege domain as long as the revokee role remains enabled. However, other users who have been granted the revokee role and subsequently enable it cannot exercise the privileges in the privilege domain of the revoked role.

If you revoke a role from PUBLIC:      ORACLE makes the role unavailable to all users who have been granted the role through PUBLIC. Any user who has enabled the role can continue to exercise the privileges in its privilege domain as long as it remains enabled. However, users cannot subsequently enable the role. Note that the role is not revoked from users who have been granted the privilege directly or through other roles.

The REVOKE command can only revoke privileges and roles that have been granted directly with a GRANT statement. The REVOKE command cannot perform these operations:

•	revoke privileges or roles not granted to the revokee

•	revoke roles granted through the operating system

•	revoke privileges or roles granted to the revokee through roles

A system privilege or role cannot appear more than once in the list of privileges and roles to be revoked. A user, a role, or PUBLIC cannot appear more than once in the FROM clause.

Example I	This statement revokes DROP ANY TABLE system privilege from the users BILL and MARY:

REVOKE DROP ANY TABLE

FROM bill, mary

BILL and MARY can no longer drop tables in schemas other than their own.

Example II	This statement revokes the role CONTROLLER from the user HANSON:

REVOKE controller

FROM hanson

HANSON can no longer enable the CONTROLLER role.

Example III	This statement revokes the CREATE TABLESPACE system privilege from the CONTROLLER role:

REVOKE CREATE TABLESPACE

FROM controller

Enabling the CONTROLLER role no longer allows users to create tablespaces.

Example IV	To revoke the role VP from the role CEO, issue this statement:

REVOKE vp

 	FROM ceo

VP is no longer granted to CEO.

Related Topics

GRANT (System Privileges and Roles) and REVOKE (Object Privileges) commands.

________________________________________

REVOKE (Object Privileges)

Purpose

To revoke object privileges for a particular object from users and roles. To revoke system privileges or roles, use the REVOKE command (System Privileges and Roles) described in the previous section of this Syntax  chapter.

Prerequisites

You must have previously granted the object privileges to each user and role.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the label at which you granted the object privilege or you must satisfy one of these criteria:

•	If the label at which you granted the object privilege is higher than your DBMS label, you must have READUP and WRITEUP system privileges.

•	If the label at which you granted the object privilege is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the label at which you granted the object privilege is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

object_priv	is an object privilege to be revoked. You can substitute any of these values:

•	ALTER

•	DELETE

•	EXECUTE

•	INDEX

•	INSERT

•	REFERENCES

•	SELECT

•	UPDATE

ALL PRIVILEGES	revokes all object privileges that you have granted to the revokee.

ON	identifies the object on which the object privileges are revoked. This object can be one of these types:

•	table

•	view

•	sequence

•	procedure, stored function, or package

•	snapshot

•	synonym for a table, view, sequence, procedure, stored function, package, or snapshot

If you do not qualify object with schema, ORACLE assumes the object is in your own schema.

FROM	identifies users and roles from which the object privileges are revoked.

PUBLIC	revokes object privileges from all users.

CASCADE CONSTRAINTS	drops any referential integrity constraints that the revokee has defined using REFERENCES privilege that you are now revoking. You must specify this option along with the REFERENCES privilege or the ALL PRIVILEGES option if the revokee has exercised the REFERENCES privilege to define a referential integrity constraint.

Usage Notes

 You can use this form of the REVOKE command to revoke object privileges from both users and roles:

If you revoke a privilege from a user:      ORACLE removes the privilege from the user's privilege domain. Effective immediately, the user cannot exercise the privilege.

If you revoke a privilege from a role:      ORACLE removes the privilege from the role's privilege domain. Effective immediately, users with the role enabled cannot exercise the privilege. Other users who have been granted the role cannot exercise the privilege after enabling the role.

If you revoke a privilege from PUBLIC:      ORACLE removes the privilege from the privilege domain of each user who has been granted the privilege through PUBLIC. Effective immediately, all such users are restricted from exercising the privilege. Note that the privilege is not revoked from users who have been granted the privilege directly or through roles.

You can only use the REVOKE command to revoke object privileges that you previously granted directly to the revokee. You cannot use the REVOKE command to perform these operations:

•	revoke object privileges that you did not grant to the revokee

•	revoke privileges granted through the operating system

•	revoke privileges granted to roles granted to the revokee

A privilege cannot appear more than once in the list of privileges to be revoked. A user, a role, or PUBLIC cannot appear more than once in the FROM clause.

Object Privileges

Each object privilege authorizes some operation on an object. By revoking an object privilege, you prevent the revokee from performing that operation. For a summary of the object privileges for each type of object, see Table 6 - 3 on page 7 - 294.

Revoking Multiple Identical Grants

Multiple users may grant the same object privilege to the same user, role, or PUBLIC. To remove the privilege from the grantee's privilege domain, all grantors must revoke the privilege. If even one grantor does not revoke the privilege, the grantee can still exercise the privilege by virtue of that grant.

Cascading Revokes

Revoking an object privilege that a user has either granted or exercised to define an object or a referential integrity constraint has cascading effects:

•	If you revoke an object privilege from a user who has granted the privilege to other users or roles, ORACLE also revokes the privilege from the grantees.

•	If you revoke an object privilege from a user whose schema contains a procedure, function, or package that contains SQL statements that exercise the privilege, the procedure, function, or package can no longer be executed.

•	If you revoke an object privilege on an object from a user whose schema contains a view on that object, ORACLE invalidates the view.

•	If you revoke REFERENCES privilege from a user who has exercised the privilege to define referential integrity constraints, you must specify the CASCADE CONSTRAINTS option. ORACLE then revokes the privilege and drops the constraints.

Example I	You can grant DELETE, INSERT, SELECT, and UPDATE privileges on the table BONUS to the user PEDRO with this statement:

GRANT ALL

ON bonus

TO pedro

To revoke DELETE privilege on BONUS from PEDRO, issue this statement:

REVOKE DELETE

ON bonus

FROM pedro

To revoke the remaining privileges on BONUS that you granted to PEDRO, issue this statement:

REVOKE ALL

ON bonus

FROM pedro

Example II	You can grant SELECT and UPDATE privileges on the view REPORTS to all users by granting the privileges to the role PUBLIC:

GRANT SELECT, UPDATE

ON reports

TO public

This statement revokes UPDATE privilege on REPORTS from all users:

REVOKE UPDATE

ON reports

FROM public

Users can no longer update the REPORTS view, although users can still query it. However, if you have also granted UPDATE privilege on REPORTS to any users (either directly or through roles), these users retain the privilege.

Example III	You can grant the user BLAKE SELECT privilege on the ESEQ sequence in the schema ELLY with this statement:

GRANT SELECT

ON elly.eseq

 	TO blake

To revoke SELECT privilege on ESEQ from BLAKE, issue this statement:

REVOKE SELECT

ON elly.eseq

 	FROM blake

However, if the user ELLY has also granted SELECT privilege on ESEQ to BLAKE, BLAKE can still use ESEQ by virtue of ELLY's grant.

Example IV	You can grant BLAKE the privileges REFERENCES and UPDATE on the EMP table in the schema SCOTT with this statement:

GRANT REFERENCES, UPDATE

ON scott.emp

 	TO blake

BLAKE can exercise the REFERENCES privilege to define a constraint in his own DEPENDENT table that refers to the EMP table in the schema SCOTT:

CREATE TABLE dependent

(dependno    NUMBER,

 dependname  VARCHAR2(10),

 employee    NUMBER

             CONSTRAINT in_emp REFERENCES scott.emp(ename) )

You can revoke REFERENCES privilege on SCOTT.EMP from BLAKE, by issuing this statement that contains the CASCADE CONSTRAINTS option:

REVOKE REFERENCES

ON scott.emp

FROM blake

CASCADE CONSTRAINTS

Revoking BLAKE's REFERENCES privilege on SCOTT.EMP causes ORACLE to drop the IN_EMP constraint because BLAKE required the privilege to define the constraint.

However, if BLAKE has also been granted REFERENCES privilege on SCOTT.EMP by a user other than you, ORACLE does not drop the constraint. BLAKE still has the privilege necessary for the constraint by virtue of the other user's grant.

Related Topics

GRANT (Object Privileges) and REVOKE (System Privileges and Roles) commands.

________________________________________

ROLLBACK

Purpose

To undo work done in the current transaction.

You can also use this command to manually undo the work done by an in-doubt distributed transaction.

Prerequisites

To roll back your current transaction, no privileges are necessary.

To manually roll back an in-doubt distributed transaction that you originally committed, you must have FORCE TRANSACTION system privilege. To manually roll back an in-doubt distributed transaction originally committed by another user, you must have FORCE ANY TRANSACTION system privilege.

Syntax

Keywords and Parameters

WORK	is optional and is provided for ANSI compatibility.

TO 	rolls back the current transaction to the specified savepoint. If you omit this clause, the ROLLBACK statement rolls back the entire transaction.

FORCE	manually rolls back an in-doubt distributed transaction. The transaction is identified by the 'text' containing its local or global transaction ID. To find the IDs of such transactions, query the data dictionary view DBA_2PC_PENDING.

ROLLBACK statements with the FORCE clause are not supported in PL/SQL.

Usage Notes

A transaction (or a logical unit of work) is a sequence of SQL statements that ORACLE treats as a single unit. A transaction begins with thefirst executable SQL statement after a COMMIT, ROLLBACK or connection to the database. A transaction ends with a COMMIT statement, a ROLLBACK statement, or disconnection (intentional or unintentional) from the database. Note that ORACLE issues an implicit COMMIT statement before and after processing any Data Definition Language statement.

Using the ROLLBACK command without the TO SAVEPOINT clause performs these operations:

•	ends the transaction

•	undoes all changes in the current transaction

•	erases all savepoints in the transaction

•	releases the transaction's locks

Using the ROLLBACK command with the TO SAVEPOINT clause performs these operations:

•	rolls back just the portion of the transaction after the savepoint.

•	loses all savepoints created after that savepoint. Note that the named savepoint is retained, so you can roll back to the same savepoint multiple times. Prior savepoints are also retained.

•	releases all table and row locks acquired since the savepoint. Note that other transactions that have requested access to rows locked after the savepoint must continue to wait until the transaction is committed or rolled back. Other transactions that have not already requested the rows can request and access the rows immediately.

Oracle Corporation recommends that you explicitly end transactions in application programs using either a COMMIT or ROLLBACK statement. If you do not explicitly commit the transaction and the program terminates abnormally, ORACLE rolls back the last uncommitted transaction.

Example I	This statement rolls back your entire current transaction:

ROLLBACK

Example II	This statement rolls back your current transaction to savepoint SP5:

ROLLBACK TO SAVEPOINT sp5

 Distributed Transactions

ORACLE with the distributed option allows you to perform distributed transactions, or transactions that modify data on multiple databases. To commit or roll back a distributed transaction, you need only issue a COMMIT or ROLLBACK statement as you would any other transaction.

In the event of a network failure during the commit process for a distributed transaction, the state of the transaction may be unknown, or in-doubt. After consultation with the administrators of the other databases involved in the transaction, you may decide to manually commit or roll back the transaction on your local database. You can manually roll back the transaction on your local database by issuing a ROLLBACK statement with the FORCE clause.

For more information on when to roll back in-doubt transactions, see Chapter 15 "Managing Distributed Databases" of the ORACLE7 Server Administrator's Guide.

You cannot manually roll back an in-doubt transaction to a savepoint.

A ROLLBACK statement with a FORCE clause only rolls back the specified transaction. Such a statement does not affect your current transaction.

Example III	This statement manually rolls back an in-doubt distributed transaction:

ROLLBACK WORK

FORCE '25.32.87'

Related Topics

COMMIT, SET TRANSACTION, and SAVEPOINT commands.


CHAPTER 8. COMMANDS - ROLLBACK TO WHENEVER

________________________________________

ROLLBACK (Embedded SQL)

Purpose

To end the current transaction, discard all changes in the current transaction, and release all locks and optionally release resources and disconnect from the database.

Prerequisites

To roll back your current transaction, no privileges are necessary.

To manually roll back an in-doubt distributed transaction that you originally committed, you must have FORCE TRANSACTION system privilege. To manually roll back an in-doubt distributed transaction originally committed by another user, you must have FORCE ANY TRANSACTION system privilege.

Syntax

Keywords and Parameters

AT	identifies the database to which the ROLLBACK statement is issued. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, the statement is issued to your default database.

WORK	is optional and has no effect on ROLLBACK.

TO	rolls back the transaction to a previously declared savepoint.

RELEASE	releases all resources and disconnects you from the database.

FORCE 	manually rolls back an in-doubt distributed transaction. The transaction is identified by the 'text' containing its local or global transaction ID. To find the IDs of such transactions, query the data dictionary view DBA_2PC_PENDING.

Usage Notes

Always explicitly commit or rollbackthe last transaction in a program using the RELEASE option to disconnectfrom ORACLE.

ORACLE automatically rolls back your current transaction if the program terminates abnormally.

The ROLLBACK command has no effect on the contents of the host variables or on the control flow of the program.

Example	This example illustrates the use of the embedded SQL ROLLBACK command:

EXEC SQL ROLLBACK TO SAVEPOINT point4

Related Topics

COMMIT, DECLARE DATABASE, ROLLBACK, SAVEPOINT, and SET TRANSACTION commands.

________________________________________

SAVEPOINT

Purpose

To identify a point in a transaction to which you can later roll back.

Prerequisites

None.

Syntax

Keywords and Parameters

savepoint	is the name of the savepoint to be created.

Usage Notes

 Savepoints are used in conjunction with the ROLLBACK command to rollback portions of the current transaction.

Savepoints are useful in interactive programs, because you can create and name intermediate steps of a program. This allows you more control over longer, more complex programs. For example, you can use savepoints throughout a long complex series of updates, so that if you make an error, you need not resubmit every statement.

Savepoints are useful in application programs in a similar way. If a program contains several subprograms, you can create a savepoint before each subprogram begins. If a subprogram fails, it is easy to return the data to its state before the subprogram began and then re-execute the subprogram with revised parameters or perform a recovery action.

Savepoint names must be distinct within a given transaction. If you create a second savepoint with the same identifier as an earlier savepoint, the earlier savepoint is erased. After a savepoint has been created, you can either continue processing, commit your work, rollback the entire transaction, or rollback to the savepoint.

 Transaction

A transaction (or a logical unit of work) is a sequence of SQL statements that ORACLE treats as a single unit. A transaction begins with the first executable SQL statement after a COMMIT, ROLLBACK or connection to ORACLE. A transaction ends with a COMMIT statement, a ROLLBACK statement, or disconnection (intentional or unintentional) from ORACLE. ORACLE issues an implicit COMMIT before and after any Data Definition Language statement.

Example	To update BLAKE's and CLARK's salary, check that the total company salary does not exceed 20,000, then re-enter CLARK's salary, enter:

UPDATE emp

SET sal = 2000

WHERE ename = 'BLAKE'

SAVEPOINT blake_sal

UPDATE emp

SET sal = 1500

WHERE ename = 'CLARK'

SAVEPOINT clark_sal

SELECT SUM(sal) FROM emp

ROLLBACK TO SAVEPOINT blake_sal

UPDATE emp

SET sal = 1300

WHERE ename = 'CLARK'

COMMIT

Related Topics

COMMIT, ROLLBACK, and SET TRANSACTION commands.

________________________________________

SAVEPOINT (Embedded SQL)

Purpose

To identify a point in a transaction to which you can later roll back.

Prerequisites

None.

Syntax

Keywords and Parameters

AT	identifies the database on which the savepoint is created. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, the savepoint is created on your default database.

savepoint	is the name of the savepoint to be created.

Usage Notes

 For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Example	This example illustrates the use of the embedded SQL SAVEPOINT command:

EXEC SQL SAVEPOINT save3

Related Topics

COMMIT, ROLLBACK, and SAVEPOINT commands.

________________________________________

SELECT

Purpose

To retrieve data from one or more tables, views, or snapshots.

Prerequisites

For you to select data from a table or snapshot, the table or snapshot must be in your own schema or you must have SELECT privilege on the table or snapshot.

For you to select rows from the base tables of a view, the owner of the schema containing the view must have SELECT privilege on the base tables. Also, if the view is in a schema other than your own, you must have SELECT privilege on the view.

The SELECT ANY TABLE system privilege also allows you to select data from any table or any snapshot or any view's base table.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of each queried table, view, or snapshot or you must have READUP system privileges.

Syntax

Keywords and Parameters

DISTINCT	returns only one copy of each set of duplicate rows selected. Duplicate rows are those with matching values for each expression in the select list.

ALL	returns all rows selected, including all copies of duplicates.

The default is ALL.

*	selects all columns from all tables, views, or  snapshots, listed in the FROM clause.

table.* view.* snapshot.*	selects all columns from the specified table, view, or snapshot. You can use the schema qualifier to select from a table, view, or snapshot in a schema other than your own.

If you are using Trusted ORACLE, the * does not select the ROWLABEL column. To select this column, you must explicitly specify it in the select list.

expr	selects an expression, usually based on column values, from one of the tables, views, or snapshots in the FROM clause. See the syntax description of expr on page NO TAG. A column name in this list can only contain be qualified with schema if the table, view, or snapshot containing the column is qualified with schema in the FROM clause.

c_alias	provides a different name for the column expression and causes the alias to be used in the column heading. The AS keyword is optional. The alias effectively renames the select list item for the duration of the query. The alias can be used in the ORDER BY clause, but not other clauses in the query.

schema	is the schema containing the selected table, view, or snapshot. If you omit schema, ORACLE assumes the table, view, or snapshot is in your own schema.

table   view snapshot	is the name of a table, view, or snapshot from which data is selected.

dblink	is the complete or partial name for a database link to a remote database where the table, view, or snapshot is located. For more information on referring to database links, see the section "Referring to Objects in Remote Databases"  on page 2 - 13. Note that this database need not be an ORACLE7 database.

If you omit dblink, ORACLE assumes that the table, view, or snapshot is on the local database.

subquery	is a subquery from which data is selected. For the syntax of subquery, see page 8 - 362. ORACLE executes the subquery and then uses the resulting rows as a table in the FROM clause. The subquery cannot query a table that appears in the same FROM clause as the subquery.

t_alias	provides a different name for the table, view, or snapshot for the purpose of evaluating the query and is most often used in a correlated query. Other references to the table, view, or snapshot throughout the query must refer to the alias.

WHERE	restricts the rows selected to those for which the condition is TRUE. If you omit this clause, ORACLE returns all rows from the tables, views, or snapshots in the FROM clause. See the syntax description of condition on page NO TAG.

START WITH CONNECT BY	returns rows in a hierarchical order.

GROUP BY	groups the selected rows based on the value of expr for each row and returns a single row of summary information for each group.

HAVING	restricts the groups of rows returned to those groups for which the specified condition is TRUE. If you omit this clause, ORACLE returns summary rows for all groups.

See the syntax description of expr on page NO TAG and the syntax description of condition on page NO TAG.

UNION UNION ALL INTERSECT MINUS	combines the rows returned by two SELECT statement using a set operation.

ORDER BY	orders rows returned by the statement.

expr	orders rows based on their value for expr. The expression is based on columns in the select list or columns in the tables, views, or snapshots in the FROM clause.

position	orders rows based on their value for the expression in this position of the select list.

ASC DESC	specifies either ascending or descending order. ASC is the default.

FOR UPDATE	locks the selected rows.

NOWAIT	returns control to you if the SELECT statement attempts to lock a row that is locked by another user. If you omit this clause, ORACLE waits until the row is available and then returns the results of the SELECT statement.

Usage Notes

The list of expressions that appears after the SELECT keyword and before the FROM clause is called the select list. Eachexpr becomes the name of one column in the set of returned rows, and each table.* becomes a set of columns, one for each column in the table in the order they were defined when the table was created. The datatype and length of each expression is determined by the elements of the expression.

If two or more tables have some column names in common, you must qualify column names with names of tables.  Otherwise, fully qualified column names are optional, although it is always better to explicitly qualify table and column references. ORACLE often does less work with fully qualified table and column names.

You can use a column alias, c_alias, to label the preceding expression in the select list so that the column is displayed with a new heading. The alias effectively renames the select list item for the duration of the query. The alias can be used in the ORDER BY clause, but not other clauses in the query.

If you use the DISTINCT option to return only a single copy of duplicate rows, the total number of bytes in all select list expressions is limited to the size of a data block minus some overhead. This size is specified by the initialization parameter DB_BLOCK_SIZE.

You can use comments in a SELECT statement to pass instructions, or hints, to the ORACLE optimizer. The optimizer uses hints to choose an execution plan for the statement. For more information on hints, see Chapter 5  of the ORACLE7 Server Application Developer's Guide.

Example I	This statement selects rows from the employee table with the department number of 40:

SELECT *

FROM emp

WHERE deptno = 40

Example II	This statement selects the name, job, salary and department number of all employees except salesmen from department number 30:

SELECT ename, job, sal, deptno

FROM emp

WHERE NOT (job = 'SALESMAN' AND deptno = 30)

Example III	This statement selects from a subquery that appears in the FROM clause:

SELECT *

FROM (SELECT ename FROM emp WHERE deptno = 10)

 	WHERE job = 'CLERK'

Hierarchical Queries

If a table contains hierarchical data, you can select rows in a hierarchical order using these clauses:

START WITH	You can specify the root row(s) of the hierarchy using this clause.

CONNECT BY	You can specify the relationship between parent rows and child rows of the hierarchy using this clause.

WHERE	You can restrict the rows returned by the query without affecting other rows of the hierarchy using this clause.

ORACLE uses the information in these clauses to form the hierarchy by following these steps:

1.	ORACLE selects the root row(s) of the hierarchy. These are the rows that satisfy the condition of the START WITH clause.

2.	ORACLE selects the child rows of each root row. Each child row must satisfy the condition of the CONNECT BY clause with respect to one of the root rows.

3.	ORACLE selects successive generations of child rows. ORACLE first selects the children of the rows returned in step 2, and then the children of those children, and so on. ORACLE always selects children by evaluating the CONNECT BY condition with respect to a current parent row.

4.	If the query contains a WHERE clause, ORACLE removes all rows from the hierarchy that do not satisfy the condition of the WHERE clause. ORACLE evaluates this condition for each row individually, rather than removing all the children of a row that does not satisfy the condition.

5.	ORACLE returns the rows in the order shown in this diagram. In the diagram children appear below their parents.

SELECT statements performing hierarchical queries are subject to these restrictions:

•	A SELECT statement that performs a hierarchical query cannot also perform a join. A SELECT statement that performs a hierarchical query cannot select data from a view whose query performs a join.

•	If you use the ORDER BY clause in a hierarchical query, ORACLE orders rows by the ORDER BY clause, rather than in the order shown in step 5.

The following sections discuss the START WITH and CONNECT BY clauses.

 START WITH Clause

The START WITH clause identifies the row(s) to be used as the root(s) of a hierarchical query. This clause specifies a condition that the roots must satisfy. If you omit this clause, ORACLE uses all rows in the table as root rows. A START WITH condition can contain a subquery.

 CONNECT BY Clause

The CONNECT BY clause specifies the relationship between parent and child rows in a hierarchical query. This clause contains a condition that defines this relationship. This condition can be any condition as defined by the syntax description of condition on page NO TAG; however, some part of the condition must use the PRIOR operator to refer to the parent row. The part of the condition containing the PRIOR operator must have one of these forms:

PRIOR expr comparison_operator expr

expr comparison_operator PRIOR expr

To find the children of a parent row, ORACLE evaluates the PRIOR expression for the parent row and the other expression for each row in the table. Rows for which the condition is true are the children of the parent. The CONNECT BY clause can contain other conditions to further filter the rows selected by the query. The CONNECT BY clause cannot contain a subquery.

If the CONNECT BY clause results in a loop in the hierarchy, ORACLE returns an error. A loop occurs if one row is both the parent (or grandparent or direct ancestor) and a child (or a grandchild or a direct descendent) of another row.

Examples	This CONNECT BY clause defines a hierarchical relationship in which the EMPNO value of the parent row is equal to the MGR value of the child row:

CONNECT BY PRIOR empno = mgr

In this CONNECT BY clause, the PRIOR operator applies only to the EMPNO value. To evaluate this condition, ORACLE evaluates EMPNO values for the parent row and MGR, SAL, and COMM values for the child row:

CONNECT BY PRIOR empno = mgr AND sal > comm

To qualify as a child row, a row must have a MGR value equal to the EMPNO value of the parent row and it must have a SAL value greater than its COMM value.

 The LEVEL Pseudocolumn

SELECT statements that perform hierarchical queries can use the LEVEL pseudocolumn. LEVEL returns the value 1 for a root node, 2 for a child node of a root node, 3 for a grandchild, etc. For more information on LEVEL, see the section "Pseudocolumns" on page 2 - 37.

The number of levels returned by a hierarchical query may be limited by available user memory.

Example IV	This statement returns all employees in hierarchical order. The root row is defined to be the employee whose job is 'PRESIDENT'. The child rows of a parent row are defined to be those who have the employee number of the parent row as their manager number.

SELECT LPAD(' ',2*(LEVEL-1)) || ename org_chart, empno, mgr,

job

FROM emp

START WITH job = 'PRESIDENT'

CONNECT BY PRIOR empno = mgr

ORG_CHART          EMPNO        MGR JOB

------------- ---------- ---------- ---------

KING	 7839            PRESIDENT

  JONES	 7566       7839 MANAGER

    SCOTT	 7788       7566 ANALYST

  ADAMS	 7876       7788 CLERK

FORD	 7902       7566 ANALYST

  SMITH	 7369       7902 CLERK

BLAKE	 7698       7839 MANAGER

  ALLEN	 7499       7698 SALESMAN

  WARD	 7521       7698 SALESMAN

  MARTIN	 7654       7698 SALESMAN

  TURNER	 7844       7698 SALESMAN

  JAMES	 7900       7698 CLERK

CLARK	 7782       7839 MANAGER

  MILLER	 7934       7782 CLERK

This statement is similar to the previous one, except that it does not select employees with the job 'ANALYST'.

SELECT LPAD(' ',2*(LEVEL-1)) || ename org_chart, empno,

mgr, job

FROM emp

WHERE job != 'ANALYST'

START WITH job = 'PRESIDENT'

CONNECT BY PRIOR empno = mgr

ORG_CHART          EMPNO        MGR JOB

------------- ---------- ---------- ---------

KING                7839            PRESIDENT

  JONES             7566       7839 MANAGER

      ADAMS         7876       7788 CLERK

      SMITH         7369       7902 CLERK

BLAKE             7698         7839 MANAGER

    ALLEN           7499       7698 SALESMAN

    WARD            7521       7698 SALESMAN

    MARTIN          7654       7698 SALESMAN

    TURNER          7844       7698 SALESMAN

    JAMES           7900       7698 CLERK

CLARK             7782         7839 MANAGER

    MILLER          7934       7782 CLERK

ORACLE does not return the analysts SCOTT and FORD, although it does return employees who are managed by SCOTT and FORD.

This statement is similar to the first one, except that it uses the LEVEL pseudocolumn to select only the first two levels of the management hierarchy:

SELECT LPAD(' ',2*(LEVEL-1)) || ename org_chart, empno,

mgr, job

FROM emp

START WITH job = 'PRESIDENT'

CONNECT BY PRIOR empno = mgr AND LEVEL <= 2

ORG_CHART          EMPNO        MGR JOB

------------- ---------- ---------- ---------

KING                7839            PRESIDENT

  JONES             7566       7839 MANAGER

  BLAKE             7698       7839 MANAGER

  CLARK             7782       7839 MANAGER

GROUP BY Clause

You can use the GROUP BY clause to group selected rows and return a single row of summary information. ORACLE collects each group of rows based on the values of the expression(s) specified in the GROUP BY clause.

If a SELECT statement contains the GROUP BY clause, the select list can only contain these types of expressions:

•	constants

•	group functions

•	the functions USER, UID, and SYSDATE

•	expressions identical to those in the GROUP BY clause

•	expressions involving the above expressions that evaluate to the same value for all rows in a group

Expressions in the GROUP BY clause can contain any columns in the tables, views, and snapshots in the FROM clause regardless of whether the columns appear in the select list.

The total number of bytes in all expressions in the GROUP BY clause is limited to the size of a data block minus some overhead. This size is specified by the initialization parameter DB_BLOCK_SIZE.

Example V	To return the minimum and maximum salaries for each department in the employee table, issue this statement:

SELECT deptno, MIN(sal), MAX(sal)

FROM emp

GROUP BY deptno

DEPTNO   MIN(SAL)   MAX(SAL)

-------- ---------- ----------

10       1300       5000

20        800       3000

30        950       2850

Example VI	To return the minimum and maximum salaries for the clerks in each department, issue this statement:

SELECT deptno, MIN(sal), MAX(sal)

FROM emp

WHERE job = 'CLERK'

 	GROUP BY deptno

DEPTNO   MIN(SAL)   MAX(SAL)

-------- ---------- ----------

10       1300       1300

20        800       1100

30        950        950

HAVING Clause

You can use the HAVING clause to restrict which groups of rows defined by the GROUP BY clause are returned by the query. ORACLE processes the WHERE, GROUP BY, and HAVING clauses in the following manner:

1.	If the statement contains a WHERE clause, ORACLE removes all rows that do not satisfy it.

2.	ORACLE calculates and forms the groups as specified in the GROUP BY clause.

3.	ORACLE removes all groups that do not satisfy the HAVING clause.

Specify the GROUP BY and HAVING clauses after the WHERE and CONNECT BY clauses. If both the GROUP BY and HAVING clauses are specified, they can appear in either order.

Example VII	To return the minimum and maximum salaries for the clerks in each department whose lowest salary is below $1,000, issue this statement:

SELECT deptno, MIN(sal), MAX(sal)

FROM emp

WHERE job = 'CLERK'

GROUP BY deptno

HAVING MIN(sal) < 1000

DEPTNO   MIN(SAL)   MAX(SAL)

-------- ---------- ----------

20        800       1100

30        950        950

Set Operators

The UNION, UNION ALL, INTERSECT, and MINUS operators combine the results of two queries into a single result. The number and datatypes of the columns selected by each component query must be the same, but the column lengths can be different. For information on the use of each set operator, see the section "Set Operators" on page NO TAG.

If more than two queries are combined with set operators, adjacent pairs of queries are evaluated from left to right. You can use parentheses to specify a different order of evaluation.

The total number of bytes in all select list expressions of a component query is limited to the size of a data block minus some overhead. The size of a data block is specified by the initialization parameter DB_BLOCK_SIZE.

ORDER BY Clause

You can use the ORDER BY clause to order the rows selected by a query. The clause specifies either expressions or positions or aliases of expressions in the select list of the statement. ORACLE returns rows based on their values for these expressions.

You can specify multiple expressions in the ORDER BY clause. ORACLE first sorts rows based on their values for the first expression. Rows with the same value for the first expression are then sorted based on their values for the second expression, and so on. ORACLE sorts nulls following all others in ascending order and preceding all others in descending order.

Sorting by position is useful in these cases:

•	To order by a lengthy select list expression, you can specify its position, rather than duplicate the entire expression, in the ORDER BY clause.

•	For compound queries (containing set operators UNION, INTERSECT, MINUS, or UNION ALL), the ORDER BY clause must use positions, rather than explicit expressions. Also, the ORDER BY clause can only appear in the last component query. The ORDER BY clause orders all rows returned by the entire compound query.

The mechanism by which ORACLE sorts values for the ORDER BY clause is specified either explicitly by the NLS_SORT initialization parameter or implicitly by the NLS_LANGUAGE initialization parameter.  For information on these parameters, see Appendix C "National Language Support" of the ORACLE7 Server Administrator's Guide. You can also change the sort mechanism dynamically from one linguistic sort sequence to another using the ALTER SESSION command. You can also specify a specific sort sequence for a single query by using the NLSSORT function with the NLS_SORT parameter in the ORDER BY clause.

The ORDER BY clause is subject to these restrictions:

•	If the ORDER BY clause and the DISTINCT operator both appear in a SELECT statement, the ORDER BY clause cannot refer to columns that do not appear in the select list.

•	The ORDER BY clause cannot appear in subqueries within other statements.

•	The total number of bytes in all expressions in the ORDER BY clause is limited to the size of a data block minus some overhead. The size of a data block is specified by the initialization parameter DB_BLOCK_SIZE.

If you use the ORDER BY and GROUP BY clauses together, the expressions that can appear in the ORDER BY clause are subject to the same restrictions as the expressions in the select list, described in section "GROUP BY Clause" on page 8 - 344.

If you use the ORDER BY clause in a hierarchical query, ORACLE uses the ORDER BY clause rather than the hierarchy to order the rows.

Example VIII	To select all salesmen's records from EMP, and order the results by commission in descending order, issue this statement:

SELECT *

FROM emp

WHERE job = 'SALESMAN'

ORDER BY comm DESC

Example IX	To select the employees from EMP ordered first by ascending department number and then by descending salary, issue this statement:

SELECT ename, deptno, sal

FROM emp

ORDER BY deptno ASC, sal DESC

To select the same information as the previous SELECT and use the positional ORDER BY notation, issue this statement:

SELECT ename, deptno, sal

FROM emp

ORDER BY 2 ASC, 3 DESC

FOR UPDATE Clause

The FOR UPDATE clause locks the rows selected by the query. Once you have selected a row for update, other users cannot lock or update it until you end your transaction. The FOR UPDATE clause signals that you intend to insert, update, or delete the rows returned by the query, but does not require that you perform one of these operations. A SELECT statement with a FOR UPDATE clause is often followed by one or more UPDATE statements with WHERE clauses.

Note that the columns in this clause only specify which tables' rows are locked. The specific columns of the table that you specify are not significant. If you omit the column list from this clause, ORACLE locks the selected rows from all the tables in the query.

The FOR UPDATE clause cannot be used with these other constructs:

•	DISTINCT operator

•	GROUP BY clause

•	set operators

•	group functions

The tables locked by the FOR UPDATE clause must all be located on the same database. These locked tables must also be on the same database as any LONG columns and sequences referenced in the same statement.

If a row selected for update is currently locked by another user, ORACLE waits until the row is available, locks it, and then returns control to you. You can use the NOWAIT option to cause ORACLE to terminate the statement without waiting if such a row is already locked.

Example X	This statement locks all the clerks in the employee table who work in New York and all departments in New York that have clerks:

SELECT empno, sal, comm

FROM emp, dept

WHERE job = 'CLERK'

  AND emp.deptno = dept.deptno

  AND loc = 'NEW YORK'

FOR UPDATE

Joins

A join is a query that combines rows from two or more tables, views, or snapshots. ORACLE performs a join whenever multiple tables appear in the query's FROM clause. The query's select list can select any columns from any of these tables. If any two of these tables have a column name in common, you must qualify all references to these columns throughout the query with table names to avoid ambiguity.

 Join Conditions

Most join queries contain WHERE clause conditions that compare two columns, each from a different table. Such a condition is called a join condition. To execute a join, ORACLE combines pairs of rows, each containing one row from each table, for which the join condition evaluates to TRUE. The columns in the join conditions need not also appear in the select list.

To execute a join of three or more tables, ORACLE first joins two of the tables based on the join conditions comparing their columns and then joins the result to another table based on join conditions containing columns of the joined tables and the new table. ORACLE continues this process until all tables are joined into the result. The optimizer determines the order in which ORACLE joins tables based on the join conditions, indexes on the tables, and, in the case of the cost-based optimization approach, statistics for the tables.

In addition to join conditions, the WHERE clause of a join query can also contain other conditions that refer to columns of only one table. These conditions can further restrict the rows returned by the join query.

 Equijoins

An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that have equivalent values for the specified columns. Depending on the internal algorithm the optimizer chooses to execute the join, the total size of the columns in the equijoin condition in a single table may be limited to the size of a data block minus some overhead. The size of a data block is specified by the initialization parameter DB_BLOCK_SIZE.

Example XI	This equijoin returns the name and job of each employee and the number and name of the department in which the employee works:

SELECT ename, job, dept.deptno, dname

FROM emp, dept

WHERE emp.deptno = dept.deptno

ENAME      JOB           DEPTNO DNAME

---------- --------- ---------- --------------

CLARK      MANAGER           10 ACCOUNTING

KING       PRESIDENT         10 ACCOUNTING

MILLER     CLERK             10 ACCOUNTING

SMITH      CLERK             20 RESEARCH

ADAMS      CLERK             20 RESEARCH

FORD       ANALYST           20 RESEARCH

SCOTT      ANALYST           20 RESEARCH

JONES      MANAGER           20 RESEARCH

ALLEN      SALESMAN          30 SALES

BLAKE      MANAGER           30 SALES

MARTIN     SALESMAN          30 SALES

JAMES      CLERK             30 SALES

TURNER     SALESMAN          30 SALES

WARD       SALESMAN          30 SALES

You must use a join to return this data because employee names and jobs are stored in a different table than department names. ORACLE combines rows of the two tables according to this join condition:

emp.deptno = dept.deptno

Example XII	The following equijoin returns the name, job, department number, and department name of all clerks:

SELECT ename, job, dept.deptno, dname

FROM emp, dept

WHERE emp.deptno = dept.deptno

  AND job = 'CLERK'

ENAME      JOB           DEPTNO DNAME

---------- --------- ---------- --------------

MILLER     CLERK             10 ACCOUNTING

SMITH      CLERK             20 RESEARCH

ADAMS      CLERK             20 RESEARCH

JAMES      CLERK             30 SALES

This query is identical to Example XI except that it uses an additional WHERE clause condition to return only rows with a JOB value of 'CLERK':

job = 'CLERK'

 Self Joins

A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that are used to qualify column names in the join condition. To perform a self join, ORACLE combines and returns rows of the table that satisfy the join condition.

Example XIII	This query uses a self join to returns the name of each employee along with the name of the employee's manager:

SELECT e1.ename||' works for '||e2.ename

"Employees and their Managers"

FROM emp e1, emp e2 	WHERE e1.mgr = e2.empno

Employees and their Managers

-------------------------------

SCOTT      works for JONES

FORD       works for JONES

ALLEN      works for BLAKE

WARD       works for BLAKE

JAMES      works for BLAKE

TURNER     works for BLAKE

MARTIN     works for BLAKE

MILLER     works for CLARK

ADAMS      works for SCOTT

JONES      works for KING

CLARK      works for KING

BLAKE      works for KING

SMITH      works for FORD

The join condition for this query uses the aliases E1 and E2 for the EMP table:

e1.mgr = e2.empno

 Cartesian Products

If two tables in a join query have no join condition, ORACLE returns their Cartesian product. ORACLE combines each row of one table with each row of the other. A Cartesian product always generates a large number of rows and is rarely useful. For example, the Cartesian product of two tables each with a hundred rows has ten thousand rows. Always include a join condition unless you specifically need a Cartesian product. If a query joins three or more tables and there is no join condition for a specific pair, the optimizer may choose a join order that avoids producing an intermediate Cartesian product.

Outer Joins

The outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition as well as those rows from one table for which no rows from the other satisfy the join condition. Such rows are not returned by a simple join. To write a query that performs an outer join of tables A and B and returns all rows from A, apply the outer join operator (+) to all columns of B in the join condition. For all rows in A that have no matching rows in B, ORACLE returns NULL for any select list expressions containing columns of B.

Outer join queries are subject to these rules and restrictions:

•	The (+) operator can only appear in the WHERE clause, not in the select list, and can only be applied to a column of a table or view.

•	If A and B are joined by multiple join conditions, the (+) operator must be used in all of these conditions.

•	The (+) operator can only be applied to a column, rather than to an arbitrary expression, although an arbitrary expression can contain a column marked with the (+) operator.

•	A condition containing the (+) operator cannot be combined with another condition using the OR logical operator.

•	A condition cannot use the IN comparison operator to compare a column marked with the (+) operator to another expression.

•	A condition cannot compare a column marked with the (+) operator to a subquery.

If the WHERE clause contains a condition that compares a column from table B to a constant, the (+) operator must be applied to the column so that the rows from table A for which ORACLE has generated NULLs for this column are returned.

In a query that performs outer joins of more than two pairs of tables, a single table can only be the NULL-generated table for one other table. For this reason, you cannot apply the (+) operator to columns of B in the join condition for A and B and the join condition for B and C.

Example XIV	This query uses an outer join to extend the results of Example X:

SELECT ename, job, dept.deptno, dname

FROM emp, dept

WHERE emp.deptno (+) = dept.deptno

ENAME      JOB           DEPTNO DNAME

---------- --------- ---------- --------------

CLARK      MANAGER           10 ACCOUNTING

KING       PRESIDENT         10 ACCOUNTING

MILLER     CLERK             10 ACCOUNTING

SMITH      CLERK             20 RESEARCH

ADAMS      CLERK             20 RESEARCH

FORD       ANALYST           20 RESEARCH

SCOTT      ANALYST           20 RESEARCH

JONES      MANAGER           20 RESEARCH

ALLEN      SALESMAN          30 SALES

BLAKE      MANAGER           30 SALES

MARTIN     SALESMAN          30 SALES

JAMES      CLERK             30 SALES

TURNER     SALESMAN          30 SALES

WARD       SALESMAN          30 SALES                                                     40 OPERATIONS

In this outer join, ORACLE returns a row containing the OPERATIONS department even though no employees work in this department. ORACLE returns NULL in the ENAME and JOB columns for this row. The join query in Example X only selects departments that have employees.

The following query uses an outer join to extend the results of Example XI:

SELECT ename, job, dept.deptno, dname

FROM emp, dept

WHERE emp.deptno (+) = dept.deptno

  AND job (+) = 'CLERK'

ENAME      JOB           DEPTNO DNAME

---------- --------- ---------- --------------

MILLER     CLERK             10 ACCOUNTING

SMITH      CLERK             20 RESEARCH

ADAMS      CLERK             20 RESEARCH

JAMES      CLERK             30 SALES                                                     40 OPERATIONS

In this outer join, ORACLE returns a row containing the OPERATIONS department even though no clerks work in this department. The (+) operator on the JOB column ensures that rows for which the JOB column is NULL are also returned. If this (+) were omitted, the row containing the OPERATIONS department would not be returned because its JOB value is not 'CLERK'.

Example XV	This example shows four outer join queries on the CUSTOMERS, ORDERS, LINEITEMS, and PARTS tables. These tables are shown here:

SELECT custno, custname

FROM customers

CUSTNO     CUSTNAME

---------- --------------------

1          Angelic Co.

2          Believable Co.

3          Cabels R Us

SELECT orderno, custno, TO_CHAR(orderdate, 'MON-DD-YYYY')

"ORDERDATE"

FROM orders

ORDERNO    CUSTNO     ORDERDATE

---------- ---------- -----------

9001       1          OCT-13-1993

9002       2          OCT-13-1993

9003       1          OCT-20-1993

9004       1          OCT-27-1993

9005       2          OCT-31-1993

SELECT orderno, lineno, partno, quantity

FROM lineitems

ORDERNO        LINENO     PARTNO   QUANTITY

---------- ---------- ---------- ----------

9001       1         101         15

9001       2         102         10

9002       1         101         25

9002       2         103         50

9003       1         101         15

9004       1         102         10

9004       2         103         20

SELECT partno, partname

FROM parts

PARTNO     PARTNAME

---------- --------

101        X-Ray Screen

102        Yellow Bag

103        Zoot Suit

Note that the customer Cabels R Us have placed no orders and that order number 9005 has no line items.

The following outer join returns all customers and the dates they placed orders. The (+) operator ensures that customers who placed no orders are also returned:

SELECT custname, TO_CHAR(orderdate, 'MON-DD-YYYY') "ORDERDATE"

FROM customers, orders

WHERE customers.custno = orders.custno (+)

CUSTNAME             ORDERDATE

-------------------- --------------

Angelic Co.         OCT-13-1993

Angelic Co.         OCT-20-1993

Angelic Co.         OCT-27-1993

Believable Co.      OCT-13-1993

Believable Co.      OCT-31-1993

Cabels R Us

The following outer join builds on the result of the previous one by adding the LINEITEMS table to the FROM clause, columns from this table to the select list, and a join condition joining this table to the ORDERS table to the WHERE clause. This query joins the results of the previous query to the LINEITEMS table and returns all customers, the dates they placed orders, and the part number and quantity of each part they ordered. The first (+) operator serves the same purpose as in the previous query. The second (+) operator ensures that orders with no line items are also returned:

SELECT custname,

TO_CHAR(orderdate, 'MON-DD-YYYY') "ORDERDATE",

partno,

quantity

FROM customers, orders, lineitems

WHERE customers.custno = orders.custno (+)

  AND orders.orderno = lineitems.orderno (+)

CUSTNAME             ORDERDATE          PARTNO   QUANTITY

-------------------- -------------- ---------- ----------

Angelic Co.         OCT-13-1993           101         15

Angelic Co.         OCT-13-1993           102         10

Angelic Co.         OCT-20-1993           101         15

Angelic Co.         OCT-27-1993           102         10

Angelic Co.         OCT-27-1993           103         20

Believable Co.      OCT-13-1993           101         25

Believable Co.      OCT-13-1993           103         50

Believable Co.      OCT-31-1993

Cabels R Us

The following outer join builds on the result of the previous one by adding the PARTS table to the FROM clause, the PARTNAME column from this table to the select list, and a join condition joining this table to the LINEITEMS table to the WHERE clause. This query joins the results of the previous query to the PARTS table to return all customers, the dates they placed orders, and the quantity and name of each part they ordered. The first two (+) operators serve the same purposes as in the previous query. The third (+) operator ensures that rows with NULL part numbers are also returned:

SELECT custname,

TO_CHAR(orderdate, 'MON-DD-YYYY') "ORDERDATE",

quantity,

partname

FROM customers, orders, lineitems, parts

WHERE customers.custno = orders.custno (+)

  AND orders.orderno = lineitems.orderno (+)

  AND lineitems.partno = parts.partno (+)

CUSTNAME             ORDERDATE        QUANTITY PARTNAME

-------------------- -------------- ---------- ------------

Angelic Co.         OCT-13-1993            15 X-Ray Screen

Angelic Co.         OCT-13-1993            10 Yellow Bag

Angelic Co.         OCT-20-1993            15 X-Ray Screen

Angelic Co.         OCT-27-1993            10 Yellow Bag

Angelic Co.         OCT-27-1993            20 Zoot Suit

Believable Co.      OCT-13-1993            25 X-Ray Screen

Believable Co.      OCT-13-1993            50 Zoot Suit

Believable Co.      OCT-31-1993

Cabels R Us

Subqueries

A subquery is a form of the SELECT command that appears inside another SQL statement. A subquery is sometimes called a nested query. The statement containing a subquery is called the parent statement. The rows returned by the subquery are used by the parent statement.

This is the syntax for a subquery:

Subqueries can be used for these purposes:

•	to define the set of rows to be inserted into the target table of an INSERT or CREATE TABLE statement

•	to define the set of rows to be included in a view or snapshot in a CREATE VIEW or CREATE SNAPSHOT statement

•	to define one or more values to be assigned to existing rows in an UPDATE statement

•	to provide values for conditions in WHERE, HAVING, and START WITH clauses of SELECT, UPDATE, and DELETE statements

A subquery is used to answer multiple part questions. For example, to determine who works in Taylor's department, you can first use a subquery to determine in which department Taylor works. You can then answer the original question with the parent SELECT statement.

A subquery is evaluated once for the entire parent statement, in contrast to a correlated subquery which is evaluated once per row processed by the parent statement.

A subquery can itself contain a subquery. ORACLE places no limit on the level of query nesting.

Example XVI	To determine who works in Taylor's department, issue this statement:

SELECT ename, deptno

FROM emp

WHERE deptno =

(SELECT deptno

FROM emp

WHERE ename = 'TAYLOR')

Example XVII	To give all employees in the EMP table a ten percent raise if they have not already been issued a bonus (if they do not appear in the BONUS table), issue this statement:

UPDATE emp

SET sal = sal * 1.1

 	WHERE empno NOT IN (SELECT empno FROM bonus)

Example XVIII	To create a duplicate of the DEPT table named NEWDEPT, issue this statement:

CREATE TABLE newdept (deptno, dname, loc)

AS SELECT deptno, dname, loc FROM dept

Correlated Subqueries

A correlated subquery is a subquery that is evaluated once for each row processed by the parent statement. The parent statement can be a SELECT, UPDATE, or DELETE statement. These examples show the general syntax of a correlated subquery:

SELECT select_list

FROM table1 t_alias1

WHERE expr operator

(SELECT column_list

FROM table2 t_alias2

WHERE t_alias1.column

      operator t_alias2.column)

UPDATE table1 t_alias1

SET column =

(SELECT expr

FROM table2 t_alias2

WHERE t_alias1.column = t_alias2.column)

DELETE FROM table1 t_alias1

WHERE column operator

(SELECT expr

FROM table2 t_alias2

WHERE t_alias1.column = t_alias2.column)

This discussion focuses on correlated subqueries in SELECT statements, although it also applies to correlated subqueries in UPDATE and DELETE statements.

You can use a correlated subquery to answer a multi-part question whose answer depends on the value in each row processed by the parent statement. For example, a correlated subquery can be used to determine which employees earn more than the average salaries for their departments. In this case, the correlated subquery is used specifically to compute the average salary for each department.

ORACLE performs a correlated subquery when the subquery references a column from a table from the parent statement.

ORACLE resolves unqualified columns in the subquery by looking in the tables of the subquery, then in the tables of the parent statement, then in the tables of the next enclosing parent statement, and so on. ORACLE resolves all unqualified columns in the subquery to the same table. If the tables in a subquery and parent query contain a column with the same name, a reference to the column of a table from the parent query must be prefixed by the table name or alias. To make your statements easier for you to read, always qualify the columns in a correlated subquery with the table, view, or snapshot name or alias.

In the case of an UPDATE statement, you can use a correlated subquery to update rows in one table based on rows from another table. For example, you could use a correlated subquery to roll up four quarterly sales tables into a yearly sales table.

In the case of a DELETE statement, you can use a correlated query to delete only those rows that also exist in another table.

Example XIX	This statement returns data about employees whose salaries exceed the averages for their departments. This statement assigns an alias to EMP, the table containing the salary information, and then uses the alias in a correlated subquery:

SELECT deptno, ename, sal

FROM emp x

WHERE sal > (SELECT AVG(sal)

FROM emp

WHERE x.deptno = deptno)

ORDER BY deptno

For each row of the EMP table, the parent query uses the correlated subquery to compute the average salary for members of the same department. The correlated subquery performs these steps for each row of the EMP table:

1.	The DEPTNO of the row is determined.

2.	The DEPTNO is then used to evaluate the parent query.

3.	If that row's salary is greater than the average salary for that row's department, then the row is returned.

The subquery is evaluated once for each row of the EMP table.

Selecting from the DUAL Table

DUAL is a table automatically created by ORACLE along with the data dictionary. It is in the schema of the user SYS, but is accessible by the name DUAL to all users. It has one column, DUMMY, defined to be VARCHAR2(1), and contains one row with a value 'X'. Selecting from the DUAL table is useful for computing a constant expression with the SELECT command. Because DUAL has only one row, the constant is only returned once. You can select a constant, pseudocolumn, or expression from any table, but it is convenient to select from DUAL.

Example XX	This statement returns the current date:

SELECT SYSDATE FROM DUAL

You could select SYSDATE from the EMP table, but ORACLE would return 14 rows of the same SYSDATE, one for every row of the EMP table. Selecting from DUAL is more convenient.

Using Sequences

The sequence pseudocolumns NEXTVAL and CURRVAL can also appear in the select list of a SELECT statement. For information on sequences and their use, see the CREATE SEQUENCE command earlier in this chapter and the section "Pseudocolumns" on page 2 - 37.

Example XXI	This statement increments the ZSEQ sequence and returns the new value:

SELECT zseq.nextval

FROM dual

This statement selects the current value of ZSEQ:

SELECT zseq.currval

FROM dual

Distributed Queries

ORACLE's distributed database management system architecture allows you to access data in remote databases using SQL*Net and an ORACLE Server. You can identify a remote table, view, or snapshot by appending @dblink to the end of its name. The dblink must be a complete or partial name for a database link to the database containing the remote table, view, or snapshot. For more information on referring to database links, see the section "Referring to  on page 2 - 13.

Distributed queries are currently subject to this restriction:  all tables locked by a FOR UPDATE clause and all tables with LONG columns selected by the query must be located on the same database. For example, you cannot issue this statement because it locks the EMP_NY table on the NY database and the DEPT table on the local database:

SELECT emp_ny.*

FROM emp_ny@ny, dept

WHERE emp_ny.deptno = dept.deptno

  AND dept.dname = 'ACCOUNTING'

FOR UPDATE OF emp_ny.sal

Also, you cannot issue this statement because it selects LONG_COLUMN, a LONG value, from the EMP_REVIEW table on the NY database and locks the EMP table on the local database:

SELECT emp.empno, review.long_column, emp.sal

FROM emp, emp_review@ny review

WHERE emp.empno = emp_review.empno

FOR UPDATE OF emp.sal

Example XXII	This example shows a query which joins the DEPT table on the local database with the EMP table on the HOUSTON database:

SELECT ename, dname

FROM emp@houston, dept

WHERE emp.deptno = dept.deptno

Related Topics

DELETE, SELECT (Embedded SQL), and UPDATE commands.

________________________________________

SELECT (Embedded SQL)

Purpose

To retrieve data from one or more tables, views, or snapshots, assigning the selected values to host variables.

Prerequisites

For you to select data from a table or snapshot, the table or snapshot must be in your own schema or you must have SELECT privilege on the table or snapshot.

For you to select rows from the base tables of a view, the owner of the schema containing the view must have SELECT privilege on the base tables. Also, if the view is in a schema other than your own, you must have SELECT privilege on the view.

The SELECT ANY TABLE system privilege also allows you to select data from any table or any snapshot or any view's base table.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the creation label of each queried table, view, or snapshot or you must have READUP system privileges.

Syntax

Keywords and Parameters

AT	identifies the database to which the SELECT statement is issued. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, the SELECT statement is issued to your default database.

select_list	identical to the non-embedded SELECT command except that a host variables can be used in place of literals.

INTO	specifies output host variables and optional indicator variables to receive the data returned by the SELECT statement. Note that these variables must be either all scalars or all arrays, but arrays need not have the same size.

WHERE	restricts the rows returned to those for which the condition is TRUE. See the syntax description of condition on page NO TAG. The condition can contain host variables and optional indicator variables. These host variables can be either scalars or arrays.

All other keywords and parameters are identical to the non-embedded SQL SELECT command.

Usage Notes

If no rows meet the WHERE clause condition, no rowsare retrieved and ORACLE returns an error code through the SQLCODE component of the SQLCA.

You can use comments in a SELECT statement to pass instructions, or hints, to the ORACLE optimizer. The optimizer uses hints to choose an execution plan for the statement. For more information on hints, see Chapter 5  of the ORACLE7 Server Application Developer's Guide.

Example I	This example illustrates the use of the embedded SQL SELECT command:

EXEC SQL SELECT ename, sal + 100, job

INTO :ename, :sal, :job

FROM emp

WHERE empno = :empno

Related Topics

DECLARE DATABASE, DECLARE CURSOR, EXECUTE, FETCH, and PREPARE commands.

________________________________________

SET ROLE

Purpose

To enable and disable roles for your current session.

Prerequisites

You also must already have been granted the roles that you name in this statement.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must dominate the label at which these roles were granted to you.

Syntax

Keywords and Parameters

role	is a role to be enabled for the current session. Any roles not listed are disabled for the current session.

password	is the password for a role. If the role has a password, you must specify the password to enable the role.

ALL  EXCEPT	enables all roles granted to you for the current session, except those listed in the EXCEPT clause. Roles listed in the EXCEPT clause must be roles granted directly to you; they cannot be roles granted to you through other roles. You cannot use this option to enable roles with passwords that have been granted directly to you.

If you list a role in the EXCEPT clause that has been granted to you both directly and through another role, the role is still enabled by virtue of your enabling the role to which it has been granted.

NONE	disables all roles for the current session.

Default Privilege Domain

 At logon ORACLE establishes your default privilege domain by enabling your default roles. Your default privilege domain contains all privileges granted explicitly to you and all privileges in the privilege domains of your default roles. You can then perform any operations authorized by the privileges in your default privilege domain.

Changing Your Privilege Domain

During your session, you can change your privilege domain with the SET ROLE command. The SET ROLE command changes the roles currently enabled for your session. You can change your enabled roles any number of times during a session. The number of roles that can be concurrently enabled is limited by the initialization parameter MAX_ENABLED_ROLES.

You can use the SET ROLE command to enable or disable any of these roles:

•	roles that have been granted directly to you

•	roles granted to you through other roles

You cannot use the SET ROLE command to enable roles that you have not been granted either directly or through other roles.

Your current privilege domain is also changed in these cases:

•	if you are granted a privilege

•	if one of your privileges is revoked

•	if one of your enabled roles is revoked

•	if the privilege domain of one of your enabled roles is changed

If none of these conditions occur and you do not issue the SET ROLE command, your default privilege domain remains in effect for the duration of your session. In the last two cases, the change in your privilege domain does not take effect until you logon to ORACLE again or issue a SET ROLE statement.

You can determine which roles are in your current privilege domain at any time by examining the SESSION_ROLES data dictionary view.

To change your default roles, use the ALTER USER command.

Example I	To enable the role GARDENER identified by the password MARIGOLDS for your current session, issue this statement:

SET ROLE gardener IDENTIFIED BY marigolds

Example II	To enable all roles granted to you for the current session, issue this statement:

SET ROLE ALL

Example III	To enable all roles granted to you except BANKER, issue this statement:

SET ROLE ALL EXCEPT banker

Example IV	To disable all roles granted to you for the current session, issue this statement:

SET ROLE NONE

Related Topics

CREATE ROLE and ALTER USER commands.

________________________________________

SET TRANSACTION

Purpose

To perform one of these operations on your current transaction:

•	establish your current transaction as either a read-only or a read-write transaction

•	assign your current transaction to a specified rollback segment

Prerequisites

A SET TRANSACTION statement must be the first statement in your transaction. However, every transaction need not begin with a SET TRANSACTION statement.

Syntax

Keywords and Parameters

READ ONLY	establishes the current transaction as a read-only transaction.

READ WRITE	establishes the current transaction as a read-write transaction.

USE ROLLBACK SEGMENT	assigns the current transaction to the specified rollback segment. This option also establishes the transaction as a read-write transaction.

You cannot use the READ ONLY option and the USE ROLLBACK SEGMENT clause in a single SET TRANSACTION statement or in different statements in the same transaction. Read-only transactions do not generate rollback information and therefore are not assigned rollback segments.

Usage Notes

The operations performed by a SET TRANSACTION statement affect only your current transaction, not other users or other transactions. Yourtransaction ends whenever you issue a COMMIT or ROLLBACK statement. Note also that ORACLE implicitly commits the current transaction before and after executing a Data Definition Language statement.

Establishing Read-only Transactions

The default state for all transactions is statement level read consistency. You can explicitly specify this state by issuinga SET TRANSACTION statement with the READ WRITE option.

You can establish transaction level read consistency by issuing a SET TRANSACTION statement with the READ ONLY option. After a transaction has been established as read-only, all subsequent queries in that transaction only see changes committed before the transaction began. Read-only transactions are very useful for reports that run multiple queries against one or more tables while other users update these same tables.

Only these statements are permitted in a read-only transaction:

•	SELECT (except statements with the FOR UPDATE clause)

•	LOCK TABLE

•	SET ROLE

•	ALTER SESSION

•	ALTER SYSTEM

INSERT, UPDATE, and DELETE statements and SELECT statements with the FOR UPDATE clause are not permitted. Any Data Definition Language statement implicitly ends the read-only transaction.

The read consistency that read-only transactions provide is implemented in the same way as statement-level read consistency. Every statement by default uses a consistent view of the data as of the time the statement is issued. Read-only transactions present a consistent view of the data as of the time that the SET TRANSACTION READ ONLY statement is issued. Read-only transactions provide read consistency is for all nodes accessed by distributed queries as well as local queries.

You cannot toggle between transaction level read consistency and statement level read consistency in the same transaction. A SET TRANSACTION statement can only be issued as the first statement of a transaction.

Example I	The following statements could be run at midnight of the last day of every month to count how many ships and containers the company owns. This report would not be affected by any other user who might be in the process of adding or removing ships and/or containers.

COMMIT

SET TRANSACTION READ ONLY

SELECT COUNT(*) FROM ship

SELECT COUNT(*) FROM container

COMMIT

The last COMMIT statement does not actually make permanent any changes to the database. It is used to end the read-only transaction.

Assigning Transactions to Rollback Segments

If you issue a Data Manipulation Language statement in a transaction, ORACLE assigns the transaction to a rollback segment. The rollback segment holds the information necessary to undo the changes made by the transaction. You can issue a SET TRANSACTION statement with the USE ROLLBACK SEGMENT clause to choose a specific rollback segment for your transaction. If you do not choose a rollback segment, ORACLE chooses one randomly and assigns your transaction to it.

This statement allows you to assign transactions of different types to rollback segments of different sizes:

•	Assign OLTP transactions, or small transactions containing only a few Data Manipulation Language statements that modify only a few rows, to small rollback segments if there are no long-running queries concurrently reading the same tables. Small rollback segments are more likely to remain in memory.

•	Assign transactions that modify tables that are concurrently being read by long-running queries to large rollback segments so that the rollback information needed for the read consistent queries is not overwritten.

•	Assign transactions with bulk Data Manipulation Language statements, or statements that insert, update, or delete large amounts of data, to rollback segments large enough to hold the rollback information for the transaction.

Example II	This statement assigns your current transaction to the rollback segment OLTP_5:

SET TRANSACTION 	USE ROLLBACK SEGMENT oltp_5

Related Topics

COMMIT, ROLLBACK, and SAVEPOINT commands.

________________________________________

STORAGE clause

Purpose

To specify storage characteristics for tables, indexes, clusters, and rollback segments, and the default storage characteristics for tablespaces.

Prerequisites

The STORAGE clause can appear in commands that create or alter any of these objects:

•	clusters

•	indexes

•	rollback segments

•	snapshots

•	snapshot logs

•	tables

•	tablespaces

To change the value of a STORAGE parameter, you must have the privileges necessary to issue one of these commands.

Syntax

Keywords and Parameters

INITIAL	specifies the size in bytes of the object's first extent. ORACLE allocates space for this extent when you create the object. You can also use K or M to specify this size in kilobytes or megabytes. The default value is the size of 5 data blocks. The minimum value is the size of 2 data blocks. The maximum value varies depending on your operating system. ORACLE rounds values up to the next multiple of the data block size.

NEXT	specifies the size in bytes of the next extent to be allocated to the object. You can also use K or M to specify the size in kilobytes or megabytes. The default value is the size of 5 data blocks. The minimum value is the size of 1 data block. The maximum value varies depending on your operating system. ORACLE rounds values up to the next multiple of the data block size.

PCTINCREASE	specifies the percent by which each extent after the second grows over the previous extent. The default value is 50,  meaning that each subsequent extent is 50% larger than the preceding extent. The minimum value is 0, meaning all extents after the first are the same size. The maximum value varies depending on your operating system.

You cannot specify PCTINCREASE for rollback segments. Rollback segments always have a PCTINCREASE value of 0.

ORACLE rounds the calculated size of each new extent up to the next multiple of the data block size.

MINEXTENTS	specifies the total number of extents allocated when the segment is created. This parameter allows you to allocate a large amount of space when you create an object, even if the space available is not contiguous. The default and minimum value is 1, meaning that ORACLE only allocates the initial extent, except for rollback segments for which the default and minimum value is 2. The maximum value varies depending on your operating system.

If the MINEXTENTS value is greater than 1, then ORACLE calculates the size of subsequent extents based on the values of the INITIAL, NEXT, and PCTINCREASE parameters.

MAXEXTENTS	specifies the total number of extents, including the first, that ORACLE can allocate for the object. The minimum value is 1. The default and maximum values vary depending your data block size.

OPTIMAL	specifies an optimal size in bytes for a rollback segment. You can also use K or M to specify this size in kilobytes or megabytes. ORACLE tries to maintain this size for the rollback segment by dynamically deallocating extents when their data is no longer needed for active transactions. ORACLE deallocates as many extents as possible without reducing the total size of the rollback segment below the OPTIMAL value. This parameter is only for rollback segments and not for other objects.

NULL	specifies no optimal size for the rollback segment, meaning that ORACLE never deallocates the rollback segment's extents. This is the default behavior.

The value of this parameter cannot be less than the space initially allocated for the rollback segment specified by the MINEXTENTS, INITIAL, NEXT, and PCTINCREASE parameters. The maximum value varies depending on your operating system. ORACLE rounds values to the next multiple of the data block size.

 FREELIST GROUPS	specifies the number of groups of free lists for a table, cluster, or index. The default and minimum value for this parameter is 1. Only use this parameter if you are using ORACLE with the Parallel Server option in parallel mode.

FREELISTS	specifies the number of free lists for each of the free list groups for the table, cluster, or index. The default and minimum value for this parameter is 1, meaning that each free list group contains one free list. The maximum value of this parameter depends on the data block size. If you specify a FREELISTS value that is too large, ORACLE returns an error message indicating the maximum value.

You can only specify the FREELISTS parameter in CREATE TABLE, CREATE CLUSTER, and CREATE INDEX statements. You can only specify the FREELIST GROUPS parameter in CREATE TABLE and CREATE CLUSTER statements.

Usage Notes

 The STORAGE parameters affect both how long it takes to access data stored in the database as well as how efficientlyspace in the database is used. For a discussion of the effects of these parameters, see Chapter 22 "Tuning I/O" of the ORACLE7 Server Administrator's Guide.

When you create a tablespace, you can specify values for the STORAGE parameters. These values serve as default STORAGE parameter values for segments allocated in the tablespace.

When you create a cluster, index, rollback segments, snapshot, snapshot log, or table, you can specify values for the STORAGE parameters for the segments allocated to these objects. If you omit any STORAGE parameter, ORACLE uses the value of that parameter specified for the tablespace.

When you alter a cluster, index, rollback segment, snapshot, snapshot log, or table, you can change the values of STORAGE parameters. These new values only affect future extent allocations. For this reason, you cannot change the values of the INITIAL and MINEXTENTS parameter. If you change the value of the NEXT parameter, the next allocated extent will have the specified size, regardless of the size of the most-recently allocated extent and the value of the PCTINCREASE parameter. If you change the value of the PCTINCREASE parameter, ORACLE calculates the size of the next extent using this new value and the size of the most recently allocated extent.

When you alter a tablespace, you can change the values of STORAGE parameters. These new values serve as default values only to subsequently allocated segments (or subsequently created objects).

Example I	This statement creates a table and provides STORAGE parameter values:

CREATE TABLE dept

(deptno  NUMBER(2),

 dname   VARCHAR2(14),

 loc     VARCHAR2(13) )

STORAGE (INITIAL 100K  NEXT     50K

         MINEXTENTS 1  MAXEXTENTS 50  PCTINCREASE 5 )

ORACLE allocates space for the table based on the STORAGE parameter values:

•	Because the MINEXTENTS value is 1, ORACLE allocates 1 extent for the table upon creation.

•	Because the INITIAL value is 100K, the first extent's size is 100 kilobytes.

•	If the table data grows to exceed the first extent, ORACLE allocates a second extent. Because the NEXT value is 50K, the second extent's size is 50 kilobytes.

•	If the table data subsequently grows to exceed the first two extents, ORACLE allocates a third extent. Because the PCTINCREASE value is 5, the calculated size of the third extent is 5% larger than the second extent, or 52.5 kilobytes. If the data block size is 2 kilobytes, ORACLE rounds this value to 52 kilobytes.

If the table data continues to grow, ORACLE allocates more extents, each 5% larger than the previous one.

•	Because the MAXEXTENTS value is 50, ORACLE can allocate as many as 50 extents for the table.

Example II	This statement creates a rollback segment and provides STORAGE parameter values:

CREATE ROLLBACK SEGMENT rsone

STORAGE ( INITIAL  10K  NEXT 10K

          MINEXTENTS 2  MAXEXTENTS 25

          OPTIMAL 50K )

ORACLE allocates space for the rollback segment based on the STORAGE parameter values:

•	Because the MINEXTENTS value is 2, ORACLE allocates 2 extents for the rollback segment upon creation.

•	Because the INITIAL value is 10K, the first extent's size is 10 kilobytes.

•	Because the NEXT value is 10K, the second extent's size is 10 kilobytes.

•	If the rollback data exceeds the first two extents, ORACLE allocates a third extent. Because the PCTINCREASE value for rollback segments is always 0, the third extent is the same size as the second extent, 10 kilobytes.

If the rollback data continues to grow, ORACLE allocates more extents, each the same size as the previous one, 10 kilobytes.

•	Because the MAXEXTENTS value is 25, ORACLE can allocate as many as 25 extents for the rollback segment.

•	Because the OPTIMAL value is 50K, ORACLE deallocates extents if the rollback segment exceeds 50 kilobytes. Note that ORACLE only deallocates extents that contain data for transactions that are no longer active.

Related Topics

CREATE CLUSTER, CREATE INDEX, CREATE ROLLBACK SEGMENT, CREATE TABLE, and CREATE TABLESPACE commands.

________________________________________

TRUNCATE

Purpose

To remove all rows from a table or cluster.

Prerequisites

The table or cluster must be in your schema or you must have DELETE ANY TABLE system privilege.

If you are using Trusted ORACLE, your DBMS label must match the creation label of the table or cluster or you must satisfy one of these criteria:

•	If the creation label of the table or cluster is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the creation label of the table or cluster is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the creation label of the table or cluster is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

TABLE	specifies the schema and name of the table to be truncated. If you omit schema, ORACLE assumes the table is in your own schema. This table cannot be part of a cluster.

When you truncate a table, ORACLE also automatically deletes all data in the table's indexes.

CLUSTER	specifies the schema and name of the cluster to be truncated. If you omit schema, ORACLE assumes the cluster is in your own schema. You can only truncate an indexed cluster, not a hash cluster.

When you truncate a cluster, ORACLE also automatically deletes all data in the cluster's tables' indexes.

DROP STORAGE	deallocates the space from the deleted rows from the table or cluster. This space can subsequently be used by other objects in the tablespace.

REUSE STORAGE	leaves the space from the deleted rows allocated to the table or cluster. This space can be subsequently used only by new data in the table or cluster resulting from inserts or updates.

The DROP STORAGE or REUSE STORAGE option that you choose also applies to the space freed by the data deleted from associated indexes.

If you omit both the REUSE STORAGE and DROP STORAGE options, ORACLE uses the DROP STORAGE option by default.

Usage Notes

You can use the TRUNCATE command to quickly remove all rows from a table or cluster. Removing rows with the TRUNCATE command is faster than removing them with the DELETE command for these reasons:

•	The TRUNCATE command is a Data Definition Language command and generates no rollback information.

•	Truncating a table does not fire the table's DELETE triggers.

•	Truncating the master table of a snapshot does not record any changes in the table's snapshot log.

The TRUNCATE command allows you to optionally deallocate the space freed by the deleted rows. The DROP STORAGE option deallocates all but the space specified by the table's MINEXTENTS parameter.

Deleting rows with the TRUNCATE command is also more convenient than dropping and recreating a table for these reasons:

•	Dropping and recreating invalidates the table's dependent objects, while truncating does not.

•	Dropping and recreating requires you to regrant object privileges on the table, while truncating does not.

•	Dropping and recreating requires you to recreate the table's indexes, integrity constraints, and triggers and respecify its STORAGE parameters, while truncating does not.

You cannot individually truncate a table that is part of a cluster. You must either truncate the cluster, delete all rows from the table, or drop and recreate the table.

You cannot truncate the parent table of an enabled referential integrity constraint. You must disable the constraint before truncating the table.

If you truncate the master table of a snapshot, ORACLE does not record the removed rows in the snapshot log. For this reason, a fast refresh does not remove the rows from the snapshot. Snapshots based on a truncated table must be refreshed completely for ORACLE to remove their rows.

You cannot roll back a TRUNCATE statement.

Example I	This statement deletes all rows from the EMP table and returns the freed space to the tablespace containing EMP:

TRUNCATE TABLE emp

This statement also deletes all data from all indexes on EMP and returns the freed space to the tablespaces containing them.

Example II	This statement deletes all rows from all tables in the CUST cluster, but leaves the freed space allocated to the tables:

TRUNCATE CLUSTER cust

REUSE STORAGE

This statement also deletes all data from all indexes in the tables in CUST.

Related Topics

DELETE, DROP CLUSTER, and DROP TABLE command.

________________________________________

TYPE (Embedded SQL)

Purpose

To perform user-defined type equivalencing, or to assign an ORACLE external datatype to awhole class of host variables by equivalencing the external datatype to a user-defined datatype.

Prerequisites

The user-defined datatype must be previously declared in an embedded SQL program.

Syntax

Keywords and Parameters

type	is the user-defined datatype to be equivalenced with an ORACLE external datatype.

datatype	is an ORACLE external datatype recognized by the ORACLE Precompilers (not an ORACLE internal datatype). The datatype may include a length, precision, or scale. This external datatype is equivalenced to the user-defined type and assigned to all host variables assigned the type. For a list of external datatypes, see the Programmer's Guide to the ORACLE Precompilers.

Usage Notes

User defined type equivalencing is one kind of datatype equivalencing. You can only perform user-defined type equivalencing with the embedded SQL TYPE command in a Pro*C or Pro*Pascal Precompiler program. You may want to use datatype equivalencing for one of these purposes:

•	to automatically null-terminate a character host variable

•	to store program data as binary data in the database

•	to override default datatype conversion

For more information on using the TYPE command to perform user-defined type equivalencing, see the Programmer's Guide to the ORACLE Precompilers.

All ORACLE Precompilers also support the embedded SQL VAR command for host variable equivalencing.

Example I	This example shows an embedded SQL TYPE statement in a Pro*C Precompiler program:

struct screen {short len;

   char  buff[4002];

               };

typedef struct screen graphics;

EXEC SQL BEGIN DECLARE SECTION;

EXEC SQL TYPE graphics IS VARRAW (4002);

graphics crt;  -- host variable of type graphics

...

EXEC SQL END DECLARE SECTION;

Example II	This example shows an embedded SQL TYPE statement in a Pro*Pascal Precompiler program:

Type

OraDate = Record

    Cent, Year, Month, Day, Hour, Min, Sec: Byte                 End;

Var

EXEC SQL BEGIN DECLARE SECTION;

  EXEC SQL TYPE OraDate IS DATE;

  Birthday: OraDate;  -- host variable of type OraDate

  ...

EXEC SQL END DECLARE SECTION;

Related Topics

VAR command (Embedded SQL).

________________________________________

UPDATE

Purpose

To change existing values in a table or in a view's base table.

Prerequisites

For you to update values in a table, the table must be in your own schema or you must have UPDATE privilege on the table.

For you to update values in the base table of a view, the owner of the schema containing the view must have UPDATE privilege on the base table. Also, if the view is in a schema other than your own, you must have UPDATE privilege on the view.

The UPDATE ANY TABLE system privilege also allows you to update values in any table or any view's base table.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the creation label of the table or view:

•	If the creation label of the table or view is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the creation label of the table or view is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the creation label of your table or view is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

schema	is the schema containing the table or view. If you omit schema, ORACLE assumes the table or view is in your own schema.

table view	is the name of the table to be updated. If you specify view, ORACLE updates the view's base table.

dblink	is a complete or partial name of a database link to a remote database where the table or view is located. For information on referring to database links, see the section "Referring to Objects  on page 2 - 13. You can only use a database link to update a remote table or view if you are using ORACLE with the distributed option.

If you omit dblink, ORACLE assumes the table or view is on the local database.

alias	is used to relabel the name of the reference in the other clauses of the command.

column	is the name of a column of the table or view that is to be updated. If you omit a column of the table from the SET clause, that column's value remains unchanged.

expr	is the new value assigned to the corresponding column. This expression can contain host variables and optional indicator variables. See the syntax description of expr on page NO TAG.

subquery	is a SELECT statement that returns new values that are assigned to the corresponding columns. See the syntax description of subquery on page 8 - 362.

WHERE	restricts the rows updated to those for which the specified condition is TRUE. If you omit this clause, ORACLE updates all rows in the table or view. See the syntax description of condition on page NO TAG.

Usage Notes

 The SET clause determines which columns are updated and what new values are stored in them.

The WHERE clause determines the rows in which values are updated. If no WHERE clause is specified, all rows are updated.  For each row that satisfies the WHERE clause, the columns to the left of the equals (=) operator in the SET clause are set to the values of the corresponding expressions on the right. The expressions are evaluated as the row is updated.

You can use comments in an UPDATE statement to pass instructions, or hints, to the ORACLE optimizer. The optimizer uses hints to choose an execution plan for the statement. For more information, see the ORACLE7 Server Application Developer's Guide.

Issuing an UPDATE statement against a table fires any UPDATE triggers associated with the table.

Updating Views

If a view was created with the WITH CHECK OPTION, you can only update the view if the resulting data satisfies the view's defining query.

You cannot update a view if the view's defining query contains one of these constructs:

•	join

•	set operator

•	GROUP BY clause

•	group function

•	DISTINCT operator

Subqueries

If the SET clause contains a subquery, it must return exactly one row for each row updated. Each value in the subquery result is assigned respectively to the columns in the parenthesized list. If the subquery returns no rows, then the column is assigned a null. Subqueries may select from the table being updated.

The SET clause may intermix assignments of expressions and subqueries.

Correlated Update

If a subquery refers to columns from the updated table, ORACLE evaluates the subquery once for each row, rather than once for the entire update. Such an update is called a correlated update. The reference to columns from the updated table is usually accomplished by means of a table alias.

Potentially, each row evaluated by an UPDATE statement could be updated with a different value as determined by the correlated subquery. Normal UPDATE statements update each row with the same value.

Example I	This statement gives null commissions to all employees with the job TRAINEE:

UPDATE emp

SET comm = NULL

WHERE job = 'TRAINEE'

Example II	This statement promotes JONES to manager of Department 20 with a $1,000 raise (assuming there is only one JONES):

UPDATE emp

SET job = 'MANAGER', sal = sal + 1000, deptno = 20

WHERE ename = 'JONES'

Example III	This statement increases the balance of bank account number 5001 in the ACCOUNTS table on a remote database accessible through the database link BOSTON:

UPDATE accounts@boston

SET balance = balance + 500

WHERE acc_no = 5001

Example IV	This example shows these syntactic constructs of the UPDATE command:

•	both forms of the SET clause together in a single statement

•	a correlated subquery

•	a WHERE clause to limit the updated rows

UPDATE emp a

SET deptno =

(SELECT deptno

FROM dept

WHERE loc = 'BOSTON'),

(sal, comm) =

(SELECT 1.1*AVG(sal), 1.5*AVG(comm)

FROM emp b

WHERE a.deptno = b.deptno)

WHERE deptno IN

(SELECT deptno

FROM dept

WHERE loc = 'DALLAS'

   OR loc = 'DETROIT')

This UPDATE statement performs these operations:

•	updates only those employees who work in Dallas or Detroit

•	sets DEPTNO for these employees to the DEPTNO of Boston

•	sets each employee's salary to 1.1 times the average salary of their department

•	sets each employee's commission to 1.5 times the average commission of their department

Related Topics

DELETE and INSERT commands.

________________________________________

UPDATE (Embedded SQL)

Purpose

To change existing values in a table or in a view's base table.

Prerequisites

For you to update values in a table or snapshot, the table must be in your own schema or you must have UPDATE privilege on the table.

For you to update values in the base table of a view, the owner of the schema containing the view must have UPDATE privilege on the base table. Also, if the view is in a schema other than your own, you must have UPDATE privilege on the view.

The UPDATE ANY TABLE system privilege also allows you to update values in any table or any view's base table.

If you are using Trusted ORACLE in DBMS MAC mode, your DBMS label must match the creation label of the table or view:

•	If the creation label of the table or view is higher than your DBMS label, you must have READUP and WRITEUP system privileges

•	If the creation label of the table or view is lower than your DBMS label, you must have WRITEDOWN system privilege.

•	If the creation label of your table or view is noncomparable to your DBMS label, you must have READUP, WRITEUP, and WRITEDOWN system privileges.

Syntax

Keywords and Parameters

AT	identifies the database to which the UPDATE statement is issued. The database can be identified by either:

db_name	is a database identifier declared in a previous DECLARE DATABASE statement.

:host_variable	is a host variable whose value is a previously declared db_name.

If you omit this clause, the UPDATE statement is issued to your default database.

FOR :host_integer	limits the number of times the UPDATE statement is executed if the SET and WHERE clauses contain array host variables. If you omit this clause, ORACLE executes the statement once for each component of the smallest array.

schema	is the schema containing the table or view. If you omit schema, ORACLE assumes the table or view is in your own schema.

table view	is the name of the table to be updated. If you specify view, ORACLE updates the view's base table.

dblink	is a complete or partial name of a database link to a remote database where the table or view is located. For information on referring to database links, see the section "Referring to Objects  on page 2 - 13. You can only use a database link to update a remote table or view if you are using ORACLE with the distributed option.

If you omit dblink, ORACLE assumes the table or view is on the local database.

column	is the name of a column of the table or view that is to be updated. If you omit a column of the table from the SET clause, that column's value remains unchanged.

expr	is the new value assigned to the corresponding column. This expression can contain host variables and optional indicator variables. See the syntax description of expr on page NO TAG.

subquery	is a SELECT statement that returns new values that are assigned to the corresponding columns. For the syntax description of subquery, see page 8 - 362.

WHERE	specifies which rows of the table or view are updated:

condition	updates only rows for which this condition is true. This condition can contain host variables and optional indicator variables. See the syntax description of condition on page NO TAG.

CURRENT OF	updates only the row most recently fetched by the cursor. The cursor cannot be associated with a SELECT statement that performs a join unless its FOR UPDATE clause explicitly locks only one table.

If you omit this clause entirely, ORACLE updates all rows of the table or view.

Usage Notes

Host variables in the SET and WHERE clauses must be either all scalars or all arrays. If they are scalars, ORACLE executes the UPDATE statementonly once. If they are arrays, ORACLE executes the statement once for each set of array components. Each execution may update zero, one, or multiple rows.

Array host variables can have different sizes. In this case, the number of times ORACLE executes the statement is determined by the smaller of these values:

•	the size of the smallest array

•	the value of the :host_integer in the optional FOR clause

The cumulative number of rows updated is returned through the third element of the SQLERRD component of the SQLCA. When arrays are used as input host variables, this count reflects the total number of updates for all components of the array processed in the UPDATE statement. If no rows satisfy the condition, no rows are updated and ORACLE returns an error message through the SQLCODE element of the SQLCA. If you omit the WHERE clause, all rows are updated and ORACLE raises a warning flag in the fifth component of the SQLWARN element of the SQLCA.

You can use comments in an UPDATE statement to pass instructions, or hints, to the ORACLE optimizer. The optimizer uses hints to choose an execution plan for the statement. For more information on hints, see Chapter 5  of the ORACLE7 Server Application Developer's Guide.

For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Examples	These examples illustrate the use of the embedded SQL UPDATE command:

EXEC SQL UPDATE emp

SET sal = :sal, comm = :comm INDICATOR :comm_ind

WHERE ename = :ename;

EXEC SQL UPDATE emp

SET (sal, comm) =

(SELECT AVG(sal)*1.1, AVG(comm)*1.1

FROM emp)

WHERE ename = 'JONES';

Related Topics

DECLARE DATABASE and UPDATE commands.

________________________________________

VAR (Embedded SQL)

Purpose

To perform host variable equivalencing,or to assign a specific ORACLE external datatype to an individual host variable, overriding the default datatype assignment.

Prerequisites

The host variable must be previously declared in the Declare Section of the embedded SQL program.

Syntax

Keywords and Parameters

host_variable	is the host variable to be assigned an ORACLE external datatype.

datatype	is an ORACLE external datatype recognized by the ORACLE Precompilers (not an ORACLE internal datatype). The datatype may include a length, precision, or scale. This external datatype is assigned to the host_variable. For a list of external datatypes, see the Programmer's Guide to the ORACLE Precompilers.

Usage Notes

Host variable equivalencing is one kind of datatype equivalencing. You may want to use datatype equivalencing for one of these purposes:

•	to automatically null-terminate a character host variable

•	to store program data as binary data in the database

•	to override default datatype conversion

For more information on using the VAR command to perform host variable equivalencing, see the Programmer's Guide to the ORACLE Precompilers. The Pro*C and Pro*Pascal Precompilers also support the embedded SQL TYPE command for user-defined type equivalencing.

Example	This example equivalences the host variable DEPT_NAME to the datatype STRING and the host variable BUFFER to the datatype RAW(2000):

EXEC SQL BEGIN DECLARE SECTION;

...

dept_name  CHARACTER(15);  -- default datatype is CHAR

EXEC SQL VAR dept_name IS STRING; -- reset to STRING

...

buffer CHARACTER(200); -- default datatype is CHAR

EXEC SQL VAR buffer IS RAW(200); -- refer to RAW

EXEC SQL END DECLARE SECTION;

Related Topics

TYPE command (Embedded SQL).

________________________________________

WHENEVER (Embedded SQL)

Purpose

To specify the action to be taken when if error an warning results from executing an embedded SQL program.

Prerequisites

None.

Syntax

Keywords and Parameters

NOT FOUND 	identifies any exception condition that results in a return code of +100 in SQLCODE, (or +1403 in Version 5 compatibility mode).

SQLERROR	identifies a condition that results in a negative return code.

SQLWARNING	identifies a non-fatal warning condition.

CONTINUE	indicates that the program should progress to the next statement.

GOTO	indicates that the program should branch to the statement named by label_name.

STOP	stops program execution.

DO	indicates that the program should call a host language routine. The syntax of routine_call depends on your host language. See your language-specific Supplement to the ORACLE Precompilers Guide.

Usage Notes

The WHENEVER command allows your program to transfer control to an errorhandling routine in the event an embedded SQL statement results in an error or warning.

The scope of a WHENEVER statement is positional, rather than logical. A single WHENEVER statement applies to all embedded SQL statements that physically follow it in the Precompiler source file, not in the flow of the program logic. A WHENEVER statement remains in effect until it is superseded by another WHENEVER statement checking for the same condition.

For more information on this command, see the Programmer's Guide to the ORACLE Precompilers.

Do not confuse the WHENEVER embedded SQL command with the WHENEVER SQL*Plus command.

Example	The example illustrates the use of the WHENEVER command in a Pro*C embedded SQL program:

EXEC SQL WHENEVER NOT FOUND;

...

EXEC SQL WHENEVER SQLERROR GOTO sqlerror:

...

sql_error:

EXEC SQL WHENEVER SQLERROR CONTINUE;

EXEC SQL ROLLBACK RELEASE;


APPENDIX A. SUMMARY OF CHANGES TO SQL IN ORACLE7

This appendix lists differences in the SQL language between ORACLE7 and ORACLE Version 6. Many of these changes have been implemented to support new features of ORACLE7. Others have been implemented so that ORACLE complies with standard SQL. This appendix has information on these topics:

•	terminology used in this Manual

•	reserved words

•	ORACLE datatypes

•	commands

•	SQL functions

•	format elements

•	operators

•	comments

•	namespaces

•	system privileges

•	optional components of ORACLE7

•	compatibility modes

________________________________________

Terminology Used in this Manual

Some new terms have been introduced in ORACLE7 that describe features of ORACLE Version 6. These are new terms that better explain old concepts:

initialization parameters	The term initialization parameter now describes parameters that you use to specify configuration settings when starting an instance.

In Version 6 manuals, these parameters were commonly called INIT.ORA parameters.

schema	The term schema now describes the collection of objects owned by a user. Every user owns a schema in which objects can be created. The name of that schema is the same as the name of the user. The name of an object can be qualified by the schema in which the object exists. For example, the table EMP in the schema of the user SCOTT can be identified by SCOTT.EMP.

In Version 6 manuals, there was no distinction between a user and the collection of objects owned by the user. The name of an object could be qualified by the name of the user who owned it.

server processes	The term server process now describes a process that handles requests from user processes. A server process can be either dedicated to one user process or shared among many user processes, depending on the configuration of your instance.

In Version 6 manuals, these processes were called shadow processes.

Session Control commands	The term Session Control commands now describes a category of SQL commands that manage the properties of a session. This category includes the ALTER SESSION command (described in Version 6 manuals as a Data Definition Language command) and the new SET ROLE command.

system change number (SCN)	The term system change number now describes values that identify committed transactions.

In Version 6 manuals, these values were called system commit numbers. The new term is still abbreviated SCN.

System Control commands	The term System Control commands now describes a category of SQL commands that manage the properties of your ORACLE instance. This category includes the new ALTER SYSTEM command.

Transaction Control commands	The term Transaction Control commands now describes a category of SQL commands that manage changes made by Data Manipulation Language commands. This category includes the COMMIT, ROLLBACK, and SAVEPOINT commands (described in Version 6 as Data Manipulation Language commands) and the SET TRANSACTION command (described in Version 6 manuals as a Data Definition Language command).

________________________________________

Reserved Words

This section lists changes to the SQL reserved words in ORACLE7:

•	new reserved words in ORACLE7

•	previously reserved words now obsolete

A complete list of all the SQL reserved words for ORACLE7, begins on page 2 - 4.

New Reserved Words

ORACLE7 has new SQL reserved words:

ROWLABEL	This reserved word is the name of a column automatically created by Trusted ORACLE7 for all tables in the database. This column holds the label for each row in the table. For more information on ROWLABEL, see the Trusted ORACLE7 Server Administrator's Guide.

In the standard ORACLE7 Server, ROWLABEL is also a reserved word and always evaluates to null.

VARCHAR2	This reserved word is a datatype for variable length character strings. For more information on this datatype, see the section "ORACLE Datatypes"  beginning on page A - 4 and the section "Character Datatypes" on page 2 - 23.

Do not use these words to name objects or their parts in ORACLE7.

Obsolete Reserved Words

Previous versions of ORACLE contained SQL reserved words that are no longer reserved in ORACLE7:

•	GRAPHIC

•	IF

•	VARGRAPHIC

You can use these words as names of schema objects or object parts in ORACLE7.

________________________________________

ORACLE Datatypes

ORACLE7 has new datatypes and changes to existing datatypes. This section discusses how ORACLE7 treats these types of data:

•	numeric data

•	character data

•	LONG data

•	label data

Numeric Datatypes

ORACLE7 returns an error if a numeric expression evaluates to a value greater than or equal to 10126 or less than or equal to -10126. ORACLE Version 6 returned a tilde (~) for a value outside of these limits.

Character Datatypes

This section discusses the differences in ORACLE Version 6 and ORACLE7 character datatypes. For information on upgrading to ORACLE7 with respect to these differences, see the ORACLE7 Server Migration Guide.

 In ORACLE Version 6

ORACLE Version 6 supported one datatype for character strings:

CHAR	Values of this datatype were variable length character strings of maximum length 255 characters. ORACLE Version 6 compared CHAR values using non-padded comparison semantics.

ORACLE Version 6 also supported these synonyms for the CHAR datatype:

•	CHARACTER

•	VARCHAR

 In ORACLE7

ORACLE7 supports two datatypes for character strings:

CHAR	Values of this datatype are fixed length character strings of maximum length 255 characters. ORACLE7 compares CHAR values using blank-padded comparison semantics. Note that the ORACLE7 CHAR datatype is not equivalent to the ORACLE Version 6 CHAR datatype.

VARCHAR2	Values of this datatype are variable length character strings of maximum length 2000. ORACLE7 compares VARCHAR2 values using non-padded comparison semantics. The VARCHAR2 datatype is equivalent to the ORACLE Version 6 CHAR datatype except for the difference in maximum lengths.

ORACLE7 also supports these synonyms for the CHAR and VARCHAR2 datatypes:

CHARACTER	This datatype is synonymous with the ORACLE7 CHAR datatype.

VARCHAR	This datatype is currently synonymous with the VARCHAR2 datatype. However, Oracle Corporation recommends that you use VARCHAR2 rather than VARCHAR. In a future version of ORACLE, VARCHAR may be a separate datatype used for variable length character strings compared with different comparison semantics.

For complete information on the ORACLE7 datatypes, including the differences between blank-padded and non-padded comparison semantics, see the sections "Character Datatypes" on page 2 - 23 and "Datatype Comparison  on page 2 - 31.

LONG Datatype

The LONG datatype has new properties and fewer restrictions:

•	The maximum length a LONG value is now 2 gigabytes, or 231 - 1 bytes, increased from 65,535 bytes.

•	You can now use a distributed query to select a LONG column from a remote table or view.

For more information on the LONG datatype, see the section "LONG Datatype" on page 2 - 26.

Label Data

Labels are used by the Trusted ORACLE7 to mediate access to information.  The new MLSLABEL datatype is used to store representations of labels. For more information on these datatypes, see the Trusted ORACLE7 Server Administrator's Guide.

________________________________________

New Commands

These commands are new to the SQL language for ORACLE7. They were not part have been added for stored functions.

CREATE FUNCTION	These commands have been

ALTER FUNCTION	added for stored functions.

DROP FUNCTION

CREATE PACKAGE	These commands have been

CREATE PACKAGE BODY	added for stored packages.

ALTER PACKAGE

DROP PACKAGE

CREATE PROCEDURE	These commands have been

ALTER PROCEDURE 	added for stored procedures.

DROP PROCEDURE

CREATE TRIGGER	These commands have been

ALTER TRIGGER	added for database triggers.

DROP TRIGGER

ALTER VIEW	This command has been added to

recompile views.

CREATE PROFILE	These commands have been

ALTER PROFILE	added for resource limits.

DROP PROFILE

ALTER RESOURCE COST

CREATE ROLE	These commands have been

ALTER ROLE	added for security.

DROP ROLE

SET ROLE

CREATE USER

DROP USER

CREATE SNAPSHOT	These commands have been

ALTER SNAPSHOT	added for. snapshots.

DROP SNAPSHOT

CREATE SNAPSHOT LOG

ALTER SNAPSHOT LOG

DROP SNAPSHOT LOG

ALTER SYSTEM	This command has been added to

perform various specialized

operations on an instance.

ANALYZE	This command has been added to

collect statistics for cost-based

optimization.

CREATE CONTROLFILE	This command has been added

for recovery.

CREATE SCHEMA	This command has been added to

added to issue multiple Data

Definition Language statements

in the same transaction.

TRUNCATE	This command has been added to

added to quickly remove all rows

from a table or cluster.

For complete information on each of these commands, see Chapter 4 "Commands" of this Manual.

For a list of new embedded SQL commands for ORACLE7, see the Programmer's Guide to the ORACLE Precompilers.

________________________________________

Existing Commands with New Functionality

These commands were part of the SQL language for ORACLE Version 6, but they have new syntax or functionality in ORACLE7. For complete information on these commands, see the section describing the command in Chapter 4  of this Manual. For a list of embedded SQL commands with new syntax or functionality for ORACLE7, see the Programmer's Guide to ORACLE Precompilers.

ALTER CLUSTER

This command has a new ALLOCATE EXTENT clause for dynamic free space management.

The maximum value of the MAXEXTENTS parameter of the STORAGE clause varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and generated an error message only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE generates an error immediately.

For complete information on this parameter, see the section describing the STORAGE clause on page 8 - 371.

ALTER DATABASE

This command now allows you to specify multiple copies of redo log files and has new clauses to manipulate multiple copies of redo log files:

•	ADD LOGFILE MEMBER

•	DROP LOGFILE MEMBER

This command also has these new clauses for managing multiple redo log files for multiple instances of the ORACLE7 Parallel Server in parallel mode:

•	ENABLE THREAD

•	DISABLE THREAD

The ADD LOGFILE clause of this command also has a new THREAD parameter for this purpose.

This command also has a new PARALLEL option that replaces the SHARED option from ORACLE Version 6.

This command also has the new BACKUP CONTROLFILE, CREATE DATAFILE, and RECOVER clauses for backup and recovery.

This command also has the new RENAME GLOBAL_NAME to change the database's global name.

This command also has a new SET clause to change the MAC mode or to establish the labels DBHIGH and DBLOW with Trusted ORACLE7. For more information on this clause, see the Trusted ORACLE7 Server Administrator's Guide.

The CLOSE and DISMOUNT options of this command that were supported in previous versions are no longer supported. You should use the SQL*DBA SHUTDOWN command instead. For information on this command, see the ORACLE7 Server Utilities User's Guide.

ALTER INDEX

The maximum value of the MAXEXTENTS parameter of the STORAGE clause varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and generated an error message only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE generates an error immediately.

For complete information on this parameter, see the section describing the STORAGE clause on page 8 - 371.

ALTER ROLLBACK SEGMENT

You need no longer specify the PUBLIC keyword to alter a public rollback segment, although ORACLE still accepts this keyword for backward compatibility.

The STORAGE clause of this command has new syntax and functionality. For a summary of these changes, see the CREATE ROLLBACK SEGMENT command later in this list.

ALTER SESSION

This command has new parameters for National Language Support:

•	NLS_LANGUAGE

•	NLS_TERRITORY

•	NLS_DATE_FORMAT

•	NLS_DATE_LANGUAGE

•	NLS_NUMERIC_CHARACTERS

•	NLS_ISO_CURRENCY

•	NLS_CURRENCY

•	NLS_SORT

The equal sign (=) following the SQL_TRACE parameter is optional. Equal signs following all other parameters are mandatory.

This command also has a new GLOBAL_NAMES parameter to enable and disable global name resolution for remote objects. For more information on global name resolution, see Chapter 15 "Managing Distributed  of the ORACLE7 Server Administrator's Guide.

This command also has a new LABEL parameter to change your DBMS session label and to change your default label format with Trusted ORACLE7. For more information on this command, see the Trusted ORACLE7 Server Administrator's Guide.

This command also has a new OPTIMIZER_GOAL parameter to change:

•	the optimization approach between the rule-based approach and the cost-based approach

•	the goal of the cost-based approach between best throughput and best response time

In future versions of ORACLE, the rule-based approach will not be available and this parameter will only specify the goal of the cost-based approach.

This command also has a new CLOSE DATABASE LINK clause to explicitly close an open database link.

This command also has a new ADVISE clause for sending advice for forcing in-doubt distributed transactions to remote databases.

This command also has a new COMMIT IN PROCEDURE clause for permitting or prohibiting COMMIT and ROLLBACK commands in procedures and stored functions.

ALTER TABLE

This command has a new ALLOCATE EXTENT clause for dynamic free space management.

The maximum value of the MAXEXTENTS parameter of the STORAGE clause varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and generated an error message only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE generates an error immediately.

For complete information on this parameter, see the section describing the STORAGE clause on page 8 - 371.

This command also has these new clauses to enable and disable integrity constraints and database triggers:

•	ENABLE

•	DISABLE

The CONSTRAINT clause of the ALTER TABLE command also has new syntax and functionality. For a summary of these changes, see the CREATE TABLE command later in this list.

DEFAULT values for columns were not enforced by ORACLE Version 6. ORACLE7 does enforce them. ORACLE7 also ensures that a column is long enough to hold its DEFAULT value.

This command also has a new DROP clause for dropping integrity constraints.

For information on the ENABLE, DISABLE, CONSTRAINT, and DROP clauses, see the sections describing them in Chapter 4 "Commands" of this Manual.

ALTER TABLESPACE

This command has a new OFFLINE TEMPORARY option. Also, the ONLINE option generates an error message if the tablespace requires media recovery, rather than performing the media recovery transparently.

The maximum value of the MAXEXTENTS parameter of the STORAGE clause varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and returned an error message only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE returns an error message immediately.

For information on this parameter, see the section describing the STORAGE clause on page 8 - 371.

ALTER USER

This command has new clauses to assign tablespaces, profiles, and default roles to users:

•	QUOTA

•	PROFILE

•	DEFAULT ROLE

AUDIT (SQL Statements)

This form of the AUDIT command has many new system auditing options to support auditing of system operations with finer granularity.

AUDIT (Schema Objects)

This form of the AUDIT command has new object auditing options to support auditing of stored procedures, functions, and packages.

COMMIT

This command has new clauses for managing distributed transactions:

•	COMMENT

•	FORCE

CREATE CLUSTER

This command has these new parameters to create hash clusters:

•	HASH

•	HASHKEYS

The STORAGE clause of this command has new syntax and functionality:

•	The maximum value of the MAXEXTENTS parameter of the STORAGE varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and returns an error message only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE returns an error message immediately.

•	This clause has these new parameters for managing free space:

•	FREELIST GROUPS

•	FREELISTS

For complete information on these parameters, see the section describing the STORAGE clause on page 8 - 371.

CREATE DATABASE

This command now allows you to specify redo log file groups containing multiple copies. This command also has these new parameters:

MAXLOGMEMBERS	This parameter specifies the maximum number of members in a single redo log file group.

MAXLOGHISTORY	This parameter specifies the maximum number of archived redo log file groups for automatic media recovery of the ORACLE7 Parallel Server.

CHARACTER SET	This parameter specifies the database character set.

CREATE DATABASE LINK

The name of a database link must correspond to the name and domain of the remote database to which it connects. For more information on naming and referring to database links, see the section "Referring to Objects in Remote Databases" on page 2 - 13.

The USING clause of this command is now optional. This clause specifies the connect string to a remote database.

The USING clause also supports the specification of a secondary database for a read-only mount with Trusted ORACLE7. For information on using this command with read-only mounts, see the Trusted ORACLE7 Server Administrator's Guide.

When you issue a SQL statement that contains a database link, ORACLE must determine both of these things before connecting to the remote database:

•	a username and password (specified by the CONNECT TO clause of a CREATE DATABASE LINK statement)

•	a database string (specified by the USING clause of a CREATE DATABASE LINK statement)

ORACLE finds these things by first searching for private database links in your own schema with the same name as the database link in the statement, and then, if necessary, searching for a public database link with the same name.

ORACLE always determines the username and password from the first matching database link (either private or public). If the first matching database link has an associated username and password, ORACLE uses it. If it does not have an associated username and password, ORACLE uses your current username and password.

If the first matching database link has an associated database string, ORACLE uses it. If not, ORACLE searches for the next matching (public) database link. If there is no matching database link, or if no matching link has an associated database string, ORACLE returns an error message.

CREATE INDEX

Enforcing uniqueness among column values is now performed by integrity constraints. Oracle Corporation recommends that you use UNIQUE integrity constraints rather than unique indexes. Unique indexes may not be supported in future versions of ORACLE.

The STORAGE clause of this command has new syntax and functionality:

•	The maximum value of the MAXEXTENTS parameter of the STORAGE clause varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and returned an error message only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE returns an error message immediately.

•	This clause has the new FREELISTS parameter for managing free space.

For complete information on these parameters, see the section describing the STORAGE clause on page 8 - 371.

CREATE ROLLBACK SEGMENT

This command has these changes to the STORAGE clause parameters: @HALFLINESMUSH =

•	The PCTINCREASE parameter can no longer be specified for rollback segments. Rollback segments automatically have a PCTINCREASE value of 0.

•	The maximum value of the MAXEXTENTS parameter of the STORAGE clause varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and returned an error message only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE returns an error message immediately.

•	There is a new parameter OPTIMAL.

For complete information on these parameters, see the section describing the STORAGE clause on page 8 - 371.

CREATE TABLE

This command has these new clauses to enable and disable integrity constraints and triggers:

•	ENABLE

•	DISABLE

The CONSTRAINT clause of the CREATE TABLE command has new syntax and functionality:

•	The optional CONSTRAINT identifier must appear at the beginning of the CONSTRAINT clause in ORACLE7, rather than at the end as in ORACLE Version 6.

•	The new ON DELETE CASCADE option allows deletions of referenced key values from the parent table that have dependent rows in the child table and causes ORACLE to delete the dependent rows to maintain referential integrity.

•	The new DISABLE option allows you to disable an integrity constraint upon creation.

•	The new USING INDEX option allows you to specify parameter values and storage characteristics for the index that ORACLE7 uses to enforce a UNIQUE or PRIMARY KEY constraint.

•	The new EXCEPTIONS INTO clause allows you to identify existing rows that violate a constraint.

Furthermore, ORACLE Version 6 only enforced NOT NULL constraints. ORACLE7 enforces all types of integrity constraints.

DEFAULT values for columns were not enforced by ORACLE Version 6. ORACLE7 does enforce them. ORACLE7 also ensures columns are long enough to hold their DEFAULT values.

The STORAGE clause of this command has new syntax and functionality:

•	The maximum value of the MAXEXTENTS parameter of the STORAGE clause varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and generated an error only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE generates an error immediately.

•	This clause has these new parameters for managing free space:

•	FREELIST GROUPS

•	FREELISTS

For complete information on the ENABLE, DISABLE, CONSTRAINT, and STORAGE clauses, see the sections describing them in Chapter 4 "Commands" of this Manual.

CREATE TABLESPACE

The STORAGE clause of this command has new syntax and functionality:

•	The maximum value of the MAXEXTENTS parameter of the STORAGE clause varies depending on your data block size:

•	In ORACLE Version 6, if you specified a value that exceeded the maximum, ORACLE stored the specified value in the data dictionary and returned an error message only in the event of an attempt to allocate more extents than the maximum MAXEXTENTS value.

•	In ORACLE7, if you specify a value greater than the maximum, ORACLE returns an error message immediately.

•	This clause has these new parameters for managing free space:

•	FREELIST GROUPS

•	FREELISTS

For complete information on these parameters, see the section describing the STORAGE clause on page 8 - 371.

CREATE VIEW

This command has these new options:

OR REPLACE	This option allows you to redefine a view without dropping and recreating it and regranting object privileges previously granted on it.

FORCE	This option allows you to create a view even if the tables, views, and snapshots that it queries do not exist.

NOFORCE	This option prevents you from creating a view if the tables, views, and snapshots that it queries do not exist. This is the default option and is equivalent to the behavior of Version 6.

The authorization of this command is slightly different in ORACLE7 than in ORACLE Version 6. In ORACLE Version 6, a user granted the DBA system privilege could create a view based on any table in any schema. In ORACLE7, a user granted the predefined DBA role can only create a view if the owner of the schema to contain the view is granted privileges to select, insert, update, or delete rows from the base table. These privileges must be granted directly, rather than through roles.

DELETE

This command now allows you to delete rows from a remote table or view using a database link.

DROP CLUSTER

This command has a new CASCADE CONSTRAINTS option to allow you to drop referential integrity constraints from tables outside the dropped cluster that refer to primary and unique keys in the tables of the cluster.

DROP ROLLBACK SEGMENT

You need no longer specify the PUBLIC keyword to drop a public rollback segment, although ORACLE7 still accepts this keyword for backward compatibility.

DROP TABLE

This command has a new CASCADE CONSTRAINTS option to allow you to drop referential integrity constraints that refer to primary and unique keys in a dropped table.

EXPLAIN PLAN

The INTO clause of this command can now contain a remote table qualified by a database link.

The SQL statement in the FOR clause can now contain bind variables. ORACLE assumes these bind variables are of datatype VARCHAR2.

GRANT (System Privileges and Roles)

In ORACLE7, this form of the GRANT command is the same as Form I in ORACLE Version 6. It also has many new system privileges to support security management with finer granularity. This form of the GRANT command can also administer roles.

In ORACLE Version 6, the GRANT command (Form I) was also used to create users and change passwords. In ORACLE7, you can use the CREATE USER and ALTER USER commands to perform these tasks. Oracle Corporation recommends that you use the CREATE USER and ALTER USER commands rather than the GRANT command. Using the GRANT command for these purposes may not be supported in future versions of ORACLE. For information on using the GRANT command for these purposes, see the SQL Language Reference Manual for ORACLE Version 6.

In ORACLE Version 6, the GRANT command (Form II) gave users access to tablespaces. In ORACLE7, you can only perform this task with the new TABLESPACE clause of the CREATE USER and ALTER USER commands.

GRANT (Object Privileges)

In ORACLE7, this form of the GRANT command is the same as Form III in ORACLE Version 6. This form of the command grants privileges on specific objects. In ORACLE7, this form has new object privileges for security management of stored procedures, functions, and packages.

INSERT

This command now allows you to insert rows into a remote table or view using a database link.

LOCK TABLE

This command now allows you to lock a remote table or view using a database link.

NOAUDIT

Changes to the NOAUDIT command correspond directly to the changes to the AUDIT command listed earlier in this section.

REVOKE

Changes to the REVOKE command correspond directly to the changes to the GRANT command listed earlier in this section.

ROLLBACK

This command has a new FORCE clause for managing distributed transactions.

SELECT

ORACLE7 places fewer restrictions on distributed queries than ORACLE Version 6. For complete information on distributed queries, see the section "Distributed  on page 8 - 362.

In ORACLE Version 6, you could specify a column of a remote table in the select list using this syntax:

table@dblink.column

Since ORACLE7 interprets all characters following @ to be the complete name of a database link, you cannot use this syntax in ORACLE7. For example, you can issue this query in ORACLE Version 6, but not in ORACLE7:

SELECT emp@boston.ename

FROM emp@boston

ORACLE7 interprets 'boston.ename' to be the complete name of a database link. In ORACLE7, you can instead issue one of these equivalent queries also accepted by ORACLE Version 6:

SELECT e.ename

FROM emp@boston e

SELECT ename

FROM emp@boston

You can also issue this equivalent query that was not acceptable in ORACLE Version 6:

SELECT emp.ename@boston

FROM emp@boston

Also, in ORACLE Version 6, you could qualify a table.column expression with a schema in the select list regardless of whether the table was qualified with a schema in the FROM clause. In ORACLE7, you can only qualify a table.column expression with a schema if the table is qualified with a schema in the FROM clause. For example, you could issue this query in ORACLE Version 6, but not in ORACLE7:

SELECT scott.emp.ename

FROM emp

ORACLE7 places more restrictions on the WHERE clause conditions of SELECT statements that perform outer joins:

•	The OR logical operator cannot combine two conditions if either contains the outer join operator (+). Also, a condition cannot use the IN logical operator to compare a column  marked with the (+) operator to another expression. If you have applications that issue queries with such conditions, replace them with equivalent queries that use the UNION or UNION ALL set operators instead.

•	If a condition compares a column marked with the (+) operator to a subquery, ORACLE7 returns an error message. ORACLE Version 6 ignored the (+) operator in such conditions. If you have applications that issue queries with such conditions, remove the (+) operator from them and they will behave in ORACLE7 as they did in ORACLE Version 6.

SET TRANSACTION

This command has these new options:

READ WRITE	This option establishes the current transaction as a read-write transaction in which data can be both queried and modified, as opposed to a read-only transaction in which data can only be queried and not modified. ORACLE establishes a read-write transaction by default if you do not issue a SET TRANSACTION statement.

USE ROLLBACK SEGMENT	This option allows you to assign your current transaction to a specific rollback segment.

UPDATE

This command now allows you to update values in remote tables and views using a database link.

VALIDATE INDEX

Validating indexes is now also performed by the new ANALYZE command. Oracle Corporation recommends that you use the ANALYZE command rather than the VALIDATE INDEX command. The VALIDATE INDEX command may not be supported in future versions of ORACLE. For information on the VALIDATE INDEX command, see the SQL Language Reference Manual for ORACLE Version 6.

________________________________________

SQL Functions

This section lists:

•	new SQL functions added for ORACLE7

•	existing SQL functions with new functionality

New SQL Functions

These new SQL functions have been added for ORACLE7:

•	SIN

•	COS

•	TAN

•	SINH

•	COSH

•	TANH

•	EXP

•	LN

•	LOG

•	CONCAT

•	INSTRB

•	LENGTHB

•	SUBSTRB

•	NLS_INITCAP

•	NLS_LOWER

•	NLS_UPPER

•	TO_MULTI_BYTE

•	TO_SINGLE_BYTE

These new SQL functions have been added for Trusted ORACLE7:

•	GLB

•	LUB

•	TO_LABEL

•	GREATEST_LB

•	LEAST_UB

Existing SQL Functions with New Functionality

These functions have been enhanced for ORACLE7:

•	The POWER function now allows non-integral exponents.

•	The NLSSORT function now accepts the optional NLS_SORT parameter for National Language Support.

•	The TO_CHAR function now accepts the optional parameters NLS_DATE_LANGUAGE, NLS_NUMERIC_CHARACTERS, NLS_CURRENCY, and NLS_ISO_CURRENCY for National Language Support.

•	In Trusted ORACLE7, the TO_CHAR function converts values with the datatypes MLSLABEL or RAW MLSLABEL to values with the datatype VARCHAR2.

•	The TO_DATE function now accepts the optional NLS_DATE_LANGUAGE parameter for National Language Support.

•	The TO_NUMBER function now accepts the parameters NLS_NUMERIC_CHARACTERS, NLS_CURRENCY, and NLS_ISO_CURRENCY for National Language Support.

For complete information on these functions, see the section "Functions" on page NO TAG.

________________________________________

Format Models

These new number format elements have been added to SQL for ORACLE7:

•	D

•	G

•	L

•	C

•	RN

These new date format elements have been added to SQL for ORACLE7:

•	IYYY, IYY, IY, I

•	IW

•	RM

•	RR

If you used National Language Support in ORACLE Version 6, the WW date format element may behave differently in ORACLE7. In Version 6, depending on the territory component of the value of the LANGAUGE initialization parameter, WW returned a week number based on either the ISO standard or the number of days from January 1. In ORACLE7, WW always returns a week number based on the number of days from January 1, regardless of the value of the NLS_TERRITORY initialization parameter, and the new IW date format element returns the ISO standard week number. If your Version 6 application used WW to return the ISO standard week number, replace WW with IW.

ORACLE7 also has a new format model modifier FX and new functionality for the FM format model modifier. For information on format models, see the section "Format Models" on page NO TAG.

________________________________________

Operators

This section describes:

•	new operators

•	existing operators with changes in functionality

New Operators

These new operators have been added to SQL for ORACLE7:

SOME	This new comparison operator is synonymous with the ANY comparison operator.

UNION ALL	This new set operator combines two queries and returns all rows returned by either query, including all duplicate rows. The UNION ALL operator is similar to the UNION operator, except the UNION operator returns only one copy of duplicate rows.

Existing Operators with Functional Changes

The functionality of these existing operators has changed for ORACLE7:

-

Do not use consecutive minus signs with no separation in arithmetic expressions to indicate double negation or the subtraction of a negative value. The characters -- are used to begin comments within SQL statements. If you have applications that issue SQL statements with such arithmetic expressions, separate the minus signs with a space or a parenthesis.

LIKE	The LIKE operator accepts the new ESCAPE option, which allows you to use the characters % and _ literally, rather than as special pattern matching characters, within a pattern.

(+)	The outer join operator is subject to new restrictions listed in the section describing the SELECT command earlier in this chapter.

________________________________________

Comments

ORACLE7 supports comments within SQL statements beginning with -- as well as comments beginning with /*. For more information on comments within SQL statements, see the section "Comments" beginning on page 2 - 42.

________________________________________

Namespaces

This section describes:

•	changes to namespaces for schema objects

•	changes to namespaces for other objects

Changes to Namespaces for Schema Objects

Figure A - 1 shows the namespaces for schema objects in ORACLE Version 6:

For ORACLE7, changes have been made to these namespaces:

•	Stand-alone procedures, stand-alone stored functions, packages, and snapshots have been added to the namespace containing tables.

•	Indexes have been moved from the namespace containing tables to a new namespace.

•	Clusters have been moved from the namespace containing tables to a new namespace.

•	Database triggers have been added in a new namespace.

These changes are shown in bold in Figure A - 2.

Changes to Namespaces for Other Objects

Figure A - 3 shows the namespaces for other objects in ORACLE Version 6:

For ORACLE7, changes have been made to these namespaces:

•	Roles have been added to the namespace containing users.

•	Profiles have been added to a new namespace.

These changes are shown in bold in Figure A - 4.

________________________________________

Changes to the Optional Components of ORACLE

This section discusses the differences in the optional components between ORACLE Version 6 and ORACLE7.

With ORACLE Version 6, the transaction processing option was available. This option included these features:

•	row-level locking

•	PL/SQL

With ORACLE7, the transaction processing option is obsolete. However, these options are available:

procedural option	This option includes PL/SQL and allows you to use anonymous PL/SQL blocks, stored procedures, stored functions, stored packages, and database triggers.

distributed option	This option allows you to issue Data Manipulation Language (DELETE, EXPLAIN PLAN, LOCK TABLE, INSERT, and UPDATE) statements that modify data on remote databases.

Parallel Server option	This option allows multiple ORACLE instances to mount an ORACLE7 database in parallel mode. This functionality was also available in ORACLE Version 6.2.

To use snapshots, you must have both the procedural option and the distributed option. All other features of ORACLE7 (including row-level locking) are available in all installations and do not require one of these options.

________________________________________

Compatibility Modes

The compatibility mode controls ORACLE7's behavior in a few areas for which there are minor differences between ORACLE Version 6 and ORACLE7. ORACLE7 can operate in these compatibility modes:

V7 compatibility mode	In this mode, ORACLE interprets SQL exactly as described in this Manual.

V6 compatibility mode	In this mode, ORACLE interprets SQL as described in this Manual, with some exceptions for compatibility with ORACLE Version 6.

Table 7 - 1 describes the differences between V6 and V7 compatibility modes:

V6 Compatibility Mode	V7 Compatibility Mode

If you define a column of data	If you define a column of data

type CHAR, ORACLE creates the 	type CHAR, ORACLE creates the

column with the ORACLE7 VAR	column with the ORACLE7

CHAR2 datatype, which is equiv	CHAR datatype, which is not

alent to the ORACLE Version 6 	equivalent to the ORACLE Ver

CHAR datatype. The column is a 	sion 6 CHAR datatype. The col

variable-length character string 	umn is fixed-length character

with non-padded comparison se	string with blank-padded com

mantics and a maximum length 	parison semantics and a maxi

of 2000 bytes.	mum length of 255 bytes.

The optimal CONSTRAINT iden	The optional CONSTRAINT

tifier can only appear at the end 	identifier can only appear at the

of a CONTSTRAINT clause.	beginning of a CONSTRAINT

clause.

By default, PRIMARY KEY, 	By default, all integriy constraints

UNIQUE, referential integrity, 	are enabled upon creation.

and CHECK constraints are dis

abled upon creation. NOT NULL

constraints are enabled upon cre

ation by default.

If you specify a PCTINCREASE 	If you specify a PCTINCREASE

value for a rollback segment, 	value for a rollback segment,

ORACLE ignores this value and 	ORACLE returns an error.

uses a value of 0.

If you specify a MAXEXTENTS 	If you specify a MAXEXTENTS

value that exceeds the maximum 	value that exceeds the maximum

possible value based on the data 	possible value based on the data

block size, ORACLE ignores the 	block size, ORACLE returns an

specified value and uses the max	error.

imum possible value.

Table 7 - 1.  Differences Between V6 and V7 Compatibility Modes

There are additional differences between the V6 and V7 compatibility modes that are specific to the ORACLE Precompilers and the ORACLE Call Interfaces (OCIs). For information on these differences, see the Programmer's Guide to the ORACLE Precompilers and Programmer's Guide to the ORACLE Call Interfaces.

Migrating to ORACLE7

You may want to establish V6 compatibility mode when you initially upgrade to ORACLE7 in order ease the migration of your existing ORACLE Version 6 applications. Establishing V6 compatibility mode reduces (but does not eliminate) the number of changes you may have to make to your applications before running them on ORACLE7. Note that there is some SQL syntax supported by ORACLE Version 6 that is not supported by ORACLE7 in either V6 or V7 compatibility mode. If you have existing applications that you have run on ORACLE Version 6, see the ORACLE7 Server Migration  for a list of the changes that you must make to these applications before running them on ORACLE7.

You should eventually upgrade your applications so that they can be run in V7 compatibility mode, rather than V6 compatibility mode.

Establishing and Switching Between Compatibility Modes

By default, all sessions on ORACLE7 initially run in V7 compatibility mode. Some ORACLE application tools allow you to establish and switch between compatibility modes for your sessions. For information on how to establish and switch between compatibility modes, see the manual for the specific tool. For example, to find out how to switch between compatibility modes with SQL*Plus, see the SQL*Plus User's Guide and Reference.


APPENDIX B. SYNTAX

This appendix lists the syntax of SQL commands, clauses, and other constructs alphabetically. The syntax in this appendix is shown with BNF notation. For information on how to read BNF notation, see the Preface of this Manual. The equivalent syntax diagrams and a complete description of each command, clause, and construct are also shown throughout Chapter 2 "Elements of SQL", Chapter 3 "Operators, Functions, , and Chapter 4 "Commands" of this Manual.

ALTER CLUSTER

ALTER CLUSTER [schema.]cluster

[PCTUSED integer] [PCTFREE integer]

[SIZE integer [K|M] ]

[INITRANS integer] [MAXTRANS integer]

[STORAGE storage_clause]

[ALLOCATE EXTENT [( [SIZE integer [K|M] ]

[DATAFILE 'filename']

[INSTANCE integer] )]

ALTER DATABASE

ALTER DATABASE [database]

{ MOUNT [!!under!!EXCLUSIVE | PARALLEL]

| CONVERT

| OPEN [RESETLOGS | NORESETLOGS]

| ARCHIVELOG

| NOARCHIVELOG

| RECOVER recover_clause

| ADD LOGFILE [THREAD integer] [GROUP integer] filespec

                            [, [GROUP integer] filespec] ...

| ADD LOGFILE MEMBER 'filename' [REUSE]

[, 'filename' [REUSE]] ...

TO { GROUP integer

   | ('filename' [,'filename'] ...)

   |  'filename' }

 [, 'filename' [REUSE]

 [, 'filename' [REUSE]] ...

TO { GROUP integer

   | ('filename' [, 'filename'] ...)

   |  'filename' } ] ...

| DROP LOGFILE {  GROUP integer

               | ('filename' [, 'filename'] ...)

               |  'filename' }

           [,  {  GROUP integer

               | ('filename' [,'filename'] ...)

               |  'filename' } ] ...

| DROP LOGFILE MEMBER 'filename' [, 'filename'] ...

| RENAME FILE 'filename' [, 'filename'] ...

           TO 'filename' [, 'filename'] ...

| BACKUP CONTROLFILE TO { 'filename' [REUSE] 	                        | TRACE [!!under!!NORESETLOGS | RESETLOGS]

}

| CREATE DATAFILE 'filename' [, filename] ...

              [AS  filespec  [, filespec] ...

| DATAFILE 'filename' { ONLINE | OFFLINE [DROP] }

| ENABLE [PUBLIC] THREAD integer

| DISABLE         THREAD integer

| RENAME GLOBAL_NAME TO database[.domain]...

| RESET COMPATIBILITY

| SET { DBMAC {ON | OFF}

      | DBHIGH = 'text'

      | DBLOW  = 'text' } }

ALTER FUNCTION

ALTER FUNCTION [schema.]function

COMPILE

ALTER INDEX

ALTER INDEX [schema.]index

[INITRANS integer] [MAXTRANS integer]

[STORAGE storage_clause]

ALTER PACKAGE

ALTER PACKAGE [schema.]package

COMPILE [!!under!!PACKAGE | BODY]

ALTER PROCEDURE

ALTER PROCEDURE [schema.]procedure

COMPILE

ALTER PROFILE

ALTER PROFILE profile

LIMIT [SESSIONS_PER_USER {integer | UNLIMITED | DEFAULT}]

      [CPU_PER_SESSION

      	{integer | UNLIMITED | DEFAULT}]

      [CPU_PER_CALL

      	{integer | UNLIMITED | DEFAULT}]

      [CONNECT_TIME

      	{integer | UNLIMITED | DEFAULT}]

      [IDLE_TIME

      	{integer | UNLIMITED | DEFAULT}]

      [LOGICAL_READS_PER_SESSION

      	{integer | UNLIMITED | DEFAULT}]

      [LOGICAL_READS_PER_CALL

      	{integer | UNLIMITED | DEFAULT}]

      [COMPOSITE_LIMIT

      	{integer | UNLIMITED | DEFAULT}]

      [PRIVATE_SGA

      	{integer [K|M] | UNLIMITED | DEFAULT}]

ALTER RESOURCE COST

ALTER RESOURCE

COST [CPU_PER_SESSION           integer]

     [CONNECT_TIME              integer]

     [LOGICAL_READS_PER_SESSION integer]

     [PRIVATE_SGA               integer]

ALTER ROLE

ALTER ROLE role

{ NOT IDENTIFIED

| IDENTIFIED {BY password | EXTERNALLY }

ALTER ROLLBACK SEGMENT

ALTER ROLLBACK SEGMENT rollback_segment

{ ONLINE

| OFFLINE

| STORAGE storage_clause }

ALTER SEQUENCE

ALTER SEQUENCE [schema.]sequence

[INCREMENT BY integer]

[MAXVALUE integer | NOMAXVALUE]

[MINVALUE integer | NOMINVALUE]

[CYCLE | NOCYCLE]

[CACHE integer | NOCACHE]

[ORDER | NOORDER]

ALTER SESSION

ALTER SESSION

{ SET { SQL_TRACE              = { TRUE | FALSE }

      | GLOBAL_NAMES           = { TRUE | FALSE }

      | NLS_LANGUAGE           =   language

      | NLS_TERRITORY          =   territory

      | NLS_DATE_FORMAT        =  'fmt'

      | NLS_DATE_LANGUAGE      =   language

      | NLS_NUMERIC_CHARACTERS =  'text'

      | NLS_ISO_CURRENCY       =   territory

      | NLS_CURRENCY           =  'text'

      | NLS_SORT               = { sort  | BINARY }

      | LABEL                  = {'text' | DBHIGH |

    DBLOW | OSLABEL }

      | MLS_LABEL_FORMAT       =  'fmt'

      | OPTIMIZER_GOAL         =

      	{ RULE|ALL_ROWS|FIRST_ROWS|CHOOSE }

      	... }

| CLOSE DATABASE LINK dblink

| ADVISE {COMMIT | ROLLBACK | NOTHING}

| {ENABLE | DISABLE} COMMIT IN PROCEDURE }

ALTER SNAPSHOT

ALTER SNAPSHOT [schema.]snapshot

[PCTFREE  integer] [PCTUSED  integer]

[INITRANS integer] [MAXTRANS integer]

[STORAGE storage_clause]

[USING INDEX [INITRANS integer] [MAXTRANS integer]

[STORAGE storage_clause] ]

[REFRESH [FAST | COMPLETE | !!under!!FORCE]

[START WITH date] [NEXT date]]

ALTER SNAPSHOT LOG

ALTER SNAPSHOT LOG ON [schema.]table

[PCTFREE  integer]	[PCTUSED  integer]

[INITRANS integer]	[MAXTRANS integer]

[STORAGE storage_clause]

ALTER SYSTEM

ALTER SYSTEM

{ {ENABLE | DISABLE} RESTRICTED SESSION

| FLUSH SHARED_POOL

| {CHECKPOINT | CHECK DATAFILES}

    [!!under!!GLOBAL | LOCAL]

| SET { RESOURCE_LIMIT           = { TRUE | FALSE }

      | GLOBAL_NAMES             = { TRUE | FALSE }

      | MTS_DISPATCHERS          = 'protocol, integer'

      | MTS_SERVERS              = integer

      | LICENSE_MAX_SESSIONS     = integer

      | LICENSE_SESSIONS_WARNING = integer

      | LICENSE_MAX_USERS        = integer } ...

| SWITCH LOGFILE

| {ENABLE | DISABLE} DISTRIBUTED RECOVERY

| ARCHIVE LOG archive_log_clause

| KILL SESSION 'integer1, integer2' }

ALTER TABLE

ALTER TABLE [schema.]table

[ADD {    { column [datatype] [DEFAULT expr] 	      [column_constraint] ... | table_constraint }

       |  ( { column [datatype] [DEFAULT expr]

      [column_constraint] ... | table_constraint }

         [, { column [datatype] [DEFAULT expr]

      [column_constraint] ... | table_constraint } 	  ] ... ) } ]

[MODIFY {   column [datatype] [DEFAULT expr]

    [column_constraint] |  (column [datatype] 	    [DEFAULT expr] [column_constraint]

      [,  column [datatype] [DEFAULT expr]

      [column_constraint] ] ...) } ]

[PCTFREE  integer] [PCTUSED  integer]

[INITRANS integer] [MAXTRANS integer]

[STORAGE storage_clause]

[DROP drop_clause] ...

[ALLOCATE EXTENT [( [SIZE integer [K|M] ]

                    [DATAFILE 'filename']

                    [INSTANCE integer] )]

[ ENABLE   enable_clause

| DISABLE disable_clause ] ...

ALTER TABLESPACE

ALTER TABLESPACE tablespace

{ ADD DATAFILE filespec [, filespec] ...

| RENAME DATAFILE 'filename' [,'filename'] ...

               TO 'filename' [,'filename'] ...

| DEFAULT STORAGE storage_clause

| ONLINE

| OFFLINE [!!under!!NORMAL | TEMPORARY | IMMEDIATE]

| {BEGIN | END} BACKUP

| READ ONLY 	| READ WRITE }

ALTER TRIGGER

ALTER TRIGGER [schema.]trigger

{ ENABLE 	| DISABLE }

ALTER USER

ALTER USER user

[IDENTIFIED {BY password | EXTERNALLY}]

[DEFAULT TABLESPACE tablespace]

[TEMPORARY TABLESPACE tablespace]

[QUOTA {integer [K|M] | UNLIMITED} ON tablespace] ...

[PROFILE profile]

[DEFAULT ROLE { role [, role] ...

  | ALL [EXCEPT role [, role] ...] 	  | NONE}]

ALTER VIEW

ALTER VIEW [schema.]view

COMPILE

ANALYZE

ANALYZE

{ INDEX [schema.]index

{ { COMPUTE  STATISTICS

  | ESTIMATE STATISTICS [SAMPLE integer

  {ROWS | PERCENT}]

  | DELETE   STATISTICS }

| VALIDATE STRUCTURE }

| {TABLE [schema.]table | CLUSTER [schema.]cluster}

{ { COMPUTE  STATISTICS

  | ESTIMATE STATISTICS [SAMPLE integer

  {ROWS | PERCENT}]

  | DELETE   STATISTICS }

| VALIDATE STRUCTURE [CASCADE]

| LIST CHAINED ROWS [INTO [schema.]table] } }

ARCHIVE LOG clause

ARCHIVE LOG [THREAD integer]

{ { SEQ integer

  | CHANGE integer

  | CURRENT

  | GROUP integer

  | LOGFILE 'filename'

  | NEXT

  | ALL

  | START }

  [TO 'location']

| STOP }

AUDIT (SQL Statements)

AUDIT {statement_opt | system_priv}

[, {statement_opt | system_priv} ] ...

[BY user [, user] ...]

[BY {SESSION | ACCESS}]

[WHENEVER [NOT] SUCCESSFUL]

AUDIT(Schema Objects)

AUDIT object_opt [, object_opt] ...

ON { [schema.]object | DEFAULT }

[BY {SESSION | ACCESS}]

[WHENEVER [NOT] SUCCESSFUL]

CLOSE(Embedded SQL)

EXEC SQL CLOSE cursor

COMMENT

COMMENT ON {  TABLE [schema.]{table | view | snapshot}

| COLUMN [schema.]{table | view | snapshot}.column }

IS 'text'

COMMIT

COMMIT [WORK]

[ COMMENT 'text'

| FORCE 'text' [, integer] ]

COMMIT(Embedded SQL)

EXEC SQL [AT {db_name | :host_variable} ]

COMMIT [WORK]

[ [COMMENT 'text'] [RELEASE]

| FORCE 'text' [, integer] ]

Condition

Form I:

{ expr {= | != | ^= |  = | <> | > | < | >= | <=}

{expr | (subquery)} | expr_list {= | != | ^= |  = | <>} (subquery) }

Form II:

{ expr {= | != | ^= |  = | <> | > | < | >= | <=}

{ANY | SOME | ALL} {expr_list | (subquery)}

| expr_list {= | != | ^= |  = | <>}

{ANY | SOME | ALL} ( { expr_list [, expr_list] ...

  | subquery} ) }

Form III:

{ expr [NOT] IN {expr_list | (subquery)}

| expr_list [NOT] IN ( { expr_list [, expr_list]...

| subquery} ) }

Form IV:

expr [NOT] BETWEEN expr AND expr

Form V:

expr IS [NOT] NULL

Form VI:

EXISTS (subquery)

Form VII:

char1 [NOT] LIKE char2 [ESCAPE 'c']

Form VIII:

{ ( condition )

| NOT condition

| condition AND condition

| condition OR condition }

CONNECT (Embedded SQL)

EXEC SQL CONNECT { :user IDENTIFIED BY :password

| :user_password }

[ [AT {db_name | :host_variable} ] USING :connect_string]

CONSTRAINT clause

Column constraint:

[CONSTRAINT constraint]

{ [NOT] NULL

| {UNIQUE | PRIMARY KEY}

|  REFERENCES [schema.]table [(column)]

[ON DELETE CASCADE]

|  CHECK (condition) }

{ [ USING INDEX [PCTFREE integer]

[INITRANS integer] [MAXTRANS integer]

[TABLESPACE tablespace]

[STORAGE storage_clause] ]

[ EXCEPTIONS INTO [schema.]table

| DISABLE }

Table constraint:

[CONSTRAINT constraint]

{ {UNIQUE | PRIMARY KEY} (column [,column] ...)

|  FOREIGN KEY (column [,column] ...)

 REFERENCES [schema.]table [(column [,column] ...)]

[ON DELETE CASCADE]

| CHECK (condition) }

{ [ USING INDEX [PCTFREE integer]

[INITRANS integer] [MAXTRANS integer]

[TABLESPACE tablespace]

[STORAGE storage_clause] ]

[ EXCEPTIONS INTO [schema.]table[@dblink]

| DISABLE }

CREATE CLUSTER

CREATE CLUSTER [schema.]cluster

(column datatype [,column datatype] ... )

[PCTUSED integer] [PCTFREE integer]

[SIZE integer [K|M] ]

[INITRANS integer] [MAXTRANS integer]

[TABLESPACE tablespace]

[STORAGE storage_clause]

[!!under!!INDEX

| [HASH IS column] HASHKEYS integer]

CREATE CONTROLFILE

CREATE CONTROLFILE [REUSE]

[SET] DATABASE database

LOGFILE [GROUP integer] filespec [, [GROUP integer] 	  filespec] ...

{RESETLOGS | NORESETLOGS}

DATAFILE filespec [, filespec] ...

[MAXLOGFILES integer]

[MAXLOGMEMBERS integer]

[MAXLOGHISTORY integer]

[MAXDATAFILES integer]

[MAXINSTANCES integer]

[ARCHIVELOG | !!under!!NOARCHIVELOG]

CREATE DATABASE

CREATE DATABASE [database]

[CONTROLFILE REUSE]

[LOGFILE [GROUP integer] filespec [,

  [GROUP integer] filespec] ...]

[MAXLOGFILES integer ]

[MAXLOGMEMBERS integer]

[MAXLOGHISTORY integer]

[DATAFILE filespec [, filespec] ...]

[MAXDATAFILES integer]

[MAXINSTANCES integer]

[ARCHIVELOG | !!under!!NOARCHIVELOG]

[!!under!!EXCLUSIVE]

[CHARACTER SET charset]

CREATE DATABASE LINK

CREATE [PUBLIC] DATABASE LINK dblink

[CONNECT TO user IDENTIFIED BY password]

[USING 'dbstring']

CREATE FUNCTION

CREATE [OR REPLACE] FUNCTION [schema.]function

[ (argument [!!under!!IN] datatype

[, argument [!!under!!IN] datatype] ...)]

RETURN datatype

{IS | AS} pl/sql_subprogram_body

CREATE INDEX

CREATE INDEX [schema.]index

ON { [schema.]table (column [!!under!!ASC|DESC]

   [, column [!!under!!ASC|DESC]] ...)

   | CLUSTER [schema.]cluster }

[INITRANS integer] [MAXTRANS integer]

[TABLESPACE tablespace]

[STORAGE storage_clause]

[PCTFREE integer]

[NOSORT]

CREATE PACKAGE

CREATE [OR REPLACE] PACKAGE [schema.]package

{IS | AS} pl/sql_package_spec

CREATE PACKAGE BODY

CREATE [OR REPLACE] PACKAGE BODY [schema.]package

{IS | AS} pl/sql_package_body

CREATE PROCEDURE

CREATE [OR REPLACE] PROCEDURE [schema.]procedure

[ (argument [!!under!!IN | OUT | IN OUT] datatype

[, argument [!!under!!IN | OUT | IN OUT] datatype] ...)]

{IS | AS} pl/sql_subprogram_body

CREATE PROFILE

CREATE PROFILE profile

LIMIT [SESSIONS_PER_USER          {integer | UNLIMITED | 	DEFAULT}]

      [CPU_PER_SESSION            {integer | UNLIMITED | 	DEFAULT}]

      [CPU_PER_CALL               {integer | UNLIMITED | 	DEFAULT}]

      [CONNECT_TIME               {integer | UNLIMITED | 	DEFAULT}]

      [IDLE_TIME                  {integer | UNLIMITED | 	DEFAULT}]

      [LOGICAL_READS_PER_SESSION  {integer | UNLIMITED | 	DEFAULT}]

      [LOGICAL_READS_PER_CALL     {integer | UNLIMITED | 	DEFAULT}]

      [COMPOSITE_LIMIT            {integer | UNLIMITED | 	DEFAULT}]

      [PRIVATE_SGA          {integer [K|M] | UNLIMITED | 	DEFAULT}]

CREATE ROLE

CREATE ROLE role

[ !!under!!NOT IDENTIFIED

| IDENTIFIED {BY password | EXTERNALLY} ]

CREATE ROLLBACK SEGMENT

CREATE [PUBLIC] ROLLBACK SEGMENT rollback_segment

[TABLESPACE tablespace]

[STORAGE storage_clause]

CREATE SCHEMA

CREATE SCHEMA AUTHORIZATION schema

{ CREATE TABLE command

| CREATE VIEW command

| GRANT command } ...

CREATE SEQUENCE

CREATE SEQUENCE [schema.]sequence

[INCREMENT BY integer]

[START WITH integer]

[MAXVALUE integer | NOMAXVALUE]

[MINVALUE integer | !!under!!NOMINVALUE]

[CYCLE | NOCYCLE]

[CACHE integer | NOCACHE]

[ORDER | !!under!!NOORDER]

CREATE SNAPSHOT

CREATE SNAPSHOT [schema.]snapshot

[ [PCTFREE  integer] [PCTUSED  integer]

  [INITRANS integer] [MAXTRANS integer]

  [TABLESPACE tablespace]

  [STORAGE storage_clause]

| [CLUSTER cluster (column [, column]...) ]

  [ USING INDEX [PCTFREE integer]

[INITRANS integer] [MAXTRANS integer]

[TABLESPACE tablespace]

[STORAGE storage_clause] ]

[ REFRESH [FAST | COMPLETE | !!under!!FORCE]

  [START WITH date] [NEXT date]]

AS subquery

CREATE SNAPSHOT LOG

CREATE SNAPSHOT LOG ON [schema.]table

[PCTFREE  integer]	[PCTUSED  integer]

[INITRANS integer]	[MAXTRANS integer]

[TABLESPACE tablespace]

[STORAGE storage_clause]

CREATE SYNONYM

CREATE [PUBLIC] SYNONYM [schema.]synonym

FOR [schema.]object[@dblink]

CREATE TABLE

CREATE TABLE [schema.]table

 ( { column [datatype] [DEFAULT expr] [column_constraint] ...

   | table_constraint}

[, { column [datatype] [DEFAULT expr] [column_constraint] ...

   | table_constraint} ]...)

[ [PCTFREE  integer] [PCTUSED  integer]

  [INITRANS integer] [MAXTRANS integer]

  [TABLESPACE tablespace]

  [STORAGE storage_clause]

|  CLUSTER cluster (column [, column]...) ]

[ ENABLE   enable_clause

| DISABLE disable_clause ] ...

[AS subquery]

CREATE TABLESPACE

CREATE TABLESPACE tablespace

DATAFILE filespec [, filespec] ...

[DEFAULT STORAGE storage_clause]

[!!under!!ONLINE | OFFLINE]

CREATE TRIGGER

CREATE [OR REPLACE] TRIGGER [schema.]trigger

{BEFORE | AFTER}

{DELETE | INSERT | UPDATE [OF column [, column] ...]}

[OR {DELETE | INSERT | UPDATE [OF column [, column] ...]}] ...

ON [schema.]table

[ [REFERENCING { OLD [AS] old [NEW [AS] new]

               | NEW [AS] new [OLD [AS] old] } ]

 FOR EACH ROW

 [WHEN (condition)] ]

pl/sql_block

CREATE USER

CREATE USER user

IDENTIFIED {BY password | EXTERNALLY}

[DEFAULT TABLESPACE tablespace]

[TEMPORARY TABLESPACE tablespace]

[QUOTA {integer [K|M] | UNLIMITED} ON tablespace] ...

[PROFILE profile]

CREATE VIEW

CREATE [OR REPLACE] [FORCE | !!under!!NOFORCE] VIEW [schema.]view

[(alias [,alias]...)]

AS subquery

[WITH CHECK OPTION [CONSTRAINT constraint]]

dblink

database[.domain]...[@connection_qualifier]

DECLARE CURSOR (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable}]

  DECLARE cursor CURSOR

FOR {SELECT command | statement_name | block_name}

DECLARE DATABASE (Embedded SQL)

EXEC SQL DECLARE db_name DATABASE

DECLARE STATEMENT (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable}]

DECLARE {statement_name | block_name} STATEMENT

DECLARE TABLE (Embedded SQL)

EXEC SQL DECLARE table TABLE

( column datatype	 [ [DEFAULT expr] [NULL | NOT NULL]

 | NOT NULL [WITH DEFAULT] ]

[, column datatype [ [DEFAULT expr] [NULL | NOT NULL]        	 | NOT NULL [WITH DEFAULT] ] ] )

DELETE

DELETE [FROM] [schema.]{table | view}[@dblink] [alias]

[WHERE condition]

DELETE (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable}] [FOR :host_integer]

DELETE [FROM] [schema.]{table | view}[@dblink] [alias]

[WHERE {condition | CURRENT OF cursor} ]

DESCRIBE

 (Embedded SQL)

EXEC SQL DESCRIBE [BIND VARIABLES FOR  | SELECT LIST FOR]

{statement_name | block_name}

INTO descriptor

DISABLE clause

DISABLE { { UNIQUE (column [, column] ...)

    | PRIMARY KEY

    | CONSTRAINT constraint }

[CASCADE]

| ALL TRIGGERS }

DROP clause

DROP { PRIMARY KEY

| UNIQUE (column [, column] ...)

| CONSTRAINT constraint }

[CASCADE]

DROP CLUSTER

DROP CLUSTER [schema.]cluster

[INCLUDING TABLES [CASCADE CONSTRAINTS] ]

DROP DATABASE LINK

DROP [PUBLIC] DATABASE LINK dblink

DROP FUNCTION

DROP FUNCTION [schema.]function

DROP INDEX

DROP INDEX [schema.]index

DROP PACKAGE

DROP PACKAGE [BODY] [schema.]package

DROP PROCEDURE

DROP PROCEDURE [schema.]procedure

DROP PROFILE

DROP PROFILE profile

[CASCADE]

DROP ROLE

DROP ROLE role

DROP ROLLBACK SEGMENT

DROP ROLLBACK SEGMENT rollback_segment

DROP SEQUENCE

DROP SEQUENCE [schema.]sequence

DROP SNAPSHOT

DROP SNAPSHOT [schema.]snapshot

DROP SNAPSHOT LOG

DROP SNAPSHOT LOG ON [schema.]table

DROP SYNONYM

DROP [PUBLIC] SYNONYM [schema.]synonym

DROP TABLE

DROP TABLE [schema.]table

[CASCADE CONSTRAINTS]

DROP TABLESPACE

DROP TABLESPACE tablespace

[INCLUDING CONTENTS [CASCADE CONSTRAINTS]]

DROP TRIGGER

DROP TRIGGER [schema.]trigger

DROP USER

DROP USER user [CASCADE]

DROP VIEW

DROP VIEW [schema.]view

ENABLE clause

ENABLE { {UNIQUE (column [, column] ...)

|PRIMARY KEY

|CONSTRAINT constraint}

  [USING INDEX [INITRANS integer]

               [MAXTRANS integer]

               [TABLESPACE tablespace]

               [STORAGE storage_clause]

               [PCTFREE integer] ]

  [EXCEPTIONS INTO [schema.]table ]

| ALL TRIGGERS }

EXECUTE

(Prepared SQL Statements and PL/SQL Blocks)

(Embedded SQL)

EXEC SQL [FOR :host_integer]

EXECUTE {statement_name | block_name}

[USING { :host_variable

   [[INDICATOR] :indicator variable]

      [, :host_variable [[INDICATOR] 	   :indicator_variable] ] ...

       | DESCRIPTOR descriptor } ]

EXECUTE (Anonymous PL/SQL Blocks) (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable} ]

EXECUTE pl/sql_block END-EXEC

EXECUTE IMMEDIATE

(Embedded SQL)

EXEC SQL [AT {db_name | :host_variable} ]

EXECUTE IMMEDIATE {:host_string | 'text'}

EXPLAIN PLAN

EXPLAIN PLAN

[SET STATEMENT ID = 'text']

[INTO [schema.]table[@dblink]]

FOR statement

Expr

Form I:

{ [[schema.]{table | view | snapshot} .] {column|pseudo-column|ROWLABEL}

| 'text'

| number

| sequence.{CURRVAL | NEXTVAL}

| NULL }

Form II:

:host_variable [ [INDICATOR] :indicator_variable]

Form III:

function_name [( [DISTINCT | ALL] expr [, expr] ... )]

Form IV:

{ (expr) | +expr | -expr | PRIOR expr

| expr * expr | expr / expr

| expr + expr | expr - expr | expr || expr }

Decode_expr:

DECODE( expr, search, result [, search, result] ...

[, default] )

Expr_list:

(expr [, expr] ...)

FETCH (Embedded SQL)

EXEC SQL [FOR :host_integer]

FETCH cursor

{ INTO 	:host_variable

   [[INDICATOR] :indicator_variable]

[,	:host_variable

  [[INDICATOR] :indicator_variable] ] ...

| USING DESCRIPTOR descriptor }

Filespec

Data files:

'filename' [SIZE integer [K|M] ] [REUSE]

Redo log file groups:

{  'filename'

| ('filename' [, 'filename'] ...)}

[SIZE integer [K|M] ] [REUSE]

GRANT (System Privileges and Roles)

GRANT {system_priv | role} [, {system_priv | role}] ...

TO {user | role | PUBLIC} [, {user | role | PUBLIC}] ...

 	[WITH ADMIN OPTION]

GRANT (Object Privileges)

GRANT {object_priv | ALL [PRIVILEGES]} [ (column

[, column]...) ]

[, {object_priv | ALL [PRIVILEGES]} [ (column

[, column] ...) ] ] ...

ON [schema.]object

TO {user | role | PUBLIC} [, {user | role | PUBLIC}] ...

 	[WITH GRANT OPTION]

INSERT

INSERT INTO [schema.]{table | view}[@dblink]

[ (column [, column] ...) ]

{VALUES (expr [, expr] ...) | subquery}

INSERT

 (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable} ] [FOR :host_integer]

INSERT INTO [schema.]{table | view} [ (column [, column] ...) ] 	{VALUES (expr [, expr ] ...) | subquery}

Integer

digit[digit]...

LOCK TABLE

LOCK TABLE [schema.]{table | view}[@dblink]

 [, [schema.]{table | view}[@dblink] ]...

IN lockmode MODE

[NOWAIT]

NOAUDIT (SQL Statements)

NOAUDIT {statement_opt | system_priv}

[, {statement_opt | system_priv} ] ...

[BY user [, user] ...]

[WHENEVER [NOT] SUCCESSFUL]

NOAUDIT (Schema Objects)

NOAUDIT object_opt [, object_opt] ...

ON [schema.]object

[WHENEVER [NOT] SUCCESSFUL]

Number

[+|-]{digit[digit]...[.][digit]...

 |.digit[digit]...}[{e|E}[+|-]digit[digit]...]

OPEN (Embedded SQL)

EXEC SQL OPEN cursor

[USING {host_variable_list | DESCRIPTOR descriptor}]

PREPARE (Embedded SQL)

EXEC SQL PREPARE {statement_name | block_name}

FROM {:host_string | 'text'}

RECOVER clause

RECOVER [AUTOMATIC] [FROM 'location']

{ [DATABASE] [ UNTIL CANCEL

             | UNTIL TIME date

             | UNTIL CHANGE integer

             | USING BACKUP CONTROLFILE ]

| TABLESPACE tablespace [, tablespace] ...

| DATAFILE 'filename' [, 'filename'] ...

| LOGFILE 'filename'

| CONTINUE [DEFAULT]

| CANCEL }

RENAME

RENAME old TO new

REVOKE (System Privileges and Roles)

REVOKE {system_priv | role} [, {system_priv | role}] ...

FROM {user | role | PUBLIC}

  [, {user | role | PUBLIC}] ...

REVOKE (Object Privileges)

REVOKE {object_priv | ALL [PRIVILEGES]}

[, {object_priv | ALL [PRIVILEGES]} ] ...

ON [schema.]object

FROM {user | role | PUBLIC} [, {user | role | PUBLIC}] ... 	[CASCADE CONSTRAINTS]

ROLLBACK

ROLLBACK [WORK]

[ TO [SAVEPOINT] savepoint	| FORCE 'text' ]

ROLLBACK (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable} ]

ROLLBACK [WORK]

[ [TO [SAVEPOINT] savepoint] [RELEASE]

| FORCE 'text' ]

SAVEPOINT

SAVEPOINT savepoint

SAVEPOINT (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable} ] SAVEPOINT savepoint

SELECT

SELECT [DISTINCT | !!under!!ALL] { *

| { [schema.]{table | view | snapshot}.*

| expr [ [AS] c_alias ] }

[, { [schema.]{table | view | snapshot}.*

| expr [ [AS] c_alias ] } ] ... }

FROM { (subquery)

| [schema.]{table | view | snapshot}[@dblink] } [t_alias]

  [, { (subquery)

| [schema.]{table | view | snapshot}[@dblink] } 	  [t_alias] ] ...

[WHERE condition ]

[ [START WITH condition] CONNECT BY condition]

[GROUP BY expr [, expr] ...] [HAVING condition]

[{UNION | UNION ALL | INTERSECT | MINUS} SELECT command ]

[ORDER BY {expr | c_alias | position} [!!under!!ASC | DESC]

       [, {expr | c_alias | position}

   [!!under!!ASC | DESC]] ...]

[FOR UPDATE [OF [[schema.]{table | view}.]column

             [, [[schema.]{table | view}.]column] ...]

 [NOWAIT] ]

SELECT (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable} ] SELECT select_list

INTO :host_variable[[INDICATOR]:indicator_variable]

  [, :host_variable[[INDICATOR]:indicator_variable] ] ...

FROM table_list

[WHERE condition]

[ [START WITH condition] CONNECT BY condition]

[GROUP BY expr [, expr] ...] [HAVING condition]

[ {UNION | UNION ALL | INTERSECT | MINUS} SELECT command]

[ORDER BY {expr | c_alias | position}

  [!!under!!ASC | DESC]

[, {expr | c_alias | position}

  [!!under!!ASC | DESC]] ]...

[FOR UPDATE [OF [[schema.]{table | view}.]column

             [, [[schema.]{table | view}.]column] ...] 	[NOWAIT] ]

SET ROLE

SET ROLE { role [IDENTIFIED BY password]

[, role [IDENTIFIED BY password] ] ...

| ALL [EXCEPT role [, role] ...]

| NONE }

SET TRANSACTION

SET TRANSACTION

{ READ ONLY

| READ WRITE

| USE ROLLBACK SEGMENT rollback_segment }

STORAGE clause

STORAGE (	[INITIAL          integer [K|M] ]

      	[NEXT             integer [K|M] ]

[PCTINCREASE      integer]

[MINEXTENTS       integer]

[MAXEXTENTS       integer]

[OPTIMAL         {integer [K|M] | NULL}]

[FREELIST GROUPS  integer]

[FREELISTS        integer] )

Text

'[c | '']...'

TRUNCATE

TRUNCATE {TABLE [schema.]table | CLUSTER [schema.]cluster}

[ {!!under!!DROP | REUSE} STORAGE]

TYPE (Embedded SQL)

EXEC SQL TYPE type IS datatype

UPDATE

UPDATE [schema.]{table | view}[@dblink] [alias]

SET { (column [, column] ...) = (subquery)

|  column = { expr | (subquery) } }

 [,	{ (column [, column] ...) = (subquery)

|  column = { expr | (subquery) } } ] ...

[WHERE condition]

UPDATE (Embedded SQL)

EXEC SQL [AT {db_name | :host_variable} ]

  [FOR :host_integer]

UPDATE [schema.]{table | view}[@dblink] [alias]

SET { (column [, column] ...) = (subquery)

    |  column = { expr | (subquery) } }

 [, { (column [, column] ...) = (subquery)

|  column = { expr | (subquery) } } ] ...

[ WHERE {condition | CURRENT OF cursor}]

VAR

 (Embedded SQL)

EXEC SQL VAR host_variable IS datatype

EXEC SQL WHENEVER {NOT FOUND | SQLERROR | SQLWARNING}

{CONTINUE | GOTO label_name | STOP | DO routine_call}


APPENDIX C. ORACLE AND STANDARD SQL

This appendix discusses these topics:

•	ORACLE's conformance to the SQL standards established by industry standards governing bodies

•	ORACLE's extensions to standard SQL

•	locating extensions to standard SQL with the FIPS Flagger

________________________________________

Conformance with Standard SQL

This section declares ORACLE's conformance to the SQL standards established by these organizations:

•	American National Standards Institute (ANSI)

•	International Standards Organization (ISO)

•	United States Federal Government

Conformance with these standards is measured by the National Institute of Standards and Technology (NIST) "SQL Test Suite". NIST is an organization of the government of the United States of America.

ANSI and ISO Compliance

ANSI has adopted SQL as the standard language for relational database management systems as defined in the document ANSI X3.135-1989 "Database Language SQL with Integrity Enhancement", or ANSI SQL89. You can obtain a copy of the ANSI standard from this address:

 	American National Standards Institute

 	1430 Broadway

 	New York, NY  10018

 	USA

This standard has also been adopted by ISO in the document ISO 9075-1989 "Database Language SQL with Integrity Enhancement". You can obtain a copy of the ISO standard from the national standards bodies of countries that participate in the International Standards Organization.

ANSI has also adopted a standard for embedded SQL defined in the document ANSI X3.168-1989 "Database Language Embedded SQL".

The ANSI and ISO SQL standards require claims of conformance to state the type of conformance, the implemented facilities, and whether the Integrity Enhancement Feature is implemented. The ORACLE7 Server, the ORACLE Precompilers Version 1.5, and SQL*Module Version 1.0 provide conformance with the ANSI X3.135-1989/ISO 9075-1989 and ANSI X3.168-1989 standards:

•	Full SQL conformance to Level 2

 (including both SQL-DDL and SQL-DML)

•	Module Language

•	Embedded SQL Ada

•	Embedded SQL C

•	Embedded SQL COBOL

•	Embedded SQL FORTRAN

•	Embedded SQL Pascal

•	Embedded SQL PL/I

•	Full implementation of the Integrity Enhancement Feature

FIPS Compliance

The United States Federal Government has also adopted standard SQL in the Federal Information Processing Standard Publication (FIPS PUB) 127 "Database Language SQL". ORACLE complies completely with FIPS PUB 127, providing SQL conformance as described above. In addition, this information is provided with reference to Section 13 "Special Procurement Considerations" of FIPS PUB 127.

Section 13.1  Integrity Enhancement Feature

 ORACLE completely supports the integrity enhancement feature.

Section 13.2  Programming Language Interfaces

 The ORACLE Precompilers support the use of Embedded SQL. SQL*Module supports the use of Module Language. Support is provided for Ada, C, COBOL, FORTRAN, and Pascal.

Section 13.3  Style of Language Interface

 ORACLE with SQL*Module supports Module Language for Ada, C, COBOL, FORTRAN, and Pascal.  ORACLE with the ORACLE Precompilers supports Ada, C, COBOL, FORTRAN, and Pascal. The languages supported may vary depending on your operating system.

Section 13.4  Interactive SQL

ORACLE7 with SQL*Plus Version 3.1 (as well as other ORACLE tools) supports "direct invocation" of the following SQL commands, meeting the requirements of FIPS PUB 127-1:

•	CREATE TABLE command

•	CREATE VIEW command

•	GRANT command

•	INSERT command

•	SELECT command, with ORDER BY clause but not INTO clause

•	UPDATE command:  searched

•	DELETE command:  searched

•	COMMIT WORK command

Most other SQL commands described in this Manual are also supported interactively.

Section 13.5  Sizing for Database Constructs

Table 7 - 2 lists requirements identified in FIPS PUB 127-1 and how they are met by ORACLE7.

Length of an identifier (in bytes)	18	30

Length of CHARACTER datatype (in bytes)	240	255

Decimal precision of NUMERIC datatype	15	38

Decimal precision of DECIMAL datatype	15	38

Decimal precision of INTEGER datatype	9	38

Decimal precision of SMALLINT datatype	4	38

Binary precision of FLOAT datatype	20	126

Binary precision of REAL datatype	20	63

Binary precision of DOUBLE PRECISION datatype	30	126

Columns in a table	100	254

Values in an INSERT statement	100	254

Set clauses in an UPDATE statement 1	20	254

Length of a row 2, 3	2000	2(254)

+        231

+253(2000)

Columns in a UNIQUE constraint	6	16

Length of a UNIQUE constraint 2	120	4

Columns in a GROUP BY clause	6	No limit 5

Sort specification in ORDER BY clause	6	No limit 5

Columns in a referential integrity constraint	6	16

Tables referenced in a SQL statement	10	No limit

Cursors simultaneously open	10	6

Table 7 - 2.  Sizing for Database Constructs

1 The number of set clauses in an UPDATE statement refers to the number items separated by commas following the SET keyword.

2 The FIPS PUB defines the length of a collection of columns to be the sum of: twice the number of columns, the length of each character column in bytes, decimal precision plus 1 of each exact numeric column, binary precision divided by 4 plus 1 of each approximate numeric column.

3 The ORACLE limit for the maximum row length is based on the maximum length of a row containing a LONG value of length 2 gigabytes and 253 VARCHAR2 values, each of length 2000 bytes.

4 The ORACLE limit for a UNIQUE key is half the size of an ORACLE data block (specified by the initialization parameter DB_BLOCK_SIZE) minus some overhead.

5 ORACLE places no limit on the number of columns in a GROUP BY clause or the number of sort specifications in an ORDER BY clause. However, the sum of the sizes of all the expressions in either a GROUP BY or an ORDER BY clause is limited to the size of an ORACLE data block (specified by the initialization parameter DB_BLOCK_SIZE) minus some overhead.

6 The ORACLE limit for the number of cursors simultaneously opened is specified by the initialization parameter OPEN_CURSORS. The maximum value of this parameter depends on the memory available on your operating system and exceeds 100 in all cases.

Section 13.6  Character Data Values

ORACLE supports the ASCII character set (FIPS PUB 1-2) on most computers and the EBCDIC character set on IBM mainframe computers. ORACLE supports both single-byte and multi-byte character sets.

________________________________________

Extensions to Standard SQL

This section lists the additional features supported by ORACLE that extend beyond standard SQL "Database Language SQL with Integrity Enhancement". This section provides information on these parts of the SQL language:

•	commands

•	functions

•	operators

•	pseudocolumns

•	datatypes

•	names of schema objects

•	values

For information on the extensions to standard embedded SQL "Database Language Embedded SQL" supported by the ORACLE Precompilers, see the Programmer's Guide to the ORACLE Precompilers.

Commands

This section describes these additional commands and additional syntax and functionality of standard commands.

 Additional Commands

ORACLE supports these commands that are not part of standard SQL:

(list continued from the previous page)

 Additional Parts of Standard Commands

ORACLE supports additional syntax for some commands that are part of standard SQL.

COMMIT

The COMMIT command supports these additional clauses:

•	COMMENT clause

•	FORCE clause

Also, standard SQL requires a COMMIT statement to include the WORK keyword. ORACLE allows your COMMIT statements to either include or omit this keyword. Note that this keyword adds no functionality to the command.

CREATE TABLE

The CREATE TABLE command supports these additional parameters and clauses:

•	PCTFREE parameter

•	PCTUSED parameter

•	INITRANS parameter

•	MAXTRANS parameter

•	TABLESPACE parameter

•	STORAGE clause

•	CLUSTER clause

•	ENABLE clause

•	DISABLE clause

•	AS clause

CONSTRAINT Clause      The CONSTRAINT clause of the CREATE TABLE command supports these additional options and identifiers:

•	ON DELETE CASCADE option

•	ENABLE option

•	DISABLE option

•	CONSTRAINT identifier

CREATE VIEW

The CREATE VIEW command supports this additional syntax:

•	OR REPLACE option

•	FORCE and NOFORCE options

•	CONSTRAINT identifier with the WITH CHECK OPTION

If you omit column names from a CREATE VIEW statement, the column aliases that appear in the defining query are used for columns of the view. Standard SQL does not support column aliases in SELECT statements.

DELETE

The DELETE command supports this additional syntax:

•	Database links to delete rows from tables and views on remote databases

•	Table aliases for use with correlated queries

Also, standard SQL requires a DELETE statement to include the FROM keyword. ORACLE allows your DELETE statements to either include or omit this keyword. Note that this keyword adds no functionality to the command.

GRANT

The GRANT command (System Privileges and Roles) is an extension to standard SQL.

The GRANT command (Object Privileges) supports other privileges on other objects in addition to the DELETE, INSERT, REFERENCES, SELECT, and UPDATE privileges on tables and views supported by standard SQL. This command also supports granting object privileges to roles.

INSERT

The INSERT command supports the use of database links to insert rows into tables and views on remote databases.

ROLLBACK

The ROLLBACK command supports these additional clauses:

•	TO clause

•	FORCE clause

Also, standard SQL requires a ROLLBACK statement to include the WORK keyword. ORACLE allows your ROLLBACK statements to either include or omit this keyword. Note that this keyword adds no functionality to the command.

SELECT

The SELECT command supports these additional clauses and syntax:

•	START WITH clause

•	CONNECT BY clause

•	FOR UPDATE clause

•	Database links for querying tables, views, and snapshots on remote databases

•	Outer join operator (+) for performing outer joins

•	Column aliases in the select list

•	NULL in the select list

GROUP BY Clause      The GROUP BY clause of the SELECT command supports this additional syntax and functionality:

•	A SELECT statement that selects from a view whose defining query contains group functions or a GROUP BY clause can contain group functions and GROUP BY, HAVING, and WHERE clauses.

•	A SELECT statement can perform a join involving a view whose defining query contains a GROUP BY clause.

ORDER BY Clause      The ORDER BY clause of the SELECT command supports this additional syntax and functionality:

•	This clause can also specify any expression involving any columns in any tables or views that appear in the FROM clause, rather than only select list expressions or positions of select list expressions.

•	This clause can qualify a column name with its table or view name, using the syntax table.column or view.column.

Queries      Queries, or forms of the SELECT command that appear inside other SQL statements, support this additional functionality:

•	Queries can contain the GROUP BY clause.

•	Queries can select from views whose defining queries contain the GROUP BY clause.

UPDATE

The UPDATE command supports this additional syntax:

•	Database links to update data in tables and views on remote databases

•	Table aliases for use with correlated queries

•	Parenthesized lists of columns on the left side of the SET clause, rather than only single columns

•	Queries on the right side of the SET clause, rather than only expressions

The UPDATE command also supports this additional functionality:

•	An UPDATE statement that updates a view can contain a query.

•	A query within an UPDATE statement can refer to the table or view being updated.

•	If the columns of a view are based on both columns of the base table and expressions containing columns of the base table, an UPDATE statement can update values based on columns, but not values based on expressions. Standard SQL prohibits all updates to such views.

Functions

This section describes additional functions and additional functionality of standard functions.

 Additional Functions

The only standard SQL functions are AVG, COUNT, MAX, MIN, and SUM. ORACLE supports many additional functions that are not part of standard SQL. See section "Functions" on page NO TAG.

 Additional Functionality of Standard Functions

You can nest group functions in the select list of a SELECT statement, as in this example:

SELECT MIN(MAX(sal))

FROM emp

GROUP BY deptno

The depth of nesting cannot be more than that shown in the example.

You can also use a group function in a SELECT statement that queries a view whose defining query contains group functions or a GROUP BY clause.

Operators

This section describes additional operators and additional functionality of standard operators.

 Additional Operators

ORACLE supports these operators that are not part of standard SQL:

•	|| character operator (character concatenation)

•	!=, ^=, and = comparison operators (inequality)

•	MINUS set operator

•	INTERSECT set operator

•	(+) operator (outer join)

•	PRIOR operator

 Additional Functionality of Standard Operators

ORACLE supports additional functionality for standard SQL operators:

•	The left member of an expression containing the IN operator can be a parenthesized list of expressions, rather than only a single expression.

•	Any expression, rather than only a column, can be used with the comparison operators IS NULL and IS NOT NULL.

•	The pattern used with the LIKE operator can be any expression of datatype CHAR or VARCHAR2, rather than only a text literal.

Pseudocolumns

Pseudocolumns are values that behave like columns of a table but are not actually stored in the table. Pseudocolumns are supported by ORACLE, but are not part of standard SQL. For a list of pseudocolumns, see the section "Pseudocolumns" on page 2 - 37.

Datatypes

ORACLE supports these additional datatypes that are not part of standard SQL:

•	DATE

•	NUMBER

•	VARCHAR2

•	LONG

•	RAW

•	LONG RAW

•	ROWID

ORACLE also supports automatic conversion of values from one datatype to another that is not part of standard SQL.

Names of Schema Objects

ORACLE supports additional functionality for names of schema objects:

•	ORACLE supports names of maximum length 30 bytes, rather than 18 characters.

•	ORACLE allows you to enter names in either lowercase or uppercase, rather than only in lowercase. However, note that names are not case-sensitive unless they are in double quotes.

•	ORACLE supports names in double quotes. Quoted identifiers allow you to use:

•	names that are reserved words

•	names that are case-sensitive

•	names that contain spaces

•	ORACLE supports names that contain the special characters # and $ and repeated underscores (__).

Values

ORACLE allows you to use either uppercase "E" or lowercase "e" for exponential notation of numeric values, rather than only "E".

________________________________________

FIPS Flagger

In your ORACLE applications, you can use the extensions listed in the previous sections just as you can use standard SQL. If you are concerned with the portability of your applications to other implementations of SQL, use ORACLE's FIPS Flagger to locate ORACLE extensions to standard SQL in your embedded SQL programs. The FIPS Flagger is part of the ORACLE Precompilers and the SQL*Module compiler. For information on how to use the FIPS Flagger, see the Programmer's Guide to the ORACLE Precompilers or the SQL*Module User's Guide and Reference.


APPENDIX D. OPERATING SYSTEM SPECIFIC INFORMATION

This Manual occasionally refers to other ORACLE manuals that contain detailed information for using ORACLE only on a specific operating system. These ORACLE manuals are often called installation or user's guides, although the exact name may vary among operating systems. Throughout this Manual, occasions when you should refer to operating system specific ORACLE manuals are marked with the icon shown in the left margin.

This appendix lists all the references in this Manual to operating system specific Oracle manuals. If you are using ORACLE on multiple operating systems, this appendix can help you ensure that your SQL statements are portable. This appendix lists information on these topics:

•	parameter values

•	ROWID component lengths

•	concatenation operator character

•	names and locations of SQL scripts

•	security features

For the actual information on these topics appropriate for your operating system, see your ORACLE installation or user's guide.

________________________________________

Parameter Values

Many SQL commands contain parameters whose minimum, maximum, and default values vary depending on your operating system. This section lists these parameters.

CREATE CONTROLFILE Command Parameters

These parameter values for the CREATE CONTROLFILE command vary depending on your operating system:

•	MAXDATAFILES (default, maximum)

•	MAXINSTANCES (default, maximum)

•	MAXLOGFILES (default, maximum)

•	MAXLOGMEMBERS (default, maximum)

•	MAXLOGHISTORY (default)

CREATE DATABASE Command Parameters

These parameter values for the CREATE DATABASE command vary depending on your operating system:

•	DATAFILE (default)

•	LOGFILE (default)

•	MAXDATAFILES (default, maximum)

•	MAXINSTANCES (default, maximum)

•	MAXLOGFILES (default, minimum, maximum)

•	MAXLOGMEMBERS (default, maximum)

•	MAXLOGHISTORY (default)

•	CHARACTER SET (supported and default character sets)

STORAGE Parameters

These STORAGE parameter values vary depending on your operating system:

•	INITIAL (maximum)

•	NEXT (maximum)

•	MINEXTENTS (maximum)

•	PCTINCREASE (maximum)

•	OPTIMAL (maximum)

These parameters can appear in the STORAGE clause of statements that create or alter clusters, indexes, rollback segments, snapshots, snapshot logs, tables, or tablespaces.

________________________________________

ROWID Component Lengths

The lengths of the block and file components of ROWID values vary depending on your operating system.

________________________________________

Concatenation Operator Characters

Most operating systems use the two consecutive vertical bars (||) for the concatenation operator. However, some operating systems may use different characters for this operator.

________________________________________

Filenames and Locations

Oracle Corporation provides you with SQL scripts that create tables, views, packages, and roles that are referenced throughout this Manual. The exact names and locations of these scripts may vary depending on your operating system. Table 7 - 3 shows the common names of these scripts and the pages on which they are discussed.

Script	Page References

CATEXP.SQL	(X-REF HERE)

DBMSSNALP.SQL	(X-REF HERE)

DBMSSTDX.SQL	(X-REF HERE)

SQL.BSQ	(X-REF HERE)

UTLCHAIN.SQL	(X-REF HERE)

UTLEXCPT.SQL	(X-REF HERE)

UTLSAMPL.SQL	(X-REF HERE)

UTLXPLAN.SQL	(X-REF HERE)

Table 7 - 3.  Scripts with Operating System Specific Names

and Locations

________________________________________

Security Features

The use of these security features varies depending on your operating system:

•	Some operating systems provide facilities that grant operating system privileges to operating system users. You can use such facilities to grant roles to ORACLE users with the initialization parameter OS_ROLES.

•	The authorization of enabling roles that are created using the IDENTIFIED EXTERNALLY option of the CREATE ROLE statement varies depending on your operating system. On some operating systems, a user must specify a password when enabling the role with the SET ROLE command. Other operating systems verify the user without a password.

•	On some operating systems, ORACLE automatically creates special roles for database administration.