Unformatted Document Excerpt
Coursehero >>
California >>
Allan Hancock College >>
CS 3311
Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Reference
Release Oracle8i
SQL 2 (8.1.6)
December 1999 Part No. A76989-01
SQL Reference, Release 2 (8.1.6) Part No. A76989-01 Copyright 1996, 1999, Oracle Corporation. All rights reserved. Primary Author: Diana Lorentz
Contributors: Alan Downing, Alex Tsukerman, Alok Pareek, Amit Ganesh, Andrew Witkowski, Angela Amor, Ann Rhee, Aravind Yalamanchi, Ari Mozes, Arvind Nithrakashyap, Ashok Joshi, Ashwini Surpur, Bill Lee, Brian Wright, Carolyn Gray, Cetin Ozbutun, Chon Lei, Daniel Wong, Debbie Steiner, Edward Waugh, Eugene Chong, Franco Putzolu, Fred Zemke, Guhan Viswanathan, Hakkan Jakobsson, Harry Sun, Harvey Eneman, Ira Greenberg, Jack Raitto, Jags Srinivasan, Jerry Schwarz, Jianping Yang, Jim Finnerty, John Haydu, Juan Tellez, Karuna Muthiah, Lance Ashdown, Lilian Hobbs, Lois Price, Mark Johnson, Miclelle Cyran, Mohamed Zait, Mohamed Ziauddin, Muralidhar Krishnaprasad, Namit Jain, Nipun Agarwal, Peter Robson, Qin Yu, Rafi Ahmed, Randy Urbano, Ravi Murthy, Reema Al-Shaikh, Rick Anderson, Robert Jenkins, Rosanne Park, Ruth Baylis, Sanjay Kaluskar, Sankar Subramanian, Sashikanth Chandrasekaran, Sheri Blaisedell, Sriram Samu, Steve Harris, Steve Vivian, Subhransu Basu, Subramanian Muralidhar, Sukhjit Singh, Susan Kotsovolos, Tak Wang, Thong Bui, Thuvan Hoang, Vikas Arora, Vinay Srihari, Vishu Krishnamurthy, Vishy Karra, Wayne Smith, Wei Wang The Programs (which include both the software and documentation) contain proprietary information of Oracle Corporation; they are provided under a license agreement containing restrictions on use and disclosure and are also protected by copyright, patent, and other intellectual and industrial property laws. Reverse engineering, disassembly, or decompilation of the Programs is prohibited. The information contained in this document is subject to change without notice. If you find any problems in the documentation, please report them to us in writing. Oracle Corporation does not warrant that this document is error free. Except as may be expressly permitted in your license agreement for these Programs, no part of these Programs may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Oracle Corporation. If the Programs are delivered to the U.S. Government or anyone licensing or using the programs on behalf of the U.S. Government, the following notice is applicable: Restricted Rights Notice Programs delivered subject to the DOD FAR Supplement are "commercial computer software" and use, duplication, and disclosure of the Programs, including documentation, shall be subject to the licensing restrictions set forth in the applicable Oracle license agreement. Otherwise, Programs delivered subject to the Federal Acquisition Regulations are "restricted computer software" and use, duplication, and disclosure of the Programs shall be subject to the restrictions in FAR 52.227-19, Commercial Computer Software - Restricted Rights (June, 1987). Oracle Corporation, 500 Oracle Parkway, Redwood City, CA 94065. The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of such applications if the Programs are used for such purposes, and Oracle Corporation disclaims liability for any damages caused by such use of the Programs. Oracle is a registered trademark. All other company or product names mentioned are used for identification purposes only and may be trademarks of their respective owners.
Contents
Send Us Your Comments ................................................................................................................. xiii Preface........................................................................................................................................................... xv 1 Introduction
Lexical Conventions ........................................................................................................................... 1-4
2
Basic Elements of Oracle SQL
Literals .................................................................................................................................................. Datatypes ............................................................................................................................................. Format Models .................................................................................................................................. Nulls ................................................................................................................................................... Pseudocolumns ................................................................................................................................ Comments .......................................................................................................................................... Database Objects .............................................................................................................................. Schema Object Names and Qualifiers .......................................................................................... Referring to Schema Objects and Parts ....................................................................................... 2-2 2-9 2-38 2-54 2-56 2-62 2-68 2-72 2-76
3
Operators
Unary and Binary Operators ............................................................................................................ Precedence ........................................................................................................................................... Arithmetic Operators ........................................................................................................................ Concatenation Operator .................................................................................................................... Comparison Operators ...................................................................................................................... 3-1 3-2 3-3 3-3 3-5
iii
Logical Operators ............................................................................................................................. Set Operators ..................................................................................................................................... Other Built-In Operators ................................................................................................................. User-Defined Operators ..................................................................................................................
3-11 3-12 3-16 3-16
4
Functions
SQL Functions .................................................................................................................................... ABS ..................................................................................................................................................... ACOS .................................................................................................................................................. ADD_MONTHS ............................................................................................................................... ASCII .................................................................................................................................................. ASIN ................................................................................................................................................... ATAN .................................................................................................................................................. ATAN2 ................................................................................................................................................ AVG .................................................................................................................................................... BFILENAME ..................................................................................................................................... CEIL .................................................................................................................................................... CHARTOROWID ............................................................................................................................ CHR .................................................................................................................................................... CONCAT ............................................................................................................................................ CONVERT ......................................................................................................................................... CORR .................................................................................................................................................. COS ..................................................................................................................................................... COSH .................................................................................................................................................. COUNT .............................................................................................................................................. COVAR_POP ..................................................................................................................................... COVAR_SAMP.................................................................................................................................. CUME_DIST ..................................................................................................................................... DENSE_RANK ................................................................................................................................. DEREF ................................................................................................................................................ DUMP ................................................................................................................................................. EMPTY_[B | C]LOB ........................................................................................................................ EXP ...................................................................................................................................................... FIRST_VALUE .................................................................................................................................. FLOOR ............................................................................................................................................... 4-2 4-12 4-13 4-13 4-14 4-15 4-15 4-16 4-16 4-17 4-18 4-19 4-19 4-20 4-21 4-22 4-23 4-24 4-24 4-26 4-27 4-28 4-29 4-30 4-31 4-33 4-33 4-34 4-35
iv
GREATEST ........................................................................................................................................ GROUPING ...................................................................................................................................... HEXTORAW ..................................................................................................................................... INITCAP ............................................................................................................................................ INSTR ................................................................................................................................................ INSTRB .............................................................................................................................................. LAG .................................................................................................................................................... LAST_DAY ........................................................................................................................................ LAST_VALUE ................................................................................................................................... LEAD .................................................................................................................................................. LEAST ................................................................................................................................................ LENGTH ............................................................................................................................................ LENGTHB ......................................................................................................................................... LN ........................................................................................................................................................ LOG .................................................................................................................................................... LOWER .............................................................................................................................................. LPAD ................................................................................................................................................... LTRIM ................................................................................................................................................ MAKE_REF ....................................................................................................................................... MAX .................................................................................................................................................... MIN .................................................................................................................................................... MOD ................................................................................................................................................... MONTHS_BETWEEN .................................................................................................................... NEW_TIME ....................................................................................................................................... NEXT_DAY ........................................................................................................................................ NLS_CHARSET_DECL_LEN ........................................................................................................ NLS_CHARSET_ID ........................................................................................................................ NLS_CHARSET_NAME ................................................................................................................ NLS_INITCAP .................................................................................................................................. NLS_LOWER .................................................................................................................................... NLSSORT .......................................................................................................................................... NLS_UPPER ...................................................................................................................................... NTILE ................................................................................................................................................. NUMTODSINTERVAL ................................................................................................................... NUMTOYMINTERVAL .................................................................................................................
4-36 4-36 4-37 4-38 4-38 4-39 4-40 4-41 4-42 4-44 4-45 4-45 4-46 4-46 4-47 4-47 4-48 4-48 4-49 4-50 4-52 4-53 4-54 4-55 4-55 4-56 4-56 4-57 4-58 4-59 4-59 4-60 4-61 4-62 4-63
v
NVL ..................................................................................................................................................... 4-64 NVL2 ................................................................................................................................................... 4-65 PERCENT_RANK ............................................................................................................................ 4-66 POWER .............................................................................................................................................. 4-67 RANK ................................................................................................................................................. 4-67 RATIO_TO_REPORT ...................................................................................................................... 4-68 RAWTOHEX ..................................................................................................................................... 4-69 REF ...................................................................................................................................................... 4-70 REFTOHEX ........................................................................................................................................ 4-70 REGR_ (linear regression) functions ........................................................................................... 4-71 REPLACE ........................................................................................................................................... 4-78 ROUND (Number Function) ......................................................................................................... 4-79 ROUND (Date Function) ................................................................................................................ 4-79 ROW_NUMBER ............................................................................................................................... 4-80 ROWIDTOCHAR ............................................................................................................................ 4-81 RPAD .................................................................................................................................................. 4-82 RTRIM ................................................................................................................................................ 4-82 SIGN ................................................................................................................................................... 4-83 SIN ...................................................................................................................................................... 4-83 SINH ................................................................................................................................................... 4-84 SOUNDEX ......................................................................................................................................... 4-84 SQRT .................................................................................................................................................. 4-85 STDDEV ............................................................................................................................................ 4-86 STDDEV_POP .................................................................................................................................. 4-87 STDDEV_SAMP .............................................................................................................................. 4-88 SUBSTR ............................................................................................................................................. 4-90 SUBSTRB ........................................................................................................................................... 4-91 SUM .................................................................................................................................................... 4-91 SYS_CONTEXT ................................................................................................................................ 4-93 SYS_GUID ......................................................................................................................................... 4-97 SYSDATE ........................................................................................................................................... 4-98 TAN ..................................................................................................................................................... 4-98 TANH ................................................................................................................................................. 4-99 TO_CHAR (date conversion) ......................................................................................................... 4-99 TO_CHAR (number conversion) ................................................................................................ 4-100
vi
TO_DATE ........................................................................................................................................ TO_LOB ........................................................................................................................................... TO_MULTI_BYTE ......................................................................................................................... TO_NUMBER ................................................................................................................................. TO_SINGLE_BYTE ....................................................................................................................... TRANSLATE ................................................................................................................................... TRANSLATE ... USING ................................................................................................................ TRIM ................................................................................................................................................ TRUNC (Number Function) ........................................................................................................ TRUNC (Date Function) ............................................................................................................... UID ................................................................................................................................................... UPPER ............................................................................................................................................... USER ................................................................................................................................................ USERENV ........................................................................................................................................ VALUE .............................................................................................................................................. VAR_POP ........................................................................................................................................ VAR_SAMP ..................................................................................................................................... VARIANCE ..................................................................................................................................... VSIZE ............................................................................................................................................... ROUND and TRUNC Date Functions........................................................................................ User-Defined Functions ................................................................................................................
4-101 4-102 4-103 4-103 4-104 4-105 4-106 4-107 4-108 4-109 4-109 4-110 4-110 4-111 4-112 4-113 4-114 4-115 4-116 4-117 4-118
5
Expressions, Conditions, and Queries
Expressions .......................................................................................................................................... 5-1 Conditions ......................................................................................................................................... 5-14 Queries and Subqueries ................................................................................................................. 5-19
6
About SQL Statements
Summary of SQL Statements ........................................................................................................... 6-1 Finding the Right SQL Statement ................................................................................................... 6-5
7
SQL Statements
ALTER CLUSTER .............................................................................................................................. 7-2 ALTER DATABASE ........................................................................................................................... 7-6
vii
ALTER DIMENSION ...................................................................................................................... 7-25 ALTER FUNCTION ......................................................................................................................... 7-28 ALTER INDEX .................................................................................................................................. 7-30 ALTER JAVA ..................................................................................................................................... 7-45 ALTER MATERIALIZED VIEW / SNAPSHOT .......................................................................... 7-47 ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG ..................................................... 7-58 ALTER OUTLINE ............................................................................................................................ 7-63 ALTER PACKAGE ........................................................................................................................... 7-64 ALTER PROCEDURE ..................................................................................................................... 7-67 ALTER PROFILE .............................................................................................................................. 7-69 ALTER RESOURCE COST ............................................................................................................ 7-73 ALTER ROLE .................................................................................................................................... 7-76 ALTER ROLLBACK SEGMENT ................................................................................................... 7-78 ALTER SEQUENCE ......................................................................................................................... 7-81 ALTER SESSION ............................................................................................................................. 7-83 ALTER SNAPSHOT ....................................................................................................................... 7-100 ALTER SNAPSHOT LOG ............................................................................................................. 7-101 ALTER SYSTEM ............................................................................................................................. 7-102 ALTER TABLE ................................................................................................................................ 7-123 ALTER TABLESPACE ................................................................................................................... 7-176 ALTER TRIGGER .......................................................................................................................... 7-183 ALTER TYPE ................................................................................................................................... 7-186 ALTER USER .................................................................................................................................. 7-193 ALTER VIEW .................................................................................................................................. 7-198 ANALYZE ........................................................................................................................................ 7-200 ASSOCIATE STATISTICS ........................................................................................................... 7-210 AUDIT sql_statements .................................................................................................................. 7-213 AUDIT schema_objects ................................................................................................................. 7-221 CALL ................................................................................................................................................. 7-226 COMMENT ..................................................................................................................................... 7-228 COMMIT ......................................................................................................................................... 7-230 constraint_clause ............................................................................................................................ 7-233 CREATE CLUSTER ........................................................................................................................ 7-254 CREATE CONTEXT ...................................................................................................................... 7-261 CREATE CONTROLFILE ............................................................................................................. 7-263
viii
CREATE DATABASE .................................................................................................................... CREATE DATABASE LINK ......................................................................................................... CREATE DIMENSION ................................................................................................................. CREATE DIRECTORY .................................................................................................................. CREATE FUNCTION .................................................................................................................... CREATE INDEX ............................................................................................................................. CREATE INDEXTYPE ................................................................................................................... CREATE JAVA ................................................................................................................................ CREATE LIBRARY ........................................................................................................................ CREATE MATERIALIZED VIEW / SNAPSHOT .................................................................... CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG ................................................ CREATE OPERATOR ................................................................................................................... CREATE OUTLINE ....................................................................................................................... CREATE PACKAGE ...................................................................................................................... CREATE PACKAGE BODY ......................................................................................................... CREATE PROCEDURE ................................................................................................................ CREATE PROFILE ......................................................................................................................... CREATE ROLE ............................................................................................................................... CREATE ROLLBACK SEGMENT .............................................................................................. CREATE SCHEMA ........................................................................................................................ CREATE SEQUENCE .................................................................................................................... CREATE SNAPSHOT .................................................................................................................... CREATE SNAPSHOT LOG .......................................................................................................... CREATE SYNONYM .................................................................................................................... CREATE TABLE ............................................................................................................................. CREATE TABLESPACE ................................................................................................................ CREATE TEMPORARY TABLESPACE ..................................................................................... CREATE TRIGGER ....................................................................................................................... CREATE TYPE ................................................................................................................................ CREATE TYPE BODY ................................................................................................................... CREATE USER ............................................................................................................................... CREATE VIEW ............................................................................................................................... DELETE ............................................................................................................................................ DISASSOCIATE STATISTICS .................................................................................................... DROP CLUSTER ...........................................................................................................................
7-267 7-273 7-277 7-282 7-284 7-291 7-309 7-311 7-316 7-318 7-333 7-339 7-342 7-344 7-348 7-353 7-359 7-365 7-367 7-369 7-371 7-375 7-376 7-377 7-381 7-419 7-424 7-426 7-437 7-447 7-451 7-456 7-464 7-470 7-472
ix
DROP CONTEXT ........................................................................................................................... DROP DATABASE LINK ............................................................................................................. DROP DIMENSION ..................................................................................................................... DROP DIRECTORY ...................................................................................................................... DROP FUNCTION ........................................................................................................................ DROP INDEX ................................................................................................................................. DROP INDEXTYPE ....................................................................................................................... DROP JAVA ..................................................................................................................................... DROP LIBRARY ............................................................................................................................. DROP MATERIALIZED VIEW / SNAPSHOT ......................................................................... DROP MATERIALIZED VIEW LOG / SNAPSHOT LOG .................................................... DROP OPERATOR ........................................................................................................................ DROP OUTLINE ............................................................................................................................ DROP PACKAGE .......................................................................................................................... DROP PROCEDURE ..................................................................................................................... DROP PROFILE ............................................................................................................................. DROP ROLE ................................................................................................................................... DROP ROLLBACK SEGMENT .................................................................................................. DROP SEQUENCE ........................................................................................................................ DROP SNAPSHOT ........................................................................................................................ DROP SNAPSHOT LOG .............................................................................................................. DROP SYNONYM ......................................................................................................................... DROP TABLE .................................................................................................................................. DROP TABLESPACE ..................................................................................................................... DROP TRIGGER ........................................................................................................................... DROP TYPE .................................................................................................................................... DROP TYPE BODY ....................................................................................................................... DROP USER .................................................................................................................................... DROP VIEW ................................................................................................................................... EXPLAIN PLAN ............................................................................................................................. filespec .............................................................................................................................................. GRANT system_privileges_and_roles ........................................................................................ GRANT object_privileges ............................................................................................................. INSERT ............................................................................................................................................ LOCK TABLE ..................................................................................................................................
7-474 7-475 7-476 7-477 7-478 7-480 7-482 7-483 7-484 7-485 7-487 7-489 7-490 7-491 7-493 7-494 7-495 7-496 7-497 7-498 7-499 7-500 7-501 7-503 7-505 7-506 7-508 7-509 7-511 7-512 7-516 7-519 7-532 7-539 7-547
x
NOAUDIT sql_statements ........................................................................................................... NOAUDIT schema_objects .......................................................................................................... RENAME ......................................................................................................................................... REVOKE system_privileges_and_roles ...................................................................................... REVOKE schema_object_privileges ............................................................................................ ROLLBACK .................................................................................................................................... SAVEPOINT ................................................................................................................................... SELECT and Subqueries .............................................................................................................. SET CONSTRAINT(S) ................................................................................................................. SET ROLE ........................................................................................................................................ SET TRANSACTION ................................................................................................................... storage_clause ................................................................................................................................. TRUNCATE ..................................................................................................................................... UPDATE ...........................................................................................................................................
7-550 7-552 7-554 7-556 7-559 7-564 7-567 7-569 7-598 7-600 7-602 7-605 7-611 7-615
A B
Syntax Diagrams Oracle and Standard SQL
Conformance with Standard SQL ................................................................................................. B - 1 Oracle Extensions to Standard SQL ............................................................................................. B - 5
C
Oracle Reserved Words
xi
xii
Send Us Your Comments
SQL Reference, Release 2 (8.1.6)
Part No. A76989-01
Oracle Corporation welcomes your comments and suggestions on the quality and usefulness of this publication. Your input is an important part of the information used for revision.
s s s s s
Did you find any errors? Is the information clearly presented? Do you need more information? If so, where? Are the examples correct? Do you need more examples? What features did you like most about this manual?
If you find any errors or have any other suggestions for improvement, please indicate the chapter, section, and page number (if available). You can send comments to us in the following ways:
s s s
E-mail - infodev@us.oracle.com FAX - (650) 506-7228. Attn: Information Development Postal service: Oracle Corporation Server Technologies Documentation Manager 500 Oracle Parkway Redwood Shores, CA 94065 U.S.A.
If you would like a reply, please give your name, address, and telephone number below.
If you have problems with the software, please contact your local Oracle Support Services.
xiii
xiv
Preface
Well begun is half done. Aristotle, Nicomachean Ethics This reference contains a complete description of the Structured Query Language (SQL) used to manage information in an Oracle database. Oracle SQL is a superset of the American National Standards Institute (ANSI) and the International Standards Organization (ISO) SQL92 standard at entry level conformance.
See Also:
s
PL/SQL User's Guide and Reference for information on PL/SQL, Oracle's procedural language extension to SQL. Pro*C/C++ Precompiler Programmer's Guide, SQL*Module for Ada Programmer's Guide, and the Pro*COBOL Precompiler Programmer's Guide for detailed descriptions of Oracle embedded SQL.
s
Features and Functionality
Oracle8i SQL Reference contains information about the features and functionality of the Oracle8i and the Oracle8i Enterprise Edition products. Oracle8i and Oracle8i Enterprise Edition have the same basic features. However, several advanced features are available only with the Enterprise Edition, and some of these are optional.
See Also: Getting to Know Oracle8i for information about the differences between Oracle8i and the Oracle8i Enterprise Edition and the available features and options. That book also describes all the features that are new in Oracle8i.
xv
Audience
This reference is intended for all users of Oracle SQL.
What's New in Oracle8i?
Oracle8i contains many new features, which are documented throughout this reference. For a description of all features new to this release, see Getting to Know Oracle8i.
Release 8.1.5
The following top-level SQL statements are new to Release 8.1.5:
s
ALTER DIMENSION on page 7-25 ALTER JAVA on page 7-45 ALTER OUTLINE on page 7-63 ASSOCIATE STATISTICS on page 7-210 CALL on page 7-226 CREATE CONTEXT on page 7-261 CREATE DIMENSION on page 7-277 CREATE INDEXTYPE on page 7-309 CREATE JAVA on page 7-311 CREATE OPERATOR on page 7-339 CREATE OUTLINE on page 7-342 CREATE TEMPORARY TABLESPACE on page 4-424 DISASSOCIATE STATISTICS on page 7-470 DROP CONTEXT on page 7-474 DROP DIMENSION on page 7-476 DROP INDEXTYPE on page 7-482 DROP JAVA on page 7-483 DROP OPERATOR on page 7-489 DROP OUTLINE on page 7-490
s
s
s
s
s
s
s
s
s
s
s
s
s
s
s
s
s
s
xvi
Release 2 (8.1.6)
The following SQL functions are new to this release:
s
CORR on page 4-22 COVAR_POP COVAR_SAMP CUME_DIST DENSE_RANK FIRST_VALUE LAG LAST_VALUE LEAD NTILE NUMTOYMINTERVAL NUMTODSINTERVAL PERCENT_RANK RATIO_TO_REPORT REGR_ (linear regression) functions STDDEV_POP STDDEV_SAMP VAR_POP VAR_SAMP
s
s
s
s
s
s
s
s
s
s
s
s
s
s
s
s
s
s
In addition, the following features have been enhanced:
s
The aggregate functions have expanded functionality. See Aggregate Functions on page 4-6. When specifying LOB storage parameters, you can now specify caching of LOBs for read-only purposes. See "CREATE TABLE" on page 4-381. The section on Expressions now contains a new expression. See "CASE Expressions" on page 5-13.
s
s
xvii
s
Subqueries can now be unnested. See "Unnesting of Nested Subqueries" on page 5-25.
How this Reference Is Organized
This reference is divided into the following parts:
Volume 1
Chapter 1, "Introduction" This chapter defines SQL and describes its history as well as the advantages of using it to access relational databases. Chapter 2, "Basic Elements of Oracle SQL" This chapter describes the basic building blocks of an Oracle database and of Oracle SQL. Chapter 3, "Operators" This chapter describes how to use SQL operators to combine data into expressions and conditions. Chapter 4, "Functions" This chapter describes how to use SQL functions to combine data into expressions and conditions. Chapter 5, "Expressions, Conditions, and Queries" This chapter describes SQL expressions and conditions and discusses the various ways of extracting information from your database through queries. Chapter 6, "About SQL Statements" This chapter lists the various types of SQL statements, and provides a table to help you find the appropriate SQL statement for your database task.
Volume 2
Chapter 7, "SQL Statements" This chapter lists and describes all Oracle SQL statements in alphabetical order.
xviii
Appendix A, "Syntax Diagrams" This appendix describes how to read the syntax diagrams in this reference. Appendix B, "Oracle and Standard SQL" This appendix describes Oracle compliance with ANSI and ISO standards. Appendix C, "Oracle Reserved Words" This appendix lists words that are reserved for internal use by Oracle.
Structural Changes in the Reference in Release 8.1.5
Users familiar with the Release 8.0 documentation will find that the following sections have been moved or renamed:
s
The section "Format Models" now appears in Chapter 2 on page 2-38. Chapter 3 has been divided into several smaller chapters:
s
s
Chapter 3, "Operators" Chapter 4, "Functions" Chapter 5, "Expressions, Conditions, and Queries". The last section, "Queries and Subqueries" on page 5-19, provides background for the syntactic and semantic information in "SELECT and Subqueries" on page 7-569.
s
s
s
A new chapter, Chapter 6, "About SQL Statements", has been added to help you find the correct SQL statement for a particular task. The archive_log_clause is no longer a separate section, but has been incorporated into "ALTER SYSTEM" on page 7-102. The deallocate_unused_clause is no longer a separate section, but has been incorporated into "ALTER TABLE" on page 7-123, "ALTER CLUSTER" on page 7-2, and "ALTER INDEX" on page 7-30. The disable_clause is no longer a separate section, but has been incorporated into "CREATE TABLE" on page 4-381 and "ALTER TABLE" on page 7-123. The drop_clause is no longer a separate section. It has become the drop_constraint_clause of the ALTER TABLE statement (to distinguish it from the new drop_column_clause of that statement). See "ALTER TABLE" on page 7-123. The enable_clause is no longer a separate section, but has been incorporated into "CREATE TABLE" on page 4-381 and "ALTER TABLE" on page 7-123.
s
s
s
s
s
xix
s
The parallel_clause is no longer a separate section. The clause has been simplified, and has been incorporated into the various statements where it is relevant. The recover_clause is no longer a separate section. Recovery functionality has been enhanced, and because it is always implemented through the ALTER DATABASE statement, it has been incorporated into that section. See "ALTER DATABASE" on page 7-6. The sections on snapshots and snapshot logs have been moved and renamed. Snapshot functionality has been greatly enhanced, and these objects are now called materialized views. See "CREATE MATERIALIZED VIEW / SNAPSHOT" on page 318, "ALTER MATERIALIZED VIEW / SNAPSHOT" on page 7-47, "DROP MATERIALIZED VIEW / SNAPSHOT" on page 7-485, "CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG" on page 7-333, "ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG" on page 7-58, and "DROP MATERIALIZED VIEW LOG / SNAPSHOT LOG" on page 7-487. The section on subqueries has now been combined with the SELECT statement. See "SELECT and Subqueries" on page 7-569.
s
s
s
Conventions Used in this Reference
This section explains the conventions used in this book including:
s
Text Syntax Diagrams and Notation Code Examples Example Data
s
s
s
Text
The text in this reference adheres to the following conventions: UPPERCASE italics boldface Uppercase text calls attention to SQL keywords, filenames, and initialization parameters. Italicized text calls attention to parameters of SQL statements. Boldface text calls attention to definitions of terms.
xx
Syntax Diagrams and Notation
Syntax Diagrams This reference uses syntax diagrams to show SQL statements in Chapter 7, "SQL Statements", and to show other elements of the SQL language in Chapter 2, "Basic Elements of Oracle SQL", Chapter 3, "Operators", Chapter 4, "Functions", and Chapter 5, "Expressions, Conditions, and Queries". These syntax diagrams use lines and arrows to show syntactic structure, as shown here:
COMMENT ' text ' , WORK COMMIT FORCE ' text ' ; integer
If you are not familiar with this type of syntax diagram, refer to Appendix A, "Syntax Diagrams", for a description of how to read them. This section describes the components of syntax diagrams and gives examples of how to write SQL statements. Syntax diagrams are made up of these items: Keywords Keywords have special meanings in the SQL language. In the syntax diagrams, 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 placeholders 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 and provides examples of the values you might substitute for them in your statements:
xxi
Parameter table
Description The substitution value must be the name of an object of the type specified by the parameter. For a list of all types of objects, see the section, "Schema Objects" on page 2-68. The substitution value must be a single character from your database character set.
Examples emp
c 'text'
T s
The substitution value must be a text string in 'Employee records' single quotes. See the syntax description of 'text' in "Text" on page 2-2. The substitution value must be an expression of ename datatype CHAR or VARCHAR2 or a character 'Smith' literal in single quotes. The substitution value must be a condition that evaluates to TRUE or FALSE. See the syntax description of condition in "Conditions" on page 5-14. The substitution value must be a date constant or an expression of DATE datatype. ename >'A'
char
condition
date d
TO_DATE( '01-Jan-1994', 'DD-MON-YYYY')
expr
The substitution value can be an expression of sal + 1000 any datatype as defined in the syntax description of expr in "Expressions" on page 5-1. The substitution value must be an integer as defined by the syntax description of integer in "Integer" on page 2-3. 72
integer
number m n raw query
The substitution value must be an expression of AVG(sal) NUMBER datatype or a number constant as 15 * 7 defined in the syntax description of number in "Number" on page 2-4. The substitution value must be an expression of HEXTORAW('7D') datatype RAW. The substitution value must be a SELECT statement that will be used in another SQL statement. See "SELECT and Subqueries" on page 7-569. The substitution value must be the name of a nondefault database in an embedded SQL program. SELECT ename FROM emp
db_name
sales_db
xxii
Parameter db_string
Description The substitution value must be the database identification string for a Net8 database connection. For details, see the user's guide for your specific Net8 protocol.
Examples
Code Examples
This reference contains many examples of SQL statements. These examples show you how to use elements of SQL. The following example shows a CREATE TABLE statement:
CREATE TABLE accounts ( accno NUMBER, owner VARCHAR2(10), balance NUMBER(7,2) );
Code examples appear in a different font than the text. Examples follow these conventions:
s
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. PL/SQL blocks appear in italics. Keywords and parameters in these blocks may not be documented in this reference unless they are also SQL keywords and parameters. For more information see PL/SQL User's Guide and Reference.
s
s
Many examples assume the existence of objects that are not created in the example itself. The examples will not work as expected unless you first create those underlying objects. SQL is not case sensitive (except for quoted identifiers), so you need not follow these conventions when writing your own SQL statements. However, 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, the code examples in this reference were issued through SQL*Plus, and therefore are terminated with a semicolon (;). If you issue these example statements to Oracle, you must terminate them with the special character expected by the Oracle tool you are using.
xxiii
Example Data
Many of the examples in this reference operate on sample tables. The definitions of some of these tables appear in a SQL script available on your distribution medium. On most operating systems the name of this script is UTLSAMPL.SQL, although its exact name and location depend on your operating system. This script creates sample users and creates these sample tables in the schema of the user SCOTT (password TIGER):
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 dept ); 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 ------10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC --------NEW YORK DALLAS CHICAGO BOSTON
SELECT * FROM emp; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
xxiv
----7369 7499 7521 7566 7654 7698 7782 7788 7839 7844 7876 7900 7902 7934
------SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER
--------- ------ --------- ------ ------ ------CLERK 7902 17-DEC-80 800 20 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 22-FEB-81 1250 500 30 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 2450 10 ANALYST 7566 19-APR-87 3000 20 PRESIDENT 17-NOV-81 5000 10 SALESMAN 7698 08-SEP-81 1500 30 CLERK 7788 23-MAY-87 1100 20 CLERK 7698 03-DEC-81 950 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7782 23-JAN-82 1300 10
SELECT * FROM salgrade; GRADE ----1 2 3 4 5 LOSAL ----700 1201 1401 2001 3001 HISAL ----1200 1400 2000 3000 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 our references. As we write, revise, and evaluate, your opinions are the most important input we receive. At the front of this reference 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 is missing, or you would like to contact us, please use the following address or fax number: Server Technologies Documentation Manager Oracle Corporation 500 Oracle Parkway Redwood City, CA 94065 FAX: 650-506-7228
xxv
You can also e-mail your comments to the Information Development department at the following e-mail address: infodev@us.oracle.com
xxvi
1
Introduction
The chief merit of language is clearness . . . . Galen, On the Natural Faculties Structured Query Language (SQL) is the set of statements with which all programs and users access data in an Oracle database. Application programs and Oracle tools often allow users access to the database without using SQL directly, but these applications in turn must use SQL when executing the user's request. This chapter provides background information on SQL as used by most relational database systems. Topics include:
s
History of SQL SQL Standards Embedded SQL Lexical Conventions Tools Support
s
s
s
s
History of SQL
Dr. E. F. Codd published the paper, "A Relational Model of Data for Large Shared Data Banks", in June 1970 in the Association of Computer Machinery (ACM) journal, Communications of the ACM. Codd's model is now accepted as the definitive model for relational database management systems (RDBMS). The language, Structured English Query Language ("SEQUEL") was developed by IBM Corporation, Inc., to use Codd's model. SEQUEL later became SQL (still pronounced "sequel"). In 1979, Relational Software, Inc. (now Oracle Corporation) introduced the first commercially available implementation of SQL. Today, SQL is accepted as the standard RDBMS language.
Introduction 1-1
SQL Standards
Oracle Corporation strives to comply with industry-accepted standards and participates actively in SQL standards committees. Industry-accepted committees are the American National Standards Institute (ANSI) and the International Standards Organization (ISO), which is affiliated with the International Electrotechnical Commission (IEC). Both ANSI and the ISO/IEC have accepted SQL as the standard language for relational databases. When a new SQL standard is simultaneously published by these organizations, the names of the standards conform to conventions used by the organization, but the standards are technically identical. The latest SQL standard was adopted in July 1999 and is often called SQL-99. The formal names of this standard are:
s
ANSI X3.135-1999, "Database Language SQL", Parts 1 ("Framework"), 2 ("Foundation"), and 5 ("Bindings") ISO/IEC 9075:1999, "Database Language SQL", Parts 1 ("Framework"), 2 ("Foundation"), and 5 ("Bindings")
s
SQL-99 replaced the previous version of the standard, commonly known as SQL-92. SQL-99 is an upward compatible extension of SQL-92, except for a few minor incompatibilities noted in Annex E of Part 2, "Foundation," of SQL-99. SQL-92 defined four levels of compliance: Entry, Transitional, Intermediate, and Full. A conforming SQL implementation must support at least Entry SQL. Oracle8i fully supports Entry SQL as outlined in Federal Information Processing Standard (FIPS) PUB 127-2, and has many features that conform to Transitional, Intermediate, or Full SQL. The minimal conformance level for SQL-99 is known as Core. Core SQL-99 is a superset of SQL-92 Entry Level specification. Oracle8i also is broadly compatible with the SQL-99 Core specification. However, some SQL-99 Core features are not currently implemented in Oracle8i or differ from the Oracle8i implementation. Oracle Corporation is committed to fully supporting SQL-99 Core functionality in a future release, while providing upward compatibility for existing applications.
See Also: Appendix B, "Oracle and Standard SQL" for more
information about Oracle and standard SQL.
How SQL Works
The strengths of SQL provide benefits for all types of users, including application programmers, database administrators, managers, and end users. Technically
1-2 SQL Reference
speaking, SQL is a data sublanguage. The purpose of SQL is to provide an interface to a relational database such as Oracle, and all SQL statements are instructions to the database. In this SQL differs from general-purpose programming languages like C and BASIC. Among the features of SQL are the following:
s
It processes sets of data as groups rather than as individual units. It provides automatic navigation to the data. It uses statements that are complex and powerful individually, and that therefore stand alone. Flow-control statements were not part of SQL originally, but they are found in the recently accepted optional part of SQL, ISO/IEC 90755: 1996. Flow-control statements are commonly known as "persistent stored modules" (PSM), and Oracle's PL/SQL extension to SQL is similar to PSM.
s
s
Essentially, SQL lets you work with data at the logical level. You need to be concerned with the implementation details only when you want to manipulate the data. For example, to retrieve a set of rows from a table, you define a condition used to filter the rows. All rows satisfying the condition are retrieved in a single step and can be passed as a unit to the user, to another SQL statement, or to an application. You need not deal with the rows one by one, nor do you have to worry about how they are physically stored or retrieved. All SQL statements use the optimizer, a part of Oracle that determines the most efficient means of accessing the specified data. Oracle also provides techniques that you can use to make the optimizer perform its job better. SQL provides statements for a variety of tasks, including:
s
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
s
s
s
s
SQL unifies all of the above tasks in one consistent language.
Common Language for All Relational Databases
All major relational database management systems support SQL, so you can transfer all skills you have gained with SQL from one database to another. In addition, all programs written in SQL are portable. They can often be moved from one database to another with very little modification.
Introduction 1-3
Lexical Conventions
Embedded SQL
Embedded SQL refers to the use of standard SQL statements embedded within a procedural programming language. The embedded SQL statements are documented in the Oracle precompiler books: Pro*C/C++ Precompiler Programmer's Guide, Pro*COBOL Precompiler Programmer's Guide, and SQL*Module for Ada Programmer's Guide. Embedded SQL is a collection of these statements:
s
All SQL commands, such as SELECT and INSERT, available with SQL with interactive tools Dynamic SQL execution commands, such as PREPARE and OPEN, which integrate the standard SQL statements with a procedural programming language
s
Embedded SQL also includes extensions to some standard SQL statements. 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:
s
Pro*C/C++ precompiler Pro*COBOL precompiler SQL*Module for ADA
See Also: For a definition of the Oracle precompilers and the
s
s
embedded SQL statements, see SQL*Module for Ada Programmer's Guide, Pro*C/C++ Precompiler Programmer's Guide, and Pro*COBOL Precompiler Programmer's Guide.
Lexical Conventions
The following lexical conventions for issuing SQL statements apply specifically to Oracle's implementation of SQL, but are generally acceptable in 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 statement. Thus, Oracle evaluates the following two statements in the same manner:
SELECT ENAME,SAL*12,MONTHS_BETWEEN(HIREDATE,SYSDATE) FROM EMP;
1-4 SQL Reference
Lexical Conventions
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 in "Text" on page 2-2.
Tools Support
Most (but not all) Oracle tools support all features of Oracle SQL. This reference describes the complete functionality of SQL. 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 SQL*Plus User's Guide and Reference. If you are using Trusted Oracle, see your Trusted Oracle documentation for information about SQL statements specific to that environment.
Introduction 1-5
Lexical Conventions
1-6 SQL Reference
2
Basic Elements of Oracle SQL
Once the whole is divided, the parts need names. Lao Tsu, Tao Te Ching: Thirty-Two This chapter contains reference information on the basic elements of Oracle SQL. These elements are simplest building blocks of SQL statements. Therefore, before using the statements described in Chapter 7, "SQL Statements", you should familiarize yourself with the concepts covered in this chapter, as well as in Chapter 3, "Operators", Chapter 4, "Functions", Chapter 5, "Expressions, Conditions, and Queries", and Chapter 6, "About SQL Statements":
s
Literals
s
Text Integer Number Interval
s
s
s
s
Datatypes Format Models Nulls Pseudocolumns Comments Database Objects Schema Object Names and Qualifiers Referring to Schema Objects and Parts
s
s
s
s
s
s
s
Basic Elements of Oracle SQL 2-1
Literals
Literals
The terms literal and constant value are synonymous 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 quotation marks, which enable 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, national character literals with the N'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 sections that follow.
Text
Text specifies 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 statements in other parts of this reference. The syntax of text is as follows:
text::=
N ' c '
where N specifies representation of the literal using the national character set. Text entered using this notation is translated into the national character set by Oracle when used. is any member of the user's character set, except a single quotation mark ('). are two single quotation marks that begin and end text literals. To represent one single quotation mark within a literal, enter two single quotation marks.
c ''
A text literal must be enclosed in single quotation marks. This reference uses the terms text literal and character literal interchangeably. Text literals have properties of both the CHAR and VARCHAR2 datatypes:
2-2 SQL Reference
Literals
s
Within expressions and conditions, Oracle treats text literals as though they have the datatype CHAR by comparing them using blank-padded comparison semantics. See "Blank-Padded Comparison Semantics" on page 2-33. A text literal can have a maximum length of 4000 bytes.
s
Here are some valid text literals:
'Hello' 'ORACLE.dbs' 'Jackie''s raincoat' '09-MAR-98' N'nchar literal'
See Also: "Expressions" on page 5-1 for the syntax description of
expr.
Integer
You must use the integer notation to specify an integer whenever integer appears in expressions, conditions, SQL functions, and SQL statements described in other parts of this reference. The syntax of integer is as follows:
integer::=
+ digit
where digit is one of 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.
An integer can store a maximum of 38 digits of precision. Here are some valid integers:
7 +255
Basic Elements of Oracle SQL 2-3
Literals
See Also: "Expressions" on page 5-1 for the syntax description of
expr.
Number
You must use the number notation to specify values whenever number appears in expressions, conditions, SQL functions, and SQL statements in other parts of this reference. The syntax of number is as follows: number::=
+ . + E e digit digit digit
.
digit
where +, digit e, E indicates a positive or negative value. If you omit the sign, a positive value is the default. is one of 0, 1, 2, 3, 4, 5, 6, 7, 8 or 9. indicates that the number is specified in scientific notation. The digits after the E specify the exponent. The exponent can range from -130 to 125.
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 example, if the NLS_NUMERIC_CHARACTERS parameter specifies a decimal character of comma, specify the number 5.123 as follows:
'5,123'
2-4 SQL Reference
Literals
See Also: "ALTER SESSION" on page 7-83 and Oracle8i Reference.
Here are some valid representations of number:
25 +6.34 0.5 25e-03 -1
See Also: "Expressions" on page 5-1 for the syntax description of
expr.
Interval
An interval literal specifies a period of time. You can specify these differences in terms of years and months, or in terms of days, hours, minutes, and seconds. Oracle supports two types of interval literals, YEAR TO MONTH and DAY TO SECOND. Each type contains a leading field and may contain a trailing field. The leading field defines the basic unit of date or time being measured. The trailing field defines the smallest increment of the basic unit being considered. For example, a YEAR TO MONTH interval considers an interval of years to the nearest month. A DAY TO MINUTE interval considers an interval of days to the nearest minute. If you have date data in numeric form, you can use the NUMTOYMINTERVAL or NUMTODSINTERVAL conversion function to convert the numeric data into interval literals. Interval literals are used primarily with analytic functions.
See Also:
s
"Analytic Functions" on page 4-7 and Oracle8i Data Warehousing Guide. "NUMTODSINTERVAL" on page 4-62 and "NUMTOYMINTERVAL" on page 4-63.
s
Basic Elements of Oracle SQL 2-5
Literals
INTERVAL YEAR TO MONTH
Specify YEAR TO MONTH interval literals using the following syntax:
INTERVAL ' integer integer ' YEAR TO YEAR MONTH ( precision ) MONTH
where
s
'integer [-integer]' specifies integer values for the leading and optional trailing field of the literal. If the leading field is YEAR and the trailing field is MONTH, the range of integer values for the month field is 0 to 11. precision is the number of digits in the leading field. The valid range of the leading field precision is 0 to 9 and its default value is 2.
s
Restriction: The leading field must be a larger time element than the trailing field.
For example, INTERVAL '0-1' MONTH TO YEAR is not valid. The following INTERVAL YEAR TO MONTH literal indicates an interval of 123 years, 2 months:
INTERVAL '123-2' YEAR(3) TO MONTH
Examples of the other forms of the literal follow, including some abbreviated versions:
INTERVAL '123-2' YEAR(3) TO MONTH
indicates an interval of 123 years, 2 months. You must specify the leading field precision if it is greater than the default of 2 digits. indicates an interval of 123 years 0 months. indicates an interval of 300 months. maps to INTERVAL '4-0' YEAR TO MONTH and indicates 4 years.
INTERVAL '123' YEAR(3) INTERVAL '300' MONTH(3) INTERVAL '4' YEAR
2-6 SQL Reference
Literals
INTERVAL '50' MONTH
maps to INTERVAL '4-2' YEAR TO MONTH and indicates 50 months or 4 years 2 months. returns an error, because the default precision is 2, and '123' has 3 digits.
INTERVAL '123' YEAR
You can add or subtract one INTERVAL YEAR TO MONTH literal to or from another to yield another INTERVAL YEAR TO MONTH literal. For example:
INTERVAL '5-3' YEAR TO MONTH + INTERVAL '20' MONTH TO MONTH = INTERVAL '6-11' YEAR TO MONTH
INTERVAL DAY TO SECOND
Specify DAY TO SECOND interval literals using the following syntax:
integer INTERVAL ' integer time_expr DAY HOUR MINUTE , ( SECOND DAY HOUR TO MINUTE ( SECOND fractional_seconds_precision ) leading_precision fractional_second_precision ) time_expr '
(
leading_precision
)
where
s
integer specifies the number of days. If this value contains more digits than the number specified by the leading precision, Oracle returns an error.
Basic Elements of Oracle SQL 2-7
Literals
s
time_expr specifies a time in the format HH[:MI[:SS[.n]]]or MI[:SS[.n]] or SS[.n], where n specifies the fractional part of a second. If n contains more digits than the number specified by fractional_seconds_precision, then n is rounded to the number of digits specified by the fractional_seconds_precision value. You can specify time_expr following an integer and a space only if the leading field is DAY. day_precision is the number of digits in the DAY date field. Accepted values are 0 to 9. The default is 2. fractional_seconds_precision is the number of digits in the fractional part of the SECOND datetime field. Accepted values are 1 to 9. The default is 6.
s
s
Restriction: The leading field must be a larger time element than the trailing field.
For example, INTERVAL MINUTE TO DAY is not valid. As a result of this restriction, if SECOND is the leading field, the interval literal cannot have any trailing field. The valid range of values for the trailing field are as follows: HOUR MINUTE SECOND 0 to 23 0 to 59 0 to 59.999999999
Examples of the various forms of INTERVAL DAY TO SECOND literals follow, including some abbreviated versions: INTERVAL '4 5:12:10.222' DAY(3) TO SECOND(3) INTERVAL '4 5:12' DAY TO MINUTE INTERVAL '400 5' DAY(3) TO HOUR INTERVAL '400' DAY(3) indicates 4 days, 5 hours, 12 minutes, 10 seconds, and 222 thousandths of a second. indicates 4 days, 5 hours and 12 minutes. indicates 400 days 5 hours. indicates 400 days.
INTERVAL '11:12:10.2222222' HOUR indicates 11 hours, 12 minutes, and TO SECOND(7) 10.2222222 seconds. INTERVAL '11:20' HOUR TO MINUTE INTERVAL '10' HOUR INTERVAL '10:22' MINUTE TO SECOND indicates 11 hours and 20 minutes. indicates 10 hours. indicates 10 minutes 22 seconds.
2-8 SQL Reference
Datatypes
INTERVAL '10' MINUTE INTERVAL '4' DAY INTERVAL '25' HOUR INTERVAL '40' MINUTE INTERVAL '120' HOUR(3) INTERVAL '30.12345' SECOND(2,4)
indicates 10 minutes. indicates 4 days. indicates 25 hours. indicates 40 minutes. indicates 120 hours indicates 30.1235 seconds. The fractional second '12345' is rounded to '1235' because the precision is 4.
You can add or subtract one DAY TO SECOND interval literal from another DAY TO SECOND literal. For example.
INTERVAL '20' DAY - INTERVAL '240' HOUR = INTERVAL '10' DAY
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 a datatype for each of its columns. When you create a procedure or stored function, you must specify a 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-98' into a DATE column, Oracle treats the '01-JAN-98' character string as a DATE value after verifying that it translates to a valid date. Oracle provides a number of built-in datatypes as well as several categories for user-defined types, as shown in Figure 21.
Basic Elements of Oracle SQL 2-9
Datatypes
Figure 21 Oracle Type Categories
Built-in Datatypes User-defined type category structured type category object types collection type category varrays nested tables REFS (to object types)
The syntax of the Oracle built-in datatypes appears in the next diagram. Table 21 summarizes Oracle built-in datatypes. The rest of this section describes these datatypes as well as the various kinds of user-defined types.
Note: The Oracle precompilers recognize other datatypes in embedded
SQL programs. These datatypes are called external datatypes and are associated with host variables. Do not confuse built-in and user-defined datatypes with external datatypes. For information on external datatypes, including how Oracle converts between them and built-in or user-defined datatypes, see Pro*COBOL Precompiler Programmer's Guide, Pro*C/C++ Precompiler Programmer's Guide, and SQL*Module for Ada Programmer's Guide.
2-10
SQL Reference
Datatypes
built-in datatypes:
CHAR ( size ( ( size ( ) size ) size ) , ( NUMBER LONG LONG RAW DATE BLOB CLOB NCLOB BFILE ROWID ( UROWID ANSI_supported_types size ) ( RAW size ) precision scale ) )
VARCHAR2 NCHAR
NVARCHAR2
The ANSI-supported datatypes appear in the figure that follows. Table 22 shows the mapping of ANSI-supported datatypes to Oracle build-in datatypes.
Basic Elements of Oracle SQL
2-11
Datatypes
ANSI-supported datatypes:
CHARACTER CHARACTER CHAR VARCHAR NATIONAL NATIONAL NATIONAL NATIONAL NCHAR ( size ) ( size ) ( size size ) ( size size ) ) ) size ) )
VARYING ( size
VARYING (
CHARACTER CHAR (
CHARACTER CHAR VARYING
VARYING ( ) ,
VARYING ( size
scale )
( NUMERIC
precision
, ( DECIMAL , ( DEC INTEGER INT SMALLINT ( FLOAT DOUBLE REAL PRECISION size ) precision scale precision
scale )
)
2-12
SQL Reference
Datatypes
Table 21
Code 1
a
Built-In Datatype Summary
Description Variable-length character string having maximum length size bytes. Maximum size is 4000, and minimum is 1. You must specify size for VARCHAR2. Variable-length character string having maximum length size characters or bytes, depending on the choice of national character set. Maximum size is determined by the number of bytes required to store each character, with an upper limit of 4000 bytes. You must specify size for NVARCHAR2. Number having precision p and scale s. The precision p can range from 1 to 38. The scale s can range from -84 to 127. Character data of variable length up to 2 gigabytes, or 231 -1 bytes. Valid date range from January 1, 4712 BC to December 31, 9999 AD. Raw binary data of length size bytes. Maximum size is 2000 bytes. You must specify size for a RAW value. Raw binary data of variable length up to 2 gigabytes. Hexadecimal string representing the unique address of a row in its table. This datatype is primarily for values returned by the ROWID pseudocolumn. Hexadecimal string representing the logical address of a row of an index-organized table. The optional size is the size of a column of type UROWID. The maximum size and default is 4000 bytes. Fixed-length character data of length size bytes. Maximum size is 2000 bytes. Default and minimum size is 1 byte.
Built-In Datatype VARCHAR2(size)
1
NVARCHAR2(size)
2
NUMBER(p,s)
8 12 23 24 69
LONG DATE RAW(size) LONG RAW ROWID
208
UROWID [(size)]
96
CHAR(size)
a
The codes listed for the datatypes are used internally by Oracle. The datatype code of a column or object attribute is returned when you use the DUMP function.
Basic Elements of Oracle SQL
2-13
Datatypes
Table 21 (Cont.) Built-In Datatype Summary
Codea 96 Built-In Datatype NCHAR(size) Description Fixed-length character data of length size characters or bytes, depending on the choice of national character set. Maximum size is determined by the number of bytes required to store each character, with an upper limit of 2000 bytes. Default and minimum size is 1 character or 1 byte, depending on the character set. A character large object containing single-byte characters. Both fixed-width and variable-width character sets are supported, both using the CHAR database character set. Maximum size is 4 gigabytes. A character large object containing multibyte characters. Both fixed-width and variable-width character sets are supported, both using the NCHAR database character set. Maximum size is 4 gigabytes. Stores national character set data. A binary large object. Maximum size is 4 gigabytes. Contains a locator to a large binary file stored outside the database. Enables byte stream I/O access to external LOBs residing on the database server. Maximum size is 4 gigabytes.
112
CLOB
112
NCLOB
113 114
BLOB BFILE
a
The codes listed for the datatypes are used internally by Oracle. The datatype code of a column or object attribute is returned when you use the DUMP function.
Character Datatypes
Character datatypes store character (alphanumeric) data, which are words and freeform text, in the database character set or national 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 store only numeric values. Character data is stored in strings with byte values corresponding to one of the character sets, such as 7-bit ASCII or EBCDIC Code Page 500, specified when the database was created. Oracle supports both single-byte and multibyte character sets. These datatypes are used for character data:
s
CHAR Datatype
2-14
SQL Reference
Datatypes
s
NCHAR Datatype NVARCHAR2 Datatype VARCHAR2 Datatype
s
s
CHAR Datatype
The CHAR datatype specifies a fixed-length character string. When you create a table with a CHAR column, you 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 character and the maximum allowed is 2000 characters. A zero-length string can be inserted into a CHAR column, but the column is blank-padded to 1 character when used in comparisons. For information on comparison semantics, see "Datatype Comparison Rules" on page 2-32. Note: To ensure proper data conversion between databases with different character sets, you must ensure that CHAR data consists of well-formed strings. See Oracle8i National Language Support Guide for more information on character set support.
NCHAR Datatype
The NCHAR datatype specifies a fixed-length national character set character string. When you create a table with an NCHAR column, you define the column length either in characters or in bytes. You define the national character set when you create your database. If the national character set of the database is fixed width, such as JA16EUCFIXED, then you declare the NCHAR column size as the number of characters desired for the string length. If the national character set is variable width, such as JA16SJIS, you declare the column size in bytes. The following statement creates a table with one NCHAR column that can store strings up to 30 characters in length using JA16EUCFIXED as the national character set:
CREATE TABLE tab1 (col1 NCHAR(30));
The column's maximum length is determined by the national character set definition. Width specifications of character datatype NCHAR refer to the number of characters if the national character set is fixed width and refer to the number of
Basic Elements of Oracle SQL
2-15
Datatypes
bytes if the national character set is variable width. The maximum column size allowed is 2000 bytes. For fixed-width, multibyte character sets, the maximum length of a column allowed is the number of characters that fit into no more than 2000 bytes. If you insert a value that is shorter than the column length, Oracle blank-pads the value to column length. You cannot insert a CHAR value into an NCHAR column, nor can you insert an NCHAR value into a CHAR column. The following example compares the COL1 column of TAB1 with national character set string 'NCHAR literal':
SELECT * FROM tab1 WHERE col1 = N'NCHAR literal';
NVARCHAR2 Datatype
The NVARCHAR2 datatype specifies a variable-length national character set character string. When you create a table with an NVARCHAR2 column, you supply the maximum number of characters or bytes it can hold. Oracle subsequently stores each value in the column exactly as you specify it, provided the value does not exceed the column's maximum length. The column's maximum length is determined by the national character set definition. Width specifications of character datatype NVARCHAR2 refer to the number of characters if the national character set is fixed width and refer to the number of bytes if the national character set is variable width. The maximum column size allowed is 4000 bytes. For fixed-width, multibyte character sets, the maximum length of a column allowed is the number of characters that fit into no more than 4000 bytes. The following statement creates a table with one NVARCHAR2 column of 2000 characters in length (stored as 4000 bytes, because each character takes two bytes) using JA16EUCFIXED as the national character set:
CREATE TABLE tab1 (col1 NVARCHAR2(2000));
VARCHAR2 Datatype
The VARCHAR2 datatype specifies a variable-length character string. When you create a VARCHAR2 column, you 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 the value does not exceed the column's maximum length. If you try to insert a value that exceeds the specified length, Oracle returns an error. You must specify a maximum length for a VARCHAR2 column. This maximum must be at least 1 byte, although the actual length of the string stored is permitted to be
2-16
SQL Reference
Datatypes
zero. The maximum length of VARCHAR2 data is 4000 bytes. Oracle compares VARCHAR2 values using nonpadded comparison semantics. For information on comparison semantics, see "Datatype Comparison Rules" on page 2-32. Note: To ensure proper data conversion between databases with different character sets, you must ensure that VARCHAR2 data consists of well-formed strings. See Oracle8i National Language Support Guide for more information on character set support.
VARCHAR Datatype
The VARCHAR datatype is currently synonymous with the VARCHAR2 datatype. Oracle recommends that you use VARCHAR2 rather than VARCHAR. In the future, VARCHAR might be defined as a separate datatype used for variable-length character strings compared with different comparison semantics.
NUMBER Datatype
The NUMBER datatype stores zero, positive, and negative fixed and floating-point numbers with magnitudes between 1.0 x 10-130 and 9.9...9 x 10125 (38 nines followed by 88 zeroes) with 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. Specify a fixed-point number using the following form:
NUMBER(p,s)
where:
p s
is the precision, or the total number of digits. Oracle guarantees the portability of numbers with precision ranging from 1 to 38. is the scale, or the number of digits to the right of the decimal point. The scale can range from -84 to 127.
Specify an integer using the following form: NUMBER(p) is a fixed-point number with precision p and scale 0. This is equivalent to NUMBER(p,0).
Specify a floating-point number using the following form:
Basic Elements of Oracle SQL
2-17
Datatypes
NUMBER
is a floating-point number with decimal precision 38. Note that a scale value is not applicable for floating-point numbers. (See "Floating-Point Numbers" on page 2-19 for more information.)
Scale and Precision
Specify the scale and precision of a fixed-point number column for extra integrity checking on input. Specifying scale and precision does not force all values to a fixed length. If a value exceeds the precision, Oracle returns an error. If a value exceeds the scale, Oracle rounds it. The following examples show how Oracle stores data using different precisions and scales.
Actual Data Specified As Stored As
7456123.89 7456123.89 7456123.89 7456123.89 7456123.89 7456123.89 7456123.89
NUMBER NUMBER(9) NUMBER(9,2) NUMBER(9,1) NUMBER(6) NUMBER(7,-2) NUMBER(-7,2)
7456123.89 7456124 7456123.89 7456123.9 exceeds precision 7456100 exceeds precision
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:
2-18
SQL Reference
Datatypes
Actual Data
Specified As
Stored As
.01234 .00012 .000127 .0000012 .00000123
NUMBER(4,5) NUMBER(4,5) NUMBER(4,5) NUMBER(2,7) NUMBER(2,7)
.01234 .00012 .00013 .0000012 .0000012
Floating-Point Numbers
Oracle allows you to specify floating-point numbers, which can have a decimal point anywhere from the first to the last digit or can have no decimal point at all. A scale value is not applicable to floating-point numbers, because the number of digits that can appear after the decimal point is not restricted. You can specify floating-point numbers with the form discussed in "NUMBER Datatype" on page 2-17. Oracle also supports the ANSI datatype FLOAT. You can specify this datatype using one of these syntactic forms: FLOAT FLOAT(b) specifies a floating-point number with decimal precision 38, or binary precision 126. 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. The length of LONG values may be limited by the memory available on your computer.
Note: Oracle Corporation strongly recommends that you convert
LONG columns to LOB columns. LOB columns are subject to far fewer restrictions than LONG columns. See "TO_LOB" on page 4-102 for more information.
Basic Elements of Oracle SQL
2-19
Datatypes
You can reference LONG columns in SQL statements in these places:
s
SELECT lists SET clauses of UPDATE statements VALUES clauses of INSERT statements
s
s
The use of LONG values is subject to some restrictions:
s
A table cannot contain more than one LONG column. You cannot create an object type with a LONG attribute. LONG columns cannot appear in integrity constraints (except for NULL and NOT NULL constraints). LONG columns cannot be indexed. 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.
s
s
s
s
s
LONG columns cannot appear in certain parts of SQL statements:
s
WHERE clauses, GROUP BY clauses, ORDER BY clauses, or CONNECT BY clauses or with the DISTINCT operator in SELECT statements The UNIQUE operator of a SELECT statement The column list of a CREATE CLUSTER statement The CLUSTER clause of a CREATE MATERIALIZED VIEW statement 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 the UNION, INTERSECT, or MINUS set operators SELECT lists of CREATE TABLE ... AS SELECT statements SELECT lists in subqueries in INSERT statements
s
s
s
s
s
s
s
s
s
Triggers can use the LONG datatype in the following manner:
s
A SQL statement within a trigger can insert data into a LONG column.
2-20
SQL Reference
Datatypes
s
If data from a LONG column can be converted to a constrained datatype (such as CHAR and VARCHAR2), a LONG column can be referenced in a SQL statement within a trigger. Variables in triggers cannot be declared using the LONG datatype. :NEW and :OLD cannot be used with LONG columns.
s
s
You can use the Oracle Call Interface functions to retrieve a portion of a LONG value from the database. See Oracle Call Interface Programmer's Guide.
DATE Datatype
The DATE datatype stores 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, Oracle stores the following information: century, year, month, day, hour, minute, and second. To specify a date value, you must convert a character or numeric value to a date 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 a 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:00 AM (midnight). If you specify a time 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 "Date Format Models" on page 2-45 and Chapter 4, "Functions".
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 common date operations. For example, the ADD_MONTHS function lets you add or subtract months from a date. The
Basic Elements of Oracle SQL
2-21
Datatypes
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. 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.
See Also: "Date Functions" on page 4-5 for more information on
date functions.
Using Julian Dates
A Julian date is the number of days since January 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, 1997:
SELECT TO_CHAR(TO_DATE('01-01-1997', 'MM-DD-YYYY'),'J') FROM DUAL; TO_CHAR -------2450450
For a description of the DUAL table, see "Selecting from the DUAL Table" on page 5-26.
RAW and LONG RAW Datatypes
The RAW and LONG RAW datatypes store data that is not to be interpreted (not explicitly converted when moving data between different systems) by Oracle. These datatypes are intended for binary data or byte strings. For example, you can use LONG RAW to store graphics, sound, documents, or arrays of binary data, for which the interpretation is dependent on the use.
Note: Oracle Corporation strongly recommends that you convert
LONG RAW columns to binary LOB (BLOB) columns. LOB columns are subject to far fewer restrictions than LONG columns. See "TO_LOB" on page 4-102 for more information.
2-22
SQL Reference
Datatypes
RAW is a variable-length datatype like VARCHAR2, except that Net8 (which connects user sessions to the instance) and the Import and Export utilities do not perform character conversion when transmitting RAW or LONG RAW data. In contrast, Net8 and Import/Export automatically convert CHAR, VARCHAR2, and LONG data from the database character set to the user session character set (which you can set with the NLS_LANGUAGE parameter of the ALTER SESSION statement), if the two character sets are different. When Oracle automatically converts RAW or LONG RAW data to and from CHAR data, the binary data is represented in hexadecimal form, with one hexadecimal character representing every four bits of RAW data. For example, one byte of RAW data with bits 11001011 is displayed and entered as 'CB'.
Large Object (LOB) Datatypes
The built-in LOB datatypes BLOB, CLOB, and NCLOB (stored internally), and the BFILE (stored externally), can store large and unstructured data such as text, image, video, and spatial data up to 4 gigabytes in size. When creating a table, you can optionally specify different tablespace and storage characteristics for LOB columns or LOB object attributes from those specified for the table. LOB columns contain LOB locators that can refer to out-of-line or in-line LOB values. Selecting a LOB from a table actually returns the LOB's locator and not the entire LOB value. The DBMS_LOB package and Oracle Call Interface (OCI) operations on LOBs are performed through these locators. LOBs are similar to LONG and LONG RAW types, but differ in the following ways:
s
LOBs can be attributes of a user-defined datatype (object). The LOB locator is stored in the table column, either with or without the actual LOB value. BLOB, NCLOB, and CLOB values can be stored in separate tablespaces. BFILE data is stored in an external file on the server. When you access a LOB column, the locator is returned. A LOB can be up to 4 gigabytes in size. BFILE maximum size is operating system dependent, but cannot exceed 4 gigabytes. LOBs permit efficient, random, piece-wise access to and manipulation of data. You can define more than one LOB column in a table. With the exception of NCLOB, you can define one or more LOB attributes in an object.
s
s
s
s
s
s
Basic Elements of Oracle SQL
2-23
Datatypes
s
You can declare LOB bind variables. You can select LOB columns and LOB attributes. You can insert a new row or update an existing row that contains one or more LOB columns and/or an object with one or more LOB attributes. (You can set the internal LOB value to NULL, empty, or replace the entire LOB with data. You can set the BFILE to NULL or make it point to a different file.) You can update a LOB row/column intersection or a LOB attribute with another LOB row/column intersection or LOB attribute. You can delete a row containing a LOB column or LOB attribute and thereby also delete the LOB value. Note that for BFILEs, the actual operating system file is not deleted.
s
s
s
s
You can access and populate rows of an internal LOB column (a LOB column stored in the database) simply by issuing an INSERT or UPDATE statement. However, to access and populate a LOB attribute that is part of an object type, you must first initialize the LOB attribute using the EMPTY_CLOB or EMPTY_BLOB function. (See "EMPTY_[B | C]LOB" on page 4-33.) You can then select the empty LOB attribute and populate it using the DBMS_LOB package or some other appropriate interface. The following example creates a table with LOB columns. (It assumes the existence of tablespace RESUMES).
CREATE TABLE person_table (name CHAR(40), resume CLOB, picture BLOB) LOB (resume) STORE AS ( TABLESPACE resumes STORAGE (INITIAL 5M NEXT 5M) );
See Also:
s
Oracle8i Supplied PL/SQL Packages Reference and Oracle Call Interface Programmer's Guide for more information about these interfaces and LOBs. Oracle8i Application Developer's Guide - Large Objects (LOBs) for information on creating temporary LOBs and on LOB restrictions. "TO_LOB" on page 4-102 for more information on converting LONG columns to LOB columns.
s
s
2-24
SQL Reference
Datatypes
BFILE Datatype
The BFILE datatype enables access to binary file LOBs that are stored in file systems outside the Oracle database. A BFILE column or attribute stores a BFILE locator, which serves as a pointer to a binary file on the server's file system. The locator maintains the directory alias and the filename. See "CREATE DIRECTORY" on page 7-282. Binary file LOBs do not participate in transactions and are not recoverable. Rather, the underlying operating system provides file integrity and durability. The maximum file size supported is 4 gigabytes. The database administrator must ensure that the file exists and that Oracle processes have operating system read permissions on the file. The BFILE datatype allows read-only support of large binary files. You cannot modify or replicate such a file. Oracle provides APIs to access file data. The primary interfaces that you use to access file data are the DBMS_LOB package and the OCI.
See Also: Oracle8i Application Developer's Guide - Large Objects (LOBs) and Oracle Call Interface Programmer's Guide for more information about LOBs.
BLOB Datatype
The BLOB datatype stores unstructured binary large objects. BLOBs can be thought of as bitstreams with no character set semantics. BLOBs can store up to 4 gigabytes of binary data. BLOBs have full transactional support. Changes made through SQL, the DBMS_LOB package, or the OCI participate fully in the transaction. BLOB value manipulations can be committed and rolled back. Note, however, that you cannot save a BLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session.
CLOB Datatype
The CLOB datatype stores single-byte character data. Both fixed-width and variablewidth character sets are supported, and both use the CHAR database character set. CLOBs can store up to 4 gigabytes of character data. CLOBs have full transactional support. Changes made through SQL, the DBMS_LOB package, or the OCI participate fully in the transaction. CLOB value manipulations can be committed and rolled back. Note, however, that you cannot save a CLOB
Basic Elements of Oracle SQL
2-25
Datatypes
locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session.
NCLOB Datatype
The NCLOB datatype stores multibyte national character set character (NCHAR) data. Both fixed-width and variable-width character sets are supported. NCLOBs can store up to 4 gigabytes of character text data. NCLOBs have full transactional support. Changes made through SQL, the DBMS_LOB package, or the OCI participate fully in the transaction. NCLOB value manipulations can be committed and rolled back. Note, however, that you cannot save an NCLOB locator in a PL/SQL or OCI variable in one transaction and then use it in another transaction or session.
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 strings have the datatype ROWID. 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.
See Also: "Pseudocolumns" on page 2-56 for more information on
the ROWID pseudocolumn.
Restricted Rowids
Beginning with Oracle8, Oracle SQL incorporated an extended format for rowids to efficiently support partitioned tables and indexes and tablespace-relative data block addresses (DBAs) without ambiguity. Character values representing rowids in Oracle7 and earlier releases are called restricted rowids. Their format is as follows:
block.row.file
where: block is a hexadecimal string identifying the data block of the datafile containing the row. The length of this string depends on your operating system.
2-26
SQL Reference
Datatypes
row file
is a four-digit hexadecimal string identifying the row in the data block. The first row of the block has a digit of 0. is a hexadecimal string identifying the database file containing the row. The first datafile has the number 1. The length of this string depends on your operating system.
Extended Rowids
The extended ROWID datatype stored in a user column includes the data in the restricted rowid plus a data object number. The data object number is an identification number assigned to every database segment. You can retrieve the data object number from data dictionary views USER_OBJECTS, DBA_OBJECTS, and ALL_OBJECTS. Objects that share the same segment (clustered tables in the same cluster, for example) have the same object number. Extended rowids are not available directly. You can use a supplied package, DBMS_ROWID, to interpret extended rowid contents. The package functions extract and provide information that would be available directly from a restricted rowid, as well as information specific to extended rowids. For information on the functions available with the DBMS_ROWID package and how to use them, see Oracle8i Supplied PL/SQL Packages Reference.
Compatibility and Migration
The restricted form of a rowid is still supported in Oracle8i for backward compatibility, but all tables return rowids in the extended format. For information regarding compatibility and migration issues, see Oracle8i Migration.
UROWID Datatype
Each row in a database has an address (as discussed in "ROWID Datatype" on page 2-26). However, the rows of some tables have addresses that are not physical or permanent, or were not generated by Oracle. For example, the row addresses of index-organized tables are stored in index leaves, which can move. Rowids of foreign tables (such as DB2 tables accessed through a gateway) are not standard Oracle rowids. Oracle uses "universal rowids" (urowids) to store the addresses of index-organized and foreign tables. Index-organized tables have logical urowids and foreign tables have foreign urowids. Both types of urowid are stored in the ROWID pseudocolumn (as are the physical rowids of heap-organized tables).
Basic Elements of Oracle SQL
2-27
Datatypes
Oracle creates logical rowids based on a table's primary key. The logical rowids do not change as long as the primary key does not change. The ROWID pseudocolumn of an index-organized table has a datatype of UROWID. You can access this pseudocolumn as you would the ROWID pseudocolumn of a heap-organized (that is, using the SELECT ROWID statement). If you wish to store the rowids of an indexorganized table, you can define a column of type UROWID for the table and retrieve the value of the ROWID pseudocolumn into that column.
Note: Heap-organized tables have physical rowids. Oracle
Corporation does not recommend that you specify a column of datatype UROWID for a heap-organized table.
See Also: Oracle8i Concepts and Oracle8i Designing and Tuning for Performance for more information on the UROWID datatype and how Oracle generates and manipulates universal rowids
ANSI, DB2, and SQL/DS Datatypes
SQL statements that create tables and clusters can also use ANSI datatypes and datatypes from IBM's products SQL/DS and DB2. Oracle recognizes the ANSI or IBM datatype name and records it as the name of the datatype of the column, and then stores the column's data in an Oracle datatype based on the conversions shown in Table 22 and Table 23.
Table 22 ANSI Datatypes Converted to Oracle Datatypes
ANSI SQL Datatype Oracle Datatype
CHARACTER(n) CHAR(n) CHARACTER VARYING(n) CHAR VARYING(n) NATIONAL CHARACTER(n) NATIONAL CHAR(n) NCHAR(n)
CHAR(n)
VARCHAR(n)
NCHAR(n)
2-28
SQL Reference
Datatypes
Table 22 ANSI Datatypes Converted to Oracle Datatypes
NATIONAL CHARACTER VARYING(n) NATIONAL CHAR VARYING(n) NCHAR VARYING(n) NUMERIC(p,s) DECIMAL(p,s)a INTEGER INT SMALLINT FLOAT(b)b DOUBLE PRECISIONc REALd
aThe
NVARCHAR2(n)
NUMBER(p,s)
NUMBER(38)
NUMBER
NUMERIC and DECIMAL datatypes can specify only fixed-point numbers. For these datatypes, s defaults to 0. bThe FLOAT datatype is a floating-point number with a binary precision b. The default precision for this datatype is 126 binary, or 38 decimal. cThe DOUBLE PRECISION datatype is a floating-point number with binary precision 126. dThe REAL datatype is a floating-point number with a binary precision of 63, or 18 decimal.
Table 23 SQL/DS and DB2 Datatypes Converted to Oracle Datatypes
SQL/DS or DB2 Datatype Oracle Datatype
CHARACTER(n) VARCHAR(n) LONG VARCHAR(n) DECIMAL(p,s)a INTEGER SMALLINT FLOAT(b)b
CHAR(n) VARCHAR(n) LONG NUMBER(p,s) NUMBER(38)
NUMBER
Basic Elements of Oracle SQL
2-29
Datatypes
Table 23 SQL/DS and DB2 Datatypes Converted to Oracle Datatypes
aThe
DECIMAL datatype can specify only fixed-point numbers. For this datatype, s defaults to 0. bThe FLOAT datatype is a floating-point number with a binary precision b. The default precision for this datatype is 126 binary, or 38 decimal.
Do not define columns with these SQL/DS and DB2 datatypes, because they have no corresponding Oracle datatype:
s
GRAPHIC LONG VARGRAPHIC VARGRAPHIC TIME TIMESTAMP
s
s
s
s
Note that data of type TIME and TIMESTAMP can also be expressed as Oracle DATE data.
User-Defined Type Categories
User-defined datatypes use Oracle built-in datatypes and other user-defined datatypes as the building blocks of types that model the structure and behavior of data in applications. For information about Oracle built-in datatypes, see Oracle8i Concepts. For information about creating user-defined types, see "CREATE TYPE" on page 7-437 and the "CREATE TYPE BODY" on page 7-447. For information about using user-defined types, see Oracle8i Application Developer's Guide - Fundamentals. The sections that follow describe the various categories of user-defined types.
Object Types
Object types are abstractions of the real-world entities, such as purchase orders, that application programs deal with. An object type is a schema object with three kinds of components:
s
A name, which identifies the object type uniquely within that schema. Attributes, which are built-in types or other user-defined types. Attributes model the structure of the real-world entity. Methods, which are functions or procedures written in PL/SQL and stored in the database, or written in a language like C or Java and stored externally.
s
s
2-30
SQL Reference
Datatypes
Methods implement operations the application can perform on the real-world entity.
REFs
An object identifier (OID) uniquely identifies an object and enables you to reference the object from other objects or from relational tables. A datatype category called REF represents such references. A REF is a container for an object identifier. REFs are pointers to objects. When a REF value points to a nonexistent object, the REF is said to be "dangling". A dangling REF is different from a null REF. To determine whether a REF is dangling or not, use the predicate IS [NOT] DANGLING. For example, given table DEPT with column MGR whose type is a REF to type EMP_T, which has an attribute NAME:
SELECT t.mgr.name FROM dept t WHERE t.mgr IS NOT DANGLING;
Varrays
An array is an ordered set of data elements. All elements of a given array are of the same datatype. Each element has an index, which is a number corresponding to the element's position in the array. The number of elements in an array is the size of the array. Oracle arrays are of variable size, which is why they are called varrays. You must specify a maximum size when you declare the array. When you declare a varray, it does not allocate space. It defines a type, which you can use as:
s
The datatype of a column of a relational table An object type attribute A PL/SQL variable, parameter, or function return type
s
s
Oracle normally stores an array object either in line (that is, as part of the row data) or out of line (in a LOB), depending on its size. However, if you specify separate storage characteristics for a varray, Oracle will store it out of line, regardless of its size (see the varray_storage_clause of "CREATE TABLE" on page 4-381).
Nested Tables
A nested table type models an unordered set of elements. The elements may be built-in types or user-defined types. You can view a nested table as a single-column
Basic Elements of Oracle SQL
2-31
Datatypes
table or, if the nested table is an object type, as a multicolumn table, with a column for each attribute of the object type. A nested table definition does not allocate space. It defines a type, which you can use to declare:
s
Columns of a relational table Object type attributes PL/SQL variables, parameters, and function return values
s
s
When a nested table appears as the type of a column in a relational table or as an attribute of the underlying object type of an object table, Oracle stores all of the nested table data in a single table, which it associates with the enclosing relational or object table.
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 zero and 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-1997' is less than that of '05-JAN-1998' and '05-JAN-1998 1:35pm' is greater than '05-JAN-1998 10:09am'.
Character String Values
Character values are compared using one of these comparison rules:
s
blank-padded comparison semantics nonpadded comparison semantics
s
The following sections explain these comparison semantics. The results of comparing two character values using different comparison semantics may vary. The table below shows the results of comparing five pairs of character values using each comparison semantic. Usually, the results of blank-padded and nonpadded comparisons are the same. The last comparison in the table illustrates the differences between the blank-padded and nonpadded comparison semantics.
2-32
SQL Reference
Datatypes
Blank-Padded 'ab' > 'aa' 'ab' > 'a 'ab' > 'a' 'ab' = 'ab' 'a ' = 'a' '
Nonpadded 'ab' > 'aa' 'ab' > 'a 'ab' > 'a' 'ab' = 'ab' 'a ' > 'a' '
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, NCHAR, text literals, or values returned by the USER function. Nonpadded 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 nonpadded comparison semantics whenever one or both values in the comparison have the datatype VARCHAR2 or NVARCHAR2.
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. Oracle considers blanks to be less than any character, which is true in most character sets. These are some common character sets:
s
7-bit ASCII (American Standard Code for Information Interchange) EBCDIC Code (Extended Binary Coded Decimal Interchange Code) Page 500 ISO 8859/1 (International Standards Organization) JEUC Japan Extended UNIX
s
s
s
Basic Elements of Oracle SQL
2-33
Datatypes
Portions of the ASCII and EBCDIC character sets appear in Table 24 and Table 25. Note that uppercase and lowercase letters are not equivalent. Also, note that the numeric values for the characters of a character set may not match the linguistic sequence for a particular language.
Table 24 ASCII Character Set
Decimal value 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48-57 58 Symbol ; < = > ? @ A-Z [ \ ] ^ _ ` a-z { | } ~ Decimal value 59 60 61 62 63 64 65-90 91 92 93 94 95 96 97-122 123 124 125 126
Symbol blank ! " # $ % & ' ( ) * + , . / 0-9 :
2-34
SQL Reference
Datatypes
Table 25 EBCDIC Character Set
Symbol blank . < ( + | & ! $ * ) ; / Decimal value 64 74 75 76 77 78 79 80 90 91 92 93 94 95 96 97 Symbol % _ > ? : # @ ' = " a-i j-r s-z A-I J-R S-Z Decimal value 108 109 110 111 122 123 124 125 126 127 129-137 145-153 162-169 193-201 209-217 226-233
Object Values
Object values are compared using one of two comparison functions: MAP and ORDER. Both functions compare object type instances, but they are quite different from one another. These functions must be specified as part of the object type. For a description of MAP and ORDER methods and the values they return, see "CREATE TYPE" on page 7-437. See also Oracle8i Application Developer's Guide Fundamentals for more information.
Varrays and Nested Tables
You cannot compare varrays and nested tables in Oracle8i.
Basic Elements of Oracle SQL
2-35
Datatypes
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 conversions in these cases:
s
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.
s
s
Example 1
The text literal '10' has datatype CHAR. Oracle implicitly converts it to the NUMBER datatype if it appears in a numeric expression as in the following statement:
SELECT sal + '10' FROM emp;
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 the following statement, Oracle implicitly converts '7936' to 7936:
Example 2
SELECT ename FROM emp WHERE empno = '7936';
In the following statement, Oracle implicitly converts '12-MAR-1993' to a DATE value using the default date format 'DD-MON-YYYY':
Example 3
SELECT ename FROM emp WHERE hiredate = '12-MAR-1993';
2-36
SQL Reference
Datatypes
In the following statement, Oracle implicitly converts the text literal 'AAAAZ8AABAAABvlAAA' to a rowid value:
Example 4
SELECT ename FROM emp WHERE ROWID = 'AAAAZ8AABAAABvlAAA';
Explicit Data Conversion
You can also explicitly specify datatype conversions using SQL conversion functions. Table 26 shows SQL functions that explicitly convert a value from one datatype to another.
Table 26 SQL Functions for Datatype Conversion
TO / FROM CHAR -- NUMBER TO_CHAR TO_CHAR DATE TO_CHAR RAWTOHEX ROWIDTOCHAR (date,'J' ) -- -- -- TO_LOB -- TO_DATE (number,' J') -- CHAR -- NUMBER TO_NUMBER DATE TO_DATE RAW HEXTORAW ROWID CHARTOROWID LONG/ LONG RAW LOB
RAW ROWID LONG / LONG RAW LOB
For information on these functions, see "Conversion Functions" on page 4-5.
Basic Elements of Oracle SQL
2-37
Format Models
Note: You cannot 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 "LONG Datatype" on page 2-19.
Implicit vs. Explicit Data Conversion
Oracle recommends that you specify explicit conversions rather than rely on implicit or automatic conversions for these reasons:
s
SQL statements are easier to understand when you use explicit datatype conversion 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.
s
s
s
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 and TO_DATE functions:
s
To specify the format for Oracle to use to return a value from the database To specify the format for a value you have specified for Oracle to store in the database
s
See "TO_CHAR (date conversion)" on page 4-99, "TO_CHAR (number conversion)" on page 4-100, and "TO_DATE" on page 4-101. Note that a format model does not change the internal representation of the value in the database. This section describes how to use:
s
Number format models Date format models
s
2-38
SQL Reference
Format Models
s
Format model modifiers
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. The following 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':
Example 1
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 commissions with leading dollar signs, commas every three digits, and two decimal places. Note that TO_CHAR returns null for all employees with null in the COMM column. The following statement selects the date on which 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':
Example 2
SELECT ename, TO_CHAR(Hiredate,'fmMonth DD, YYYY') hiredate FROM emp WHERE deptno = 20; ENAME ---------SMITH JONES SCOTT HIREDATE -----------------December 17, 1980 April 2, 1981 April 19, 1987
Basic Elements of Oracle SQL
2-39
Format Models
ADAMS FORD LEWIS
May 23, 1987 December 3, 1981 October 23, 1997
With this format model, Oracle returns the hire dates (as specified by "fm" and discussed in "Format Model Modifiers" on page 2-51) without blank padding, 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 The following statement updates BAKER's hire date using the TO_DATE
function with the format mask 'YYYY MM DD' to convert the character string '1998 05 20' to a DATE value:
UPDATE emp SET hiredate = TO_DATE('1998 05 20','YYYY MM DD') WHERE ename = 'BLAKE';
Number Format Models
You can use number format models:
s
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
s
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. If a positive value is extremely large and cannot be represented in the specified format, then the infinity sign (~) replaces the value. Likewise, if a negative value is extremely small and cannot be represented by the specified format, then the negative infinity sign
2-40
SQL Reference
Format Models
replaces the value (-~). This event typically occurs when you are using TO_CHAR with a restrictive number format string, causing a rounding operation.
Number Format Elements
A number format model is composed of one or more number format elements. Table 27 lists the elements of a number format model. Examples are shown in Table 28. Negative return values automatically contain a leading negative sign and positive values automatically contain a leading space unless the format model contains the MI, S, or PR format element.
Table 27
Element , (comma)
Number Format Elements
Example 9,999 Description Returns a comma in the specified position. You can specify multiple commas in a number format model. Restrictions:
s s
A comma element cannot begin a number format model. A comma cannot appear to the right of a decimal character or period in a number format model.
. (period)
99.99
Returns a decimal point, which is a period (.) in the specified position. Restriction: You can specify only one period in a number format model.
$ 0
$9999 0999 9990
Returns value with a leading dollar sign. Returns leading zeros. Returns trailing zeros. Returns value with the specified number of digits with a leading space if positive or with a leading minus if negative. Leading zeros are blank, except for a zero value, which returns a zero for the integer part of the fixed-point number.
9
9999
B
B9999
Returns blanks for the integer part of a fixed-point number when the integer part is zero (regardless of "0"s in the format model). Returns in the specified position the ISO currency symbol (the current value of the NLS_ISO_CURRENCY parameter).
C
C999
Basic Elements of Oracle SQL
2-41
Format Models
Table 27 (Cont.) Number Format Elements
Element D Example 99D99 Description Returns in the specified position the decimal character, which is the current value of the NLS_NUMERIC_CHARACTER parameter. The default is a period (.). Restriction: You can specify only one decimal character in a number format model. EEEE FM G 9.9EEEE FM90.9 9G999 Returns a value using in scientific notation. Returns a value with no leading or trailing blanks. Returns in the specified position the group separator (the current value of the NLS_NUMERIC_CHARACTER parameter). You can specify multiple group separators in a number format model. Restriction: A group separator cannot appear to the right of a decimal character or period in a number format model. L MI L999 9999MI Returns in the specified position the local currency symbol (the current value of the NLS_CURRENCY parameter). Returns negative value with a trailing minus sign (-). Returns positive value with a trailing blank. Restriction: The MI format element can appear only in the last position of a number format model. PR 9999PR Returns negative value in <angle brackets>. Returns positive value with a leading and trailing blank. Restriction: The PR format element can appear only in the last position of a number format model. RN rn RN rn Returns a value as Roman numerals in uppercase. Returns a value as Roman numerals in lowercase. Value can be an integer between 1 and 3999. S S9999 Returns negative value with a leading minus sign (-). Returns positive value with a leading plus sign (+). 9999S Returns negative value with a trailing minus sign (-). Returns positive value with a trailing plus sign (+). Restriction: The S format element can appear only in the first or last position of a number format model.
2-42
SQL Reference
Format Models
Table 27 (Cont.) Number Format Elements
Element TM Example TM Description "Text minimum". Returns (in decimal output) the smallest number of characters possible. This element is case-insensitive. The default is TM9, which returns the number in fixed notation unless the output exceeds 64 characters. If output exceeds 64 characters, Oracle automatically returns the number in scientific notation. Restrictions:
s s
You cannot precede this element with any other element. You can follow this element only with 9 or E (only one) or e (only one).
U
U9999
Returns in the specified position the "Euro" (or other) dual currency symbol (the current value of the NLS_DUAL_CURRENCY parameter). Returns a value multiplied by 10n (and if necessary, round it up), where n is the number of 9's after the "V". Returns the hexadecimal value of the specified number of digits. If the specified number is not an integer, Oracle rounds it to an integer. Restrictions:
s
V X
999V99 XXXX xxxx
This element accepts only positive values or 0. Negative values return an error. You can precede this element only with 0 (which returns leading zeroes) or FM. Any other elements return an error. If you specify neither 0 nor FM with X, the return always has 1 leading blank.
s
The values of some formats are determined by the value of initialization parameters. For such formats, you can specify the characters returned by these format elements implicitly using the initialization parameter NLS_TERRITORY. For information on these parameters, see Oracle8i Reference and Oracle8i National Language Support Guide. You can change the default date format for your session with the ALTER SESSION statement. For information on changing the settings of these parameters, see "ALTER SESSION" on page 7-83.
Basic Elements of Oracle SQL
2-43
Format Models
Example Table 28 shows the results of the following query for different values of
number and 'fmt':
SELECT TO_CHAR(number, 'fmt') FROM DUAL;
Table 28 Results of Example Number Conversions
number -1234567890 0 +0.1 -0.2 0 +0.1 -0.2 0 1 0 1 0 +123.456 -123.456 +123.456 +123.456 +1E+123 +123.456 +123.45 +123.0 +123.45 +123.45 +1234567890 'fmt' 9999999999S 99.99 99.99 99.99 90.99 90.99 90.99 9999 9999 B9999 B9999 B90.99 999.999 999.999 FM999.009 9.9EEEE 9.9EEEE FM9.9EEEE FM999.009 FM999.009 L999.99 FML99.99 9999999999S Result '1234567890-' ' ' ' ' ' .00' .10' -.20' 0.00' 0.10'
' -0.20' ' ' ' ' ' 0' 1' ' 1' '
' 123.456' '-123.456' '123.456' ' 1.2E+02'
' 1.0E+123' '1.23E+02' '123.45' '123.00' ' '$123.45' '1234567890+' $123.45'
2-44
SQL Reference
Format Models
Date Format Models
You can use date format models:
s
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
s
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 Oracle8i Reference. You can change the default date format for your session with the ALTER SESSION statement. For information, see "ALTER SESSION" on page 7-83.
Maximum Length
The total length of a date format model cannot exceed 22 characters.
Date Format Elements
A date format model is composed of one or more date format elements as listed in Table 29.
s
For input format models, format items cannot appear twice, and format items that represent similar information cannot be combined. For example, you cannot use 'SYYYY' and 'BC' in the same format string. Some of the date format elements cannot be used in the TO_DATE function, as noted in Table 29.
s
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:
s
punctuation such as hyphens, slashes, commas, periods, and colons character literals, enclosed in double quotation marks
s
Basic Elements of Oracle SQL
2-45
Format Models
These characters appear in the return value in the same location as they appear in the format model.
Table 29
Element / , . ; : 'text' AD A.D. AM A.M. BC B.C. CC SCC D DAY
Datetime Format Elements
Specify in TO_DATE? Yes Meaning Punctuation and quoted text is reproduced in the result.
Yes Yes Yes No
AD indicator with or without periods. Meridian indicator with or without periods. BC indicator with or without periods. The first two digits of the century of a four-digit year, for example, '19' from '1900' and '20' from '2001'. "S" prefixes BC dates with "-". Day of week (1-7). This element is used only to validate a date specified in the TO_DATE function. Name of day, padded with blanks to length of 9 characters. This element is used only to validate a date specified in the TO_DATE function. Day of month (1-31). Day of year (1-366). Abbreviated name of day. This element is used only to validate a date specified in the TO_DATE function. Abbreviated era name (Japanese Imperial, ROC Official, and Thai Buddha calendars). Full era name (Japanese Imperial, ROC Official, and Thai Buddha calendars). Hour of day (1-12). Hour of day (1-12).
Yes Yes
DD DDD DY E EE HH HH12
Yes Yes Yes Yes Yes Yes Yes
2-46
SQL Reference
Format Models
Table 29 (Cont.) Datetime Format Elements
Element HH24 IW IYY IY I IYYY J MI MM MON MONTH PM P.M. Q RM RR Specify in TO_DATE? Yes No No Hour of day (0-23). Week of year (1-52 or 1-53) based on the ISO standard. Last 3, 2, or 1 digit(s) of ISO year. Meaning
No Yes Yes Yes Yes Yes No No Yes Yes
4-digit year based on the ISO standard. Julian day; the number of days since January 1, 4712 BC. Number specified with 'J' must be integers. Minute (0-59). Two-digit numeric abbreviation of month (01-12; JAN = 01) Abbreviated name of month. Name of month, padded with blanks to length of 9 characters. Meridian indicator with or without periods. Quarter of year (1, 2, 3, 4; JAN-MAR = 1) Roman numeral month (I-XII; JAN = I). Given a year with 2 digits:
s
If the year is <50 and the last 2 digits of the current year are >=50, the first 2 digits of the returned year are 1 greater than the first two digits of the current year. If the year is >=50 and the last 2 digits of the current year are <50, the first 2 digits of the returned year are the same as the first 2 digits of the current year.
s
RRRR
Yes
Round year. Accepts either 4-digit or 2-digit input. If 2digit, provides the same return as RR. If you don't want this functionality, enter the 4-digit year. Second (0-59). Seconds past midnight (0-86399).
SS SSSSS
Yes Yes
Basic Elements of Oracle SQL
2-47
Format Models
Table 29 (Cont.) Datetime Format Elements
Element WW W Y,YYY YEAR SYEAR YYYY SYYYY YYY YY Y Specify in TO_DATE? No No Yes No Yes Yes Meaning 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. Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh. Year with comma in this position. Year, spelled out. "S" prefixes BC dates with "-". 4-digit year. "S" prefixes BC dates with "-". Last 3, 2, or 1 digit(s) of year.
Oracle returns an error if an alphanumeric character is found in the date string where punctuation character is found in the format string. For example:
TO_CHAR (TO_DATE('0297','MM/YY'), 'MM/YY')
returns an error.
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:
s
MONTH MON DAY DY BC or AD or B.C. or A.D. AM or PM or A.M or P.M.
s
s
s
s
s
The language in which these values are returned is specified either explicitly with the initialization parameter NLS_DATE_LANGUAGE or implicitly with the
2-48
SQL Reference
Format Models
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 national language support initialization parameters, see Oracle8i Reference and Oracle8i National Language Support 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 the discussion of national language support in Oracle8i National Language Support 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 21st century dates in the 20th century by specifying only the last two digits of the year. It will also allow you to store 20th century dates in the 21st 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. Table 210 summarizes the behavior of the RR date format element.
Table 210 The RR Date Element Format
If the specified two-digit year is 0 - 49 If the last two digits of the current year are: 0-49 50 - 99
The return date has the same The first 2 digits of the return first 2 digits as the current date are 1 less than the first 2 date. digits of the current date. The first 2 digits of the return The return date has the same date are 1 greater than the first 2 digits as the current first 2 digits of the current date. date.
50-99
Basic Elements of Oracle SQL
2-49
Format Models
The following examples demonstrate the behavior of the RR date format element.
Example 1
Assume these queries are issued between 1950 and 1999:
SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; Year ---1998 SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; Year ---2017
Example 2
Assume these queries are issued between 2000 and 2049:
SELECT TO_CHAR(TO_DATE('27-OCT-98', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; Year ---1998 SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR') ,'YYYY') "Year" FROM DUAL; 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.
Date Format Element Suffixes
Table 211 lists suffixes that can be added to date format elements:
2-50
SQL Reference
Format Models
Table 211
Suffix TH SP
Date Format Element Suffixes
Meaning Ordinal Number Spelled Number Spelled, ordinal number Example Element DDTH DDSP DDSPTH Example Value 4TH FOUR FOURTH
SPTH or THSP Restrictions:
s
When you add one of these suffixes to a date format element, the return value is always in English. Date suffixes are valid only on output. You cannot use them to insert a date into the database.
s
Format Model Modifiers
The FM and FX modifiers, used in format models in the TO_CHAR function, control blank padding and exact format checking. A modifier can appear in a format model more than once. In such a 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 reenabled 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:
s
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. Without FM, the result of a character element is always right padded with blanks to a fixed length, and leading zeroes are always returned for a number element. With FM, because there is no blank padding, the length of the return value may vary. In a number format element of a TO_CHAR function, this modifier suppresses blanks added to the left of the number, so that the result is left-justified 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.
s
FX "Format exact". This modifier specifies exact matching for the character argument and date format model of a TO_DATE function:
Basic Elements of Oracle SQL
2-51
Format Models
s
Punctuation and quoted text in the character argument must exactly match (except for case) 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.
s
s
If any portion of the character argument violates any of these conditions, Oracle returns an error message.
Example 1
The following statement uses a date format model to return a character
expression:
SELECT TO_CHAR(SYSDATE, 'fmDDTH')||' of '||TO_CHAR (SYSDATE, 'fmMonth')||', '||TO_CHAR(SYSDATE, 'YYYY') "Ides" FROM DUAL; Ides -----------------3RD of April, 1998
Note that the statement above also uses the FM modifier. If FM is omitted, the month is blank-padded to nine characters:
SELECT TO_CHAR(SYSDATE, 'DDTH')||' of '|| TO_CHAR(SYSDATE, 'Month')||', '|| TO_CHAR(SYSDATE, 'YYYY') "Ides" FROM DUAL; Ides ----------------------03RD of April , 1998
The following statement places a single quotation mark in the return value by using a date format model that includes two consecutive single quotation marks:
Example 2
SELECT TO_CHAR(SYSDATE, 'fmDay')||'''s Special' "Menu" FROM DUAL;
2-52
SQL Reference
Format Models
Menu ----------------Tuesday's Special
Two consecutive single quotation marks can be used for the same purpose within a character literal in a format model. Table 212 shows whether the following statement meets the matching conditions for different values of char and 'fmt' using FX (the table named TABLE has a column DATE_COLUMN of datatype DATE):
Example 3
UPDATE table SET date_column = TO_DATE(char, 'fmt');
Table 212 Matching Character Data and Format Models with the FX Format Model Modifier
char '15/ JAN /1998' ' 15! JAN % /1998' '15/JAN/1998' '15-JAN-1998' '1-JAN-1998' '01-JAN-1998' '1-JAN-1998' 'fmt' 'DD-MON-YYYY' 'DD-MON-YYYY' 'FXDD-MON-YYYY' 'FXDD-MON-YYYY' 'FXDD-MON-YYYY' 'FXDD-MON-YYYY' 'FXFMDD-MON-YYYY' Match or Error? Match Error Error Match Error Match Match
String-to-Date Conversion Rules
The following additional formatting rules apply when converting string values to date values (unless you have used the FX or FXFM modifiers in the format model to control exact format checking):
s
You can omit punctuation included in the format string from the date string if all the digits of the numerical format elements, including leading zeros, are specified. In other words, specify 02 and not 2 for two-digit format elements such as MM, DD, and YY. You can omit time fields found at the end of a format string from the date string.
s
Basic Elements of Oracle SQL
2-53
Nulls
s
If a match fails between a date format element and the corresponding characters in the date string, Oracle attempts alternative format elements, as shown in Table 213.
Table 213 Oracle Format Matching
Additional Format Elements to Try in Place of the Original 'MON' and 'MONTH' 'MONTH' 'MON' 'YYYY' 'RRRR'
Original Format Element 'MM' 'MON 'MONTH' 'YY' 'RR'
Nulls
If a column in a row has no value, then the 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 not known or when a value would not be meaningful. Do not use null to represent a value of zero, because they are not equivalent. (Oracle currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.) 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 REPLACE, NVL, and CONCAT) return null when given a null argument. You can use the NVL function 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 aggregate 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.
2-54
SQL Reference
Nulls
Nulls with Comparison Operators
To test for nulls, use only 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, Oracle considers two nulls to be equal when evaluating a DECODE expression. For syntax and additional information, see "DECODE Expressions" on page 5-12. Oracle also considers two nulls to be equal if they appear in compound keys. That is, Oracle considers identical two compound keys containing nulls if all the nonnull components of the keys are equal.
Nulls in Conditions
A condition that evaluates to UNKNOWN acts almost like FALSE. For example, a SELECT statement with a condition in the WHERE clause that evaluates to UNKNOWN returns no rows. However, a condition evaluating to UNKNOWN differs from FALSE in that further operations on an UNKNOWN condition evaluation will evaluate to UNKNOWN. Thus, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN. Table 214 shows examples of various evaluations involving nulls in conditions. If the conditions evaluating to UNKNOWN were used in a WHERE clause of a SELECT statement, then no rows would be returned for that query.
Table 214
If A is: 10 10 NULL NULL 10 10 NULL NULL NULL NULL
Conditions Containing Nulls
Condition a IS NULL a IS NOT NULL a IS NULL a IS NOT NULL a = NULL a != NULL a = NULL a != NULL a = 10 a != 10 Evaluates to: FALSE TRUE TRUE FALSE UNKNOWN UNKNOWN UNKNOWN UNKNOWN UNKNOWN UNKNOWN
Basic Elements of Oracle SQL
2-55
Pseudocolumns
For the truth tables showing the results of logical expressions containing nulls, see Table 36 on page 3-12, as well as Table 37 and Table 38.
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:
s
CURRVAL and NEXTVAL LEVEL ROWID ROWNUM
s
s
s
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 NEXTVAL returns the current value of a sequence. 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
2-56
SQL Reference
Pseudocolumns
See Also: "Referring to Objects in Remote Databases" on page 2-79 for more information on referring to database links.
Where to Use Sequence Values
You can use CURRVAL and NEXTVAL in:
s
The SELECT list of a SELECT statement that is not contained in a subquery, materialized view, or view The SELECT list of a subquery in an INSERT statement The VALUES clause of an INSERT statement The SET clause of an UPDATE statement
s
s
s
Restrictions: You cannot use CURRVAL and NEXTVAL:
s
A subquery in a DELETE, SELECT, or UPDATE statement A query of a view or of a materialized view A SELECT statement with the DISTINCT operator A SELECT statement with a GROUP BY clause 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
s
s
s
s
s
s
s
Also, within a single SQL statement that uses CURVAL or NEXTVAL, all referenced LONG columns, updated tables, and locked tables must be located on the same database.
How to Use Sequence Values
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 initialize the sequence with NEXTVAL.
Basic Elements of Oracle SQL
2-57
Pseudocolumns
Within a single SQL statement, Oracle will increment the sequence only once per row. 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 "CREATE SEQUENCE" on page 4-371.
Example 1
This example selects the current value of the employee sequence:
SELECT empseq.currval FROM DUAL;
This example increments the employee sequence and uses its value for a new employee inserted into the employee table:
Example 2
INSERT INTO emp VALUES (empseq.nextval, 'LEWIS', 'CLERK', 7902, SYSDATE, 1200, NULL, 20);
This example adds a new order with the next order number to the master order table. It then adds suborders with this number to the detail order table:
Example 3
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 nonroot node. A parent
2-58
SQL Reference
Pseudocolumns
node is any node that has children. A leaf node is any node without children. Figure 22 shows the nodes of an inverted tree with their LEVEL values.
Figure 22 Hierarchical Tree
root/ parent
Level 1
Level 2
parent/ child
parent/ child
Level 3
child/ leaf
parent/ child
child/ leaf
parent/ child
Level 4
child/ leaf
child/ leaf
child/ leaf
To define a hierarchical relationship in a query, you must use the START WITH and CONNECT BY clauses.
See also: "SELECT and Subqueries" on page 7-569 for more information on using the LEVEL pseudocolumn.
ROWID
For each row in the database, the ROWID pseudocolumn returns a row's address. Oracle8i rowid values contain information necessary to locate a row:
s
the data object number of the object which data block in the datafile which row in the data block (first row is 0) which datafile (first file is 1). The file number is relative to the tablespace.
s
s
s
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 or UROWID.
Basic Elements of Oracle SQL
2-59
Pseudocolumns
See Also: "ROWID Datatype" on page 2-26 and "UROWID
Datatype" on page 2-27. Rowid values have several important uses:
s
They are the fastest way to access a single row. They can show you how a table's rows are stored. They are unique identifiers for rows in a table.
s
s
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 clause 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 -----------------AAAAqYAABAAAEPvAAA AAAAqYAABAAAEPvAAD AAAAqYAABAAAEPvAAH AAAAqYAABAAAEPvAAK AAAAqYAABAAAEPvAAM ENAME ---------SMITH JONES SCOTT ADAMS 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;
2-60
SQL Reference
Pseudocolumns
If an ORDER BY clause follows ROWNUM in the same query, the rows will be reordered by the ORDER BY clause. The results can vary depending on the way the rows are accessed. For example, if the 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. Therefore, the following statement will not have the same effect as the preceding example:
SELECT * FROM emp WHERE ROWNUM < 11 ORDER BY empno;
If you embed the ORDER BY clause in a subquery and place the ROWNUM condition in the top-level query, you can force the ROWNUM condition to be applied after the ordering of the rows. For example, the following query returns the 10 smallest employee numbers. This is sometimes referred to as a "top-N query":
SELECT * FROM (SELECT empno FROM emp ORDER BY empno) WHERE ROWNUM < 11;
In the preceding example, the ROWNUM values are those of the top-level SELECT statement, so they are generated after the rows have already been ordered by EMPNO in the subquery.
See Also: Oracle8i Application Developer's Guide - Fundamentals for more information about top-N queries.
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. You can also use ROWNUM to assign unique values to each row of a table, as in this example:
UPDATE tabx SET col1 = ROWNUM;
Basic Elements of Oracle SQL
2-61
Comments
Note: Using ROWNUM in a query can affect view optimization. For more information, see Oracle8i Concepts.
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:
s
Begin the comment with a slash and an asterisk (/*). Proceed with the text of the comment. This text can span multiple lines. End the comment with an asterisk and a slash (*/). 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.
s
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.
Note: You cannot use these styles of comments between SQL
statements in a SQL script. Use the SQL*Plus REMARK command for this purpose. For information on these statements, see SQL*Plus User's Guide and Reference.
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.*/
2-62
SQL Reference
Comments
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, sal + NVL(comm, 0), job, loc FROM emp, dept WHERE emp.deptno = dept.deptno AND sal + NVL(comm, 0) > (SELECT sal + NVL(comm,0) FROM emp WHERE ename = 'JONES'); -----select the name total compensation job and city containing the office of all employees
-- whose compensation -- is greater than -- the compensation -- of Jones.
Comments on Schema Objects
You can associate a comment with a table, view, materialized view, or column using the COMMENT command described in Chapter 7, "SQL Statements". Comments associated with schema objects are stored in the data dictionary.
Hints
You can use comments in a SQL statement to pass instructions, or hints, to the Oracle optimizer. The optimizer uses these hints as suggestions for choosing an execution plan for the statement. A statement block can have only one comment containing hints, and that comment must follow the SELECT, UPDATE, INSERT, or DELETE keyword. The syntax below shows hints contained in both styles of comments that Oracle supports within a statement block.
{DELETE|INSERT|SELECT|UPDATE} /*+ hint [text] [hint[text]]... */
or
{DELETE|INSERT|SELECT|UPDATE} --+ hint [text] [hint[text]]...
where
Basic Elements of Oracle SQL
2-63
Comments
DELETE INSERT SELECT UPDATE +
is a DELETE, INSERT, SELECT, or UPDATE keyword that begins a statement block. Comments containing hints can appear only after these keywords.
is a plus sign that causes Oracle to interpret the comment as a list of hints. The plus sign must follow immediately after the comment delimiter (no space is permitted). is one of the hints discussed in this section and in Oracle8i Designing and Tuning for Performance. The space between the plus sign and the hint is optional. If the comment contains multiple hints, separate the hints by at least one space. is other commenting text that can be interspersed with the hints.
hint
text
Table 215 lists hint syntax and descriptions.
See Also: Oracle8i Designing and Tuning for Performance and Oracle8i Concepts for more information on hints.
Table 215
Hint Syntax Optimization Approaches and Goals /*+ ALL_ROWS */ Explicitly chooses the cost-based approach to optimize a statement block with a goal of best throughput (that is, minimum total resource consumption). Causes the optimizer to choose between the rule-based approach and the cost-based approach for a SQL statement based on the presence of statistics for the tables accessed by the statement. Explicitly chooses the cost-based approach to optimize a statement block with a goal of best response time (minimum resource usage to return first row). Explicitly chooses rule-based optimization for a statement block.
Hint Syntax and Descriptions
Description
/*+ CHOOSE */
/*+ FIRST_ROWS */
/*+ RULE */
2-64
SQL Reference
Comments
Table 215 (Cont.) Hint Syntax and Descriptions
Hint Syntax Access Methods /*+ AND_EQUAL(table index) */ /*+ CLUSTER(table) */ /*+ FULL(table) */ /*+ HASH(table) */ /*+ HASH_AJ(table) */ /*+ HASH_SJ(table) */ /*+ INDEX(table index) */ /*+ INDEX_ASC(table index) */ /*+ INDEX_COMBINE(table index) */ Explicitly chooses an execution plan that uses an access path that merges the scans on several single-column indexes. Explicitly chooses a cluster scan to access the specified table. Explicitly chooses a full table scan for the specified table. Explicitly chooses a hash scan to access the specified table. Transforms a NOT IN subquery into a hash anti-join to access the specified table. Transforms a NOT IN subquery into a hash semi-join to access the specified table. Explicitly chooses an index scan for the specified table. Explicitly chooses an ascending-range index scan for the specified table. If no indexes are given as arguments for the INDEX_COMBINE hint, the optimizer uses whatever Boolean combination of bitmap indexes has the best cost estimate. If particular indexes are given as arguments, the optimizer tries to use some Boolean combination of those particular bitmap indexes. Explicitly chooses a descending-range index scan for the specified table. Causes a fast full index scan to be performed rather than a full table scan. Transforms a NOT IN subquery into a merge anti-join to access the specified table. Transforms a correlated EXISTS subquery into a merge semijoin to access the specified table. Prevents the optimizer from considering OR expansion for queries having OR or IN conditions in the WHERE clause. Instructs the optimizer not to consider a scan on the specified index or indexes. If no indexes are specified, the optimizer does not consider a scan on any index defined on the table. Disables query rewrite for the query block, overriding a TRUE setting of the QUERY_REWRITE_ENABLED parameter. Description
/*+ INDEX_DESC(table index) */ /*+ INDEX_FFS(table index) */ /*+ MERGE_AJ(table) */ /*+ MERGE_SJ(table) */ /*+ NO_EXPAND */ /*+ NO_INDEX(table index) */
/*+ NOREWRITE */
Basic Elements of Oracle SQL
2-65
Comments
Table 215 (Cont.) Hint Syntax and Descriptions
Hint Syntax /*+ NO_UNNEST */ Description Prohibits the unnesting of the subquery. The hints HASH_SJ, HASH_AJ, MERGE_SJ, and MERGE_AJ take precedence over this hint. Forces the optimizer to preserve the order of predicate evaluation (except predicates used in index keys), as specified in the WHERE clause of SELECT statements. Enforces query rewrite. If you specify a view list and the list contains an eligible materialized view, Oracle will use that view regardless of the cost. No views outside of the list are considered. If you do not specify a view list, Oracle will search for an eligible materialized view and always use it regardless of the cost. Explicitly chooses a table scan by rowid for the specified table. Forces the unnesting of the subquery if possible. Forces combined OR conditions in the WHERE clause of a query to be transformed into a compound query using the UNION ALL set operator.
/*+ ORDERED_PREDICATES */
/*+ REWRITE (view [,...]) */
/*+ ROWID(table) */ /*+ UNNEST */ /*+ USE_CONCAT */
Join Orders /*+ ORDERED */ /*+ STAR */ Join Operations /*+ DRIVING_SITE(table) */ /*+ LEADING (table) */ /*+ USE_HASH(table) */ /*+ USE_MERGE(table) */ /*+ USE_NL(table) */ Forces query execution to be done at a different site from that selected by Oracle. Causes Oracle to use the specified table as the first table in the join order. The ORDERED hint overrides this hint. Causes Oracle to join each specified table with another row source with a hash join. Causes Oracle to join each specified table with another row source with a sort-merge join. Causes Oracle to join each specified table to another row source with a nested-loops join using the specified table as the inner table. Causes Oracle to join tables in the order in which they appear in the FROM clause. This hint overrides the LEADING hint. Forces the large table to be joined last using a nested-loops join on the index.
2-66
SQL Reference
Comments
Table 215 (Cont.) Hint Syntax and Descriptions
Hint Syntax Parallel Execution Note: Oracle ignores parallel hints on a temporary table. For more information on temporary tables, see "CREATE TABLE" on page 4-381 and Oracle8i Concepts. /*+ APPEND */ /*+ NOAPPEND */ /*+ NOPARALLEL(table) */ Specifies that data is simply appended (or not) to a table; existing free space is not used. Use these hints only following the INSERT keyword. Disables parallel scanning of a table, even if the table was created with a PARALLEL clause. Restriction: You cannot parallelize a query involving a nested table. /*+ PARALLEL(table) /*+ PARALLEL(table, integer) */ Lets you specify parallel execution of DML and queries on the table; integer specifies the desired degree of parallelism, which is the number of parallel threads that can be used for the operation. Each parallel thread may use one or two parallel execution servers. If you do not specify integer, Oracle computes a value using the PARALLEL_THREADS_PER_CPU parameter. If no parallel hint is specified, Oracle uses the existing degree of parallelism for the table. DELETE, INSERT, and UPDATE operations are considered for parallelization only if the session is in a PARALLEL DML enabled mode. (Use ALTER SESSION ENABLE PARALLEL DML to enter this mode.) /*+ PARALLEL_INDEX /*+ PQ_DISTRIBUTE (table, outer_distribution, inner_distribution) */ Allows you to parallelize fast full index scans for partitioned and nonpartitioned indexes that have the PARALLEL attribute. Specifies how rows of joined tables should be distributed between producer and consumer query servers. The four possible distribution methods are NONE, HASH, BROADCAST, and PARTITION. However, only a subset of the combinations of outer and inner distributions are valid. For the permitted combinations of distributions for the outer and inner join tables, see Oracle8i Designing and Tuning for Performance. Overrides a PARALLEL attribute setting on an index. Description
/*+ NOPARALLEL_INDEX */ Other Hints /*+ CACHE */
Specifies that the blocks retrieved for the table in the hint are placed at the most recently used end of the LRU list in the buffer cache when a full table scan is performed.
Basic Elements of Oracle SQL
2-67
Database Objects
Table 215 (Cont.) Hint Syntax and Descriptions
Hint Syntax /*+ NOCACHE */ Description Specifies that the blocks retrieved for this table are placed at the least recently used end of the LRU list in the buffer cache when a full table scan is performed. Causes Oracle to evaluate complex views or subqueries before the surrounding query. Causes Oracle not to merge mergeable views. Causes the optimizer to evaluate, on a cost basis, whether to push individual join predicates into the view. Prevents pushing of a join predicate into the view. Causes nonmerged subqueries to be evaluated at the earliest possible place in the execution plan. Makes the optimizer use the best plan in which the transformation has been used.
/*+ MERGE(table) */ /*+ NO_MERGE(table) */ /*+ PUSH_JOIN_PRED(table) */ /*+ NO_PUSH_JOIN_PRED(table) */ /*+ PUSH_SUBQ */ /*+ STAR_TRANSFORMATION */
Database Objects
Oracle recognizes objects that are associated with a particular schema and objects that are not associated with a particular schema, as described in the sections that follow.
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:
s
clusters database links database triggers dimensions external procedure libraries index-organized tables indexes
s
s
s
s
s
s
2-68
SQL Reference
Database Objects
s
indextypes Java classes, Java resources, Java sources materialized views / snapshots materialized view logs / snapshot logs object tables object types object views operators packages sequences stored functions, stored procedures synonyms tables views
s
s
s
s
s
s
s
s
s
s
s
s
s
Nonschema Objects
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:
s
contexts directories profiles roles rollback segments tablespaces users
s
s
s
s
s
s
In this reference, each type of object is briefly defined in Chapter 7, "SQL Statements", in the section describing the statement that creates the database object. These statements begin with the keyword CREATE. For example, for the definition of a cluster, see "CREATE CLUSTER" on page 7-254. For an overview of database objects, see Oracle8i Concepts.
Basic Elements of Oracle SQL
2-69
Database Objects
You must provide names for most types of schema objects when you create them. These names must follow the rules listed in the following sections.
Parts of Schema Objects
Some schema objects are made up of parts that you can or must name, such as:
s
columns in a table or view index and table partitions and subpartitions integrity constraints on a table packaged procedures, packaged stored functions, and other objects stored within a package
s
s
s
Partitioned Tables and Indexes
Tables and indexes can be partitioned. When partitioned, these schema objects consist of a number of parts called partitions, all of which have the same logical attributes. For example, all partitions in a table share the same column and constraint definitions, and all partitions in an index share the same index columns. When you partition a table or index using the range method, you specify a maximum value for the partitioning key column(s) for each partition. When you partition a table or index using the hash method, you instruct Oracle to distribute the rows of the table into partitions based on a system-defined hash function on the partitioning key column(s). When you partition a table or index using the composite-partitioning method, you specify ranges for the partitions, and Oracle distributes the rows in each partition into one or more hash subpartitions based on a hash function. Each subpartition of a table or index partitioned using the composite method has the same logical attributes.
Partition-Extended and Subpartition-Extended Table Names
Partition-extended and subpartition-extended table names let you perform some partition-level and subpartition-level operations, such as deleting all rows from a partition or subpartition, on only one partition or subpartition. Without extended table names, such operations would require that you specify a predicate (WHERE clause). For range-partitioned tables, trying to phrase a partition-level operation with a predicate can be cumbersome, especially when the range partitioning key uses more than one column. For hash partitions and subpartitions, using a predicate is more difficult still, because these partitions and subpartitions are based on a system-defined hash function.
2-70
SQL Reference
Database Objects
Partition-extended table names let you use partitions as if they were tables. An advantage of this method, which is most useful for range-partitioned tables, is that you can build partition-level access control mechanisms by granting (or revoking) privileges on these views to (or from) other users or roles.To use a partition as a table, create a view by selecting data from a single partition, and then use the view as a table. You can specify partition-extended or subpartition-extended table names for the following DML statements:
s
DELETE INSERT LOCK TABLE SELECT UPDATE
Note: For application portability and ANSI syntax compliance,
s
s
s
s
Oracle strongly recommends that you use views to insulate applications from this Oracle proprietary extension.
The basic syntax for using partition-extended and subpartition-extended table names is:
Syntax
@ dblink PARTITION schema . table view SUBPARTITION ( ( partition ) )
subpartition
Restrictions Currently, the use of partition-extended and subpartition-extended
table names has the following restrictions:
s
No remote tables: A partition-extended or subpartition-extended table name cannot contain a database link (dblink) or a synonym that translates to a table with a dblink. To use remote partitions and subpartitions, create a view at the remote site that uses the extended table name syntax and then refer to the remote view.
Basic Elements of Oracle SQL
2-71
Schema Object Names and Qualifiers
s
No synonyms: A partition or subpartition extension must be specified with a base table. You cannot use synonyms, views, or any other objects.
Example In the following statement, SALES is a partitioned table with partition
JAN97. You can create a view of the single partition JAN97, and then use it as if it were a table. This example deletes rows from the partition.
CREATE VIEW sales_jan97 AS SELECT * FROM sales PARTITION (jan97); DELETE FROM sales_jan97 WHERE amount < 0;
Schema Object Names and Qualifiers
This section provides:
s
rules for naming schema objects and schema object location qualifiers guidelines for naming schema objects and qualifiers
s
Schema Object Naming Rules
The following rules apply when naming schema objects:
1.
Names must be from 1 to 30 bytes long with these exceptions:
s
Names of databases are limited to 8 bytes. Names of database links can be as long as 128 bytes.
s
2. 3. 4. 5.
Names cannot contain quotation marks. Names are not case sensitive. A name must begin with an alphabetic character from your database character set unless surrounded by double quotation marks. Names can contain only alphanumeric characters from your database character set and the underscore (_), dollar sign ($), and pound sign (#). Oracle strongly discourages you from using $ and #. Names of database links can also contain periods (.) and "at" signs (@). If your database character set contains multibyte characters, Oracle recommends that each name for a user or a role contain at least one single-byte character.
2-72
SQL Reference
Schema Object Names and Qualifiers
Note: You cannot use special characters from European or Asian
character sets in a database name, global database name, or database link names. For example, characters with an umlaut are not allowed.
6.
A name cannot be an Oracle reserved word. Appendix C, "Oracle Reserved Words", lists all Oracle reserved words. Depending on the Oracle product you plan to use to access a database 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 PL/SQL User's Guide and Reference.
7. 8.
Do not use the word DUAL as a name for an object or part. DUAL is the name of a dummy table. The Oracle SQL language contains other words that have special meanings. These words include datatypes (see "Datatypes" on page 2-9), function names (see "SQL Functions" on page 4-2), and keywords (the uppercase words in SQL statements, such as DIMENSION, SEGMENT, ALLOCATE, DISABLE, and so forth). These words are not reserved. However, Oracle uses them internally. Therefore, if you use these words as names for objects and object parts, your SQL statements may be more difficult to read and may lead to unpredictable results. In particular, do not use words beginning with "SYS_" as schema object names, and do not use the names of SQL built-in functions for the names of schema objects or user-defined functions.
9.
Within a namespace, no two objects can have the same name. The following figure shows the namespaces for schema objects. Each box is a namespace. Tables and views are in the same namespace. Therefore, a table and a view in the same schema cannot have the same name. However, tables and indexes are in different namespaces. Therefore, a table and an index in the same schema can have the same name.
Basic Elements of Oracle SQL
2-73
Schema Object Names and Qualifiers
TABLES VIEWS
INDEXES
CONSTRAINTS SEQUENCES PRIVATE SYNONYMS STAND-ALONE PROCEDURES STAND-ALONE STORED FUNCTIONS PACKAGES MATERIALIZED VIEWS/ SNAPSHOTS USER-DEFINED TYPES PRIVATE DATABASE LINKS DATABASE TRIGGERS CLUSTERS
DIMENSIONS
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. The following figure shows the namespaces for nonschema objects. Because the objects in these namespaces are not contained in schemas, these namespaces span the entire database.
USER ROLES PUBLIC SYNONYMS PUBLIC DATABASE LINKS TABLESPACES ROLLBACK SEGMENTS PROFILES
10. Columns in the same table or view cannot have the same name. However,
columns in different tables or views can have the same name.
11. 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.
2-74
SQL Reference
Schema Object Names and Qualifiers
12. A name can be enclosed in double quotation marks. Such names can contain
any combination of characters, including spaces, ignoring rules 3 through 7 in this list. This exception is allowed for portability, but Oracle recommends that you do not break rules 3 through 7. If you give a schema object a name enclosed in double quotation marks, you must use double quotation marks whenever you refer to the object. Enclosing a name in double quotes allows it to:
s
Contain spaces Be case sensitive Begin with a character other than an alphabetic character, such as a numeric character Contain characters other than alphanumeric characters and _, $, and # Be a reserved word
s
s
s
s
By enclosing names in double quotation marks, you can give the following names to different objects in the same namespace:
emp "emp" "Emp" "EMP "
Note that Oracle interprets the following names 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.
Schema Object Naming Examples
The following examples are valid schema object names:
ename horse scott.hiredate
Basic Elements of Oracle SQL
2-75
Referring to Schema Objects and Parts
"EVEN THIS & THAT!" a_very_long_and_valid_name
Although column aliases, table aliases, usernames, and passwords are not objects or parts of objects, they must also follow these naming rules with these exceptions:
s
Column aliases and table aliases exist only for the execution of a single SQL statement and are not stored in the database, so rule 12 does not apply to them. Passwords do not have namespaces, so rule 9 does not apply to them. Do not use quotation marks to make usernames and passwords case sensitive. For additional rules for naming users and passwords, see "CREATE USER" on page 7-451.
s
s
Schema Object Naming Guidelines
Here are several helpful guidelines for naming objects and their parts:
s
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.
s
s
When naming objects, balance the objective of keeping names short and easy to use with the objective of making names as 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 a name 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 sample EMP and DEPT tables are both named DEPTNO.
Referring to Schema Objects and Parts
This section tells you how to refer to schema objects and their parts in the context of a SQL statement. This section shows you:
s
the general syntax for referring to an object
2-76
SQL Reference
Referring to Schema Objects and Parts
s
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
s
s
The following diagram shows the general syntax for referring to an object or a part:
schema
. object
.
part
@
dblink
where: object schema is the name of the object. is the schema containing the object. The schema qualifier allows you to refer to an object in a schema other than your own. You must be granted privileges to refer to objects in other schemas. If you omit schema, 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 with list item 9 on page 2-73. Nonschema objects, also shown with list item 9 on page 2-73, cannot be qualified with schema because they are not schema objects. (An exception is public synonyms, which can optionally be qualified with "PUBLIC". The quotation marks are required.) part is a part of the object. This identifier allows you to refer to a part of a schema object, such as a column or a partition of a table. Not all types of objects have parts. applies only when you are using Oracle's distributed functionality. This is the name of the database containing the object. The dblink qualifier lets you refer to an object in a database other than your local database. If you omit dblink, Oracle assumes that you are referring to an object in your local database. Not all SQL statements allow you to access objects on remote databases.
dblink
You can include spaces around the periods separating the components of the reference to the object, but it is conventional to omit them.
Basic Elements of Oracle SQL
2-77
Referring to Schema Objects and Parts
How Oracle Resolves Schema 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. The following 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:
s
A table in your own schema A view in your own schema A private synonym for a table or view A public synonym
s
s
s
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 as follows:
1.
First, Oracle attempts to locate the object in the namespace in your own schema containing tables, views, and private synonyms. 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. 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. If the object is not in any namespace searched in thus far, Oracle searches the namespace containing public synonyms. If the object is in that 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. In this example, if DEPT is a public synonym for a sequence, Oracle returns an error.
2.
3.
2-78
SQL Reference
Referring to Schema Objects and Parts
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 link to that database. A database link is a schema object that causes Oracle to connect to a remote database to access an object there. This section tells you:
s
How to create database links How to use database links in your SQL statements
s
Creating Database Links
You create a database link with the CREATE DATABASE LINK statement described in Chapter 7, "SQL Statements". The statement allows you to specify this information about the database link:
s
The name of the database link The database connect string to access the remote database The username and password to connect to the remote database
s
s
Oracle stores this information in the data dictionary. Database Link Names When you create a database link, you must specify its name. Database link names are different from names of other types of objects. They can be as long as 128 bytes and can contain periods (.) and the "at" sign (@). 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. The following syntax diagram shows the form of the name of a database link:
Basic Elements of Oracle SQL
2-79
Referring to Schema Objects and Parts
dblink::=
. database
domain
@
connect_descriptor
where: database should specify name portion of the global name of the remote database to which the database link connects. This global name is stored in the data dictionary of the remote database; you can see this name in the GLOBAL_NAME view. should specify the domain portion of the global name of the remote database to which the database link connects. If you omit domain from the name of a database link, Oracle qualifies the database link name with the domain of your local database as it currently exists in the data dictionary. allows you to further qualify a database link. Using connect descriptors, you can create multiple database links to the same database. For example, you can use connect descriptors to create multiple database links to different instances of the Oracle Parallel Server that access the same database.
domain
connect_descriptor
The combination database.domain is sometimes called the "service name".
See Also: Net8 Administrator's Guide.
Username and Password Oracle uses the username and password to connect to the remote database. The username and password for a database link are optional. Database Connect String The database connect string is the specification used by Net8 to access the remote database. For information on writing database connect strings, see the Net8 documentation for your specific network protocol. The database string for a database link is optional.
2-80
SQL Reference
Referring to Schema Objects and Parts
Referring to Database Links
Database links are available only if you are using Oracle's distributed functionality. 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 connect_descriptor components. is the database and optional connect_descriptor components, but not the domain component.
partial
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 as found in the global database name stored in the data dictionary. (You can see the current global database name in the GLOBAL_NAME data dictionary view.) Oracle first searches for a private database link in your own schema with the same name as the database link in the statement. Then, if necessary, it searches for a public database link with the same name.
s
2.
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 no matching database link is found, or if no matching link has an associated database string, Oracle returns an error.
s
3.
Oracle uses the database string to access the remote database. After accessing the remote database, if the value of the GLOBAL_NAMES parameter is TRUE, Oracle verifies that the database.domain portion of the database link name matches the complete global name of the remote database. If this condition is true, Oracle proceeds with the connection, using the username and password chosen in Step 2. If not, Oracle returns an error. 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 discussed earlier in this section.
4.
Basic Elements of Oracle SQL
2-81
Referring to Schema Objects and Parts
You can disable the requirement that the database.domain portion of the database link name must match the complete global name of the remote database by setting to FALSE the initialization parameter GLOBAL_NAMES or the GLOBAL_NAMES parameter of the ALTER SYSTEM or ALTER SESSION statement.
See Also: Oracle8i Distributed Database Systems for more information on remote name resolution.
Referencing Object Type Attributes and Methods
To reference object type attributes or methods in a SQL statement, you must fully qualify the reference with a table alias. Consider the following example:
CREATE TYPE person AS OBJECT (ssno VARCHAR(20), name VARCHAR (10)); CREATE TABLE emptab (pinfo person);
In a SQL statement, reference to the SSNO attribute must be fully qualified using a table alias, as illustrated below:
SELECT e.pinfo.ssno FROM emptab e; UPDATE emptab e SET e.pinfo.ssno = '510129980' WHERE e.pinfo.name = 'Mike';
To reference an object type's member method that does not accept arguments, you must provide "empty" parentheses. For example, assume that AGE is a method in the person type that does not take arguments. In order to call this method in a SQL statement, you must provide empty parentheses as shows in this example:
SELECT e.pinfo.age() FROM emptab e WHERE e.pinfo.name = 'Mike';
See Also: Oracle8i Concepts for more information on user-defined
datatypes.
2-82
SQL Reference
3
Operators
With affection beaming in one eye, and calculation shining out of the other. Charles Dickens, Martin Chuzzlewit An operator manipulates individual data items and returns a result. The data 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. This chapter discusses the following topics:
s
Unary and Binary Operators Precedence Arithmetic Operators Concatenation Operator Comparison Operators Logical Operators Set Operators Other Built-In Operators User-Defined Operators
s
s
s
s
s
s
s
s
Unary and Binary Operators
The two general classes of operators are:
Operators 3-1
Precedence
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 operand, the result is always null. The only operator that does not follow this rule is concatenation (||).
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 31 lists the levels of precedence among SQL operators from high to low. Operators listed on the same line have the same precedence.
Table 31 SQL Operator Precedence
Operator +, *, / +, -, || Operation identity, negation multiplication, division addition, subtraction, concatenation
=, !=, <, >, <=, >=, IS NULL, LIKE, comparison BETWEEN, IN NOT AND OR exponentiation, logical negation conjunction disjunction
Example In the following expression, multiplication has a higher precedence than
addition, so Oracle first multiplies 2 by 3 and then adds the result to 1.
1+2*3
3-2 SQL Reference
Concatenation Operator
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.
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 32 lists arithmetic operators.
Table 32
Operator +-
Arithmetic Operators
Purpose Denotes a positive or negative expression. These are unary operators. Multiplies, divides. These are binary operators. Adds, subtracts. These are binary operators. Example SELECT * FROM orders WHERE qtysold = -1; SELECT * FROM emp WHERE -sal < 0; UPDATE emp SET sal = sal * 1.1; SELECT sal + comm FROM emp WHERE SYSDATE - hiredate > 365;
*/ +-
Do not use two consecutive minus signs (--) 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.
See Also: "Comments" on page 2-62 for more information on comments within SQL statements.
Concatenation Operator
The concatenation operator manipulates character strings. Table 33 describes the concatenation operator.
Operators 3-3
Concatenation Operator
Table 33
Operator ||
Concatenation Operator
Purpose Concatenates character strings. Example SELECT 'Name is ' || ename FROM emp;
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 2000 characters. If either string is of datatype VARCHAR2, the result has datatype VARCHAR2 and is limited to 4000 characters. Trailing blanks in character strings are preserved by concatenation, regardless of the strings' datatypes. On most platforms, the concatenation operator is two solid vertical bars, as shown in Table 33. However, some IBM platforms use broken vertical bars for this operator. When moving SQL script files between systems having different character sets, such as between ASCII and EBCDIC, vertical bars might not be translated into the vertical bar required by the target Oracle environment. Oracle provides the CONCAT character function as an alternative to the vertical bar operator for cases when it is difficult or impossible to control translation performed by operating system or network utilities. Use this function in applications that will be moved between environments with differing character sets. Although Oracle treats zero-length character strings as nulls, concatenating a zerolength character string with another operand always results in the other operand, so null can result only from the concatenation of two null strings. 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.
See Also: "Character Datatypes" on page 2-14 for more
information on the differences between the CHAR and VARCHAR2 datatypes.
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 and concatenates 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) ); Table created.
3-4 SQL Reference
Comparison Operators
INSERT INTO tab1 (col1, col2, VALUES ('abc', 'def 1 row created.
col3, ', 'ghi
col4) ', 'jkl');
SELECT col1||col2||col3||col4 "Concatenation" FROM tab1; Concatenation -----------------------abcdef ghi jkl
Comparison Operators
Comparison operators compare one expression with another. The result of such a comparison can be TRUE, FALSE, or UNKNOWN. For information on conditions, see "Conditions" on page 5-14. Table 34 lists comparison operators.
Table 34
Operator =
Comparison Operators
Purpose Equality test. Example SELECT * FROM emp WHERE sal = 1500; SELECT * FROM emp WHERE sal != 1500; SELECT * FROM WHERE sal > SELECT * FROM WHERE sal < emp 1500; emp 1500;
!= ^= <> = > < >= <=
Inequality test. Some forms of the inequality operator may be unavailable on some platforms. "Greater than" and "less than" tests.
"Greater than or equal to" and "less than or equal to" tests.
SELECT * FROM emp WHERE sal >= 1500; SELECT * FROM emp WHERE sal <= 1500;
Operators 3-5
Comparison Operators
Table 34
Operator IN
(Cont.) Comparison Operators
Purpose "Equal to any member of" test. Equivalent to "= ANY". Example SELECT * FROM emp WHERE job IN ('CLERK','ANALYST'); SELECT * FROM emp WHERE sal IN (SELECT sal FROM emp WHERE deptno = 30);
NOT IN
Equivalent to "!=ALL". Evaluates SELECT * FROM emp to FALSE if any member of the set WHERE sal NOT IN is NULL. (SELECT sal FROM emp WHERE deptno = 30); SELECT * FROM emp WHERE job NOT IN ('CLERK', ANALYST'); Compares a value to each value in SELECT * FROM emp a list or returned by a query. Must WHERE sal = ANY be preceded by =, !=, >, <, <=, >=. (SELECT sal FROM emp WHERE deptno = 30); Evaluates to FALSE if the query returns no rows. Compares a value to every value in a list or returned by a query. Must be preceded by =, !=, >, <, <=, >=. Evaluates to TRUE if the query returns no rows. SELECT * FROM emp WHERE sal >= ALL ( 1400, 3000);
ANY SOME
ALL
[NOT] BETWEEN x AND y EXISTS
[Not] greater than or equal to x and less than or equal to y. TRUE if a subquery returns at least one row.
SELECT * FROM emp WHERE sal BETWEEN 2000 AND 3000; SELECT ename, deptno FROM dept WHERE EXISTS (SELECT * FROM emp WHERE dept.deptno = emp.deptno);
3-6 SQL Reference
Comparison Operators
Table 34
Operator
(Cont.) Comparison Operators
Purpose Example
See "LIKE Operator" on TRUE if x does [not] match the pattern y. Within y, the character page 3-8. "%" matches any string of zero or SELECT * FROM tab1 WHERE col1 LIKE [ESCAPE 'z'] more characters except null. The character "_" matches any single 'A_C/%E%' ESCAPE '/'; character. Any character, excepting percent (%) and underbar (_) may follow ESCAPE. A wildcard character is treated as a literal if preceded by the character designated as the escape character. x [NOT] LIKE y IS [NOT] NULL Tests for nulls. This is the only operator that you should use to test for nulls. See "Nulls" on page 2-54. SELECT ename, deptno FROM emp WHERE comm IS NULL;
Additional information on the NOT IN and LIKE operators appears in the sections that follow.
NOT IN Operator
If any item in the list following a NOT IN operation is null, all rows evaluate to UNKNOWN (and no rows are returned). For example, the following statement returns the string 'TRUE' for each row:
SELECT 'TRUE' FROM emp WHERE deptno NOT IN (5,15);
However, the following statement returns no rows:
SELECT 'TRUE' FROM emp WHERE deptno NOT IN (5,15,null);
The above example returns no rows because the WHERE clause condition evaluates to:
deptno != 5 AND deptno != 15 AND deptno != null
Operators 3-7
Comparison Operators
Because all conditions that compare a null result in a 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:
NOT char1 LIKE char2
ESCAPE
'
esc_char
'
where: char1 NOT is a value to be compared with a pattern. This value can have datatype CHAR or VARCHAR2. logically inverts the result of the condition, returning FALSE if the condition evaluates to TRUE and TRUE if it evaluates to FALSE. 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 _. 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. If you wish to search for strings containing an escape character, you must specify this character twice. For example, if the escape character is '/', to search for the string 'client/server', you must specify, 'client//server'. Whereas 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. Note that blank padding is not used for LIKE comparisons. With the LIKE operator, you can compare a value to a pattern rather than to a constant. The pattern must 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':
char2
ESCAPE
3-8 SQL Reference
Comparison Operators
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 typically use special characters that Oracle matches with different characters in the value:
s
An underscore (_) in the pattern matches exactly one character (as opposed to one byte in a multibyte character set) in the value. A percent sign (%) in the pattern can match zero or more characters (as opposed to bytes in a multibyte character set) in the value. Note that the pattern '%' cannot match a null.
s
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%'
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.
Example 1
This condition is true for all ENAME values beginning with "MA":
Operators 3-9
Comparison Operators
ename LIKE 'MA%'
All of these ENAME values make the condition TRUE:
MARTIN, MA, MARK, MARY
Case is significant, so ENAME values beginning with "Ma," "ma," and "mA" make the condition FALSE.
Example 2
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 "_" then Oracle interprets this character literally in the pattern, rather than as a special pattern matching character.
Example:
To search for 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 be TRUE only if both operands have the same length.
Example:
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');
3-10
SQL Reference
Logical Operators
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.
Logical Operators
A logical operator combines the results of two component conditions to produce a single result based on them or to invert the result of a single condition. Table 35 lists logical operators.
Table 35 Logical Operators
Operator NOT Function Example
Returns TRUE if the following SELECT * condition is FALSE. Returns FROM emp FALSE if it is TRUE. If it is WHERE NOT (job IS NULL); UNKNOWN, it remains SELECT * UNKNOWN. FROM emp WHERE NOT (sal BETWEEN 1000 AND 2000); Returns TRUE if both SELECT * component conditions are FROM emp TRUE. Returns FALSE if either WHERE job = 'CLERK' is FALSE. Otherwise returns AND deptno = 10; UNKNOWN. Returns TRUE if either SELECT * component condition is TRUE. FROM emp Returns FALSE if both are WHERE job = 'CLERK' FALSE. Otherwise returns OR deptno = 10; UNKNOWN.
AND
OR
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 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 36 shows the result of applying the NOT operator to a condition.
Operators
3-11
Set Operators
Table 36
NOT Truth Table
TRUE FALSE TRUE UNKNOWN UNKNOWN
NOT
FALSE
AND Operator
Table 37 shows the results of combining two expressions with AND.
Table 37
AND TRUE FALSE UNKNOWN
AND Truth Table
TRUE TRUE FALSE UNKNOWN FALSE FALSE FALSE FALSE UNKNOWN UNKNOWN FALSE UNKNOWN
OR Operator
Table 38 shows the results of combining two expressions with OR.
Table 38
OR TRUE FALSE UNKNOWN
OR Truth Table
TRUE TRUE TRUE TRUE FALSE TRUE FALSE UNKNOWN UNKNOWN TRUE UNKNOWN UNKNOWN
Set Operators
Set operators combine the results of two component queries into a single result. Queries containing set operators are called compound queries. Table 39 lists SQL set operators.
3-12
SQL Reference
Set Operators
Table 39
Operator UNION UNION ALL INTERSECT MINUS
Set Operators
Returns All rows selected by either query. All rows selected by either query, including all duplicates. All distinct rows selected by both queries. All distinct rows selected by the first query but not the second.
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. The corresponding 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:
s
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.
s
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
Operators
3-13
Set Operators
The following examples combine the two query results with each of the set operators.
UNION Example The following statement combines the results with the UNION
operator, which eliminates duplicate selected rows. This statement shows how datatype must match when columns do not exist in one or the other table:
SELECT part, partnum, to_date(null) date_in FROM orders_list1 UNION SELECT part, to_date(null), date_in FROM orders_list2; PART ---------SPARKPLUG SPARKPLUG FUEL PUMP FUEL PUMP TAILPIPE TAILPIPE CRANKSHAFT CRANKSHAFT PARTNUM DATE_IN ------- -------3323165 10/24/98 3323162 12/24/99 1332999 01/01/01 9394991 09/12/02
SELECT part FROM orders_list1 UNION SELECT part FROM orders_list2; PART ---------SPARKPLUG FUEL PUMP TAILPIPE CRANKSHAFT
UNION ALL Example The following 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
3-14
SQL Reference
Set Operators
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 The following 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 The following statement combines results with the MINUS
operator, which returns only rows returned by the first query but not by the second:
SELECT part FROM orders_list1 MINUS SELECT part FROM orders_list2; PART ---------SPARKPLUG FUEL PUMP
Operators
3-15
Other Built-In Operators
Other Built-In Operators
Table 310 lists other SQL operators.
Table 310
Operator (+)
Other SQL Operators
Purpose Indicates that the preceding column is the outer join column in a join. See "Outer Joins" on page 5-23. Example SELECT ename, dname FROM emp, dept WHERE dept.deptno = emp.deptno(+); SELECT empno, ename, mgr FROM emp CONNECT BY PRIOR empno = mgr;
PRIOR
Evaluates the following expression for the parent row of the current row in a hierarchical, or tree-structured, 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 performs a hierarchical query. The PRIOR operator is a unary operator and has the same precedence as the unary + and arithmetic operators. See "Hierarchical Queries" on page 5-20.
User-Defined Operators
Like built-in operators, user-defined operators take a set of operands as input and return a result. However, you create them with the CREATE OPERATOR statement, and they are identified by names (e.g., MERGE). They reside in the same namespace as tables, views, types, and stand-alone functions. Once you have defined a new operator, you can use it in SQL statements like any other built-in operator. For example, you can use user-defined operators in the select list of a SELECT statement, the condition of a WHERE clause, or in ORDER BY clauses and GROUP BY clauses. However, you must have EXECUTE privilege on the operator to do so, because it is a user-defined object. For example, if you define an operator CONTAINS, which takes as input a text document and a keyword and returns 1 if the document contains the specified keyword, you can then write the following SQL query:
SELECT * FROM emp WHERE contains (resume, 'Oracle and UNIX') = 1;
See Also: "CREATE OPERATOR" on page 7-339 and Oracle8i Data Cartridge Developer's Guide for more information on user-defined operators.
3-16
SQL Reference
4
Functions
Form ever follows function. Louis Henri Sullivan, The Tall Office Building Artistically Considered Functions are similar to operators in that they manipulate data items and return a result. Functions differ from operators in the format of their arguments. This format allows them to operate on zero, one, two, or more arguments:
function(argument, argument, ...)
This chapter describes two types of functions:
s
SQL Functions User-Defined Functions
s
Functions 4-1
SQL Functions
SQL Functions
SQL functions are built into Oracle and are available for use in various appropriate SQL statements. Do not confuse SQL functions with user functions written in PL/ SQL. User functions are described in "User-Defined Functions" on page 4-118. For information about functions used with Oracle interMedia, see Oracle8i interMedia Audio, Image, and Video User's Guide and Reference. If you call a SQL function with an argument of a datatype other than the datatype expected by the SQL function, Oracle implicitly converts the argument to the expected datatype before performing the SQL function. See "Data Conversion" on page 2-36. If you call a SQL function with a null argument, the SQL function automatically returns null. The only SQL functions that do not necessarily follow this behavior are CONCAT, NVL, and REPLACE. In the syntax diagrams for SQL functions, arguments are indicated by their datatypes, following the conventions described in "Syntax Diagrams and Notation" in the Preface of this reference. When the parameter "function" appears in SQL syntax, replace it with one of the functions described in this section. Functions are grouped by the datatypes of their arguments and their return values. The general syntax is as follows: function::=
single_row_function aggregate_function analytic_function object_reference_function user_defined_function
4-2 SQL Reference
SQL Functions
single_row_function::=
number_function character_function date_function conversion_function miscellaneous_single_row_function
The sections that follow list the built-in SQL functions in each of the groups illustrated above except user-defined functions. All of the built-in SQL functions are then described in alphabetical order. User-defined functions are described at the end of this chapter. The examples provided with the function descriptions use the EMP and DEPT tables that are part of the SCOTT schema in your sample Oracle database. Many examples also use a SALES table, which has the following contents:
REGION PRODUCT S_DAY S_MONTH S_YEAR S_AMOUNT ------ ------- ------ ---------- ---------- ---------200 1 10 6 1998 77586 200 1 26 8 1998 62109 200 1 11 11 1998 46632 200 1 14 4 1999 15678 201 1 9 6 1998 77972 201 1 25 8 1998 62418 201 1 10 11 1998 46864 201 1 13 4 1999 15756 200 2 9 6 1998 39087 200 2 25 8 1998 31310 200 2 10 11 1998 23533 200 2 13 4 1999 7979 201 2 9 11 1998 23649.5 201 2 12 4 1999 8018.5 200 3 9 11 1998 15834 200 3 12 4 1999 5413.33 201 3 11 4 1999 5440 200 4 11 4 1999 4131 201 4 10 4 1999 4151.25 200 5 10 4 1999 3362 201 5 5 6 1998 16068 201 5 21 8 1998 12895.6 201 5 9 4 1999 3378.4 S_PROFIT -------586 509 432 278 587 510 433 279 293.5 255 216.5 139.5 217 140 144.67 93.33 93.67 70.25 70.5 56.4 118.2 102.8 56.6
Functions 4-3
SQL Functions
Single-Row Functions
Single-row functions return a single result row for every row of a queried table or view. These functions can appear in select lists, WHERE clauses, START WITH clauses, and CONNECT BY clauses.
Number Functions
Number functions accept numeric input and return numeric values. 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, and TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN, ATAN, and ATAN2 are accurate to 30 decimal digits. The number functions are:
ABS ACOS ADD_MONTHS ATAN ATAN2 CEIL COS COSH EXP FLOOR LN LOG MOD POWER ROUND (Number Function) SIGN SIN SINH SQRT TAN TANH TRUNC (Number Function)
Character Functions Returning Character Values
Character functions that return character values, unless otherwise noted, return values with the datatype VARCHAR2 and are limited in length to 4000 bytes. Functions that return values of datatype CHAR are limited in length to 2000 bytes. If the length of the return value exceeds the limit, Oracle truncates it and returns the result without an error message. The character functions that return character values are:
4-4 SQL Reference
SQL Functions
CHR CONCAT INITCAP LOWER LPAD LTRIM NLS_INITCAP
NLS_LOWER NLSSORT NLS_UPPER REPLACE RPAD RTRIM SOUNDEX
SUBSTR SUBSTRB TRANSLATE TRIM UPPER
Character Functions Returning Number Values
The character functions that return number values are:
ASCII INSTR INSTRB LENGTH LENGTHB
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. The date functions are:
ADD_MONTHS LAST_DAY MONTHS_BETWEEN NEW_TIME NEXT_DAY ROUND (Date Function) SYSDATE TRUNC (Date Function)
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 second datatype is the output datatype. The SQL conversion functions are:
Functions 4-5
SQL Functions
CHARTOROWID CONVERT HEXTORAW NUMTODSINTERVAL NUMTOYMINTERVAL RAWTOHEX
ROWIDTOCHAR TO_CHAR (date conversion) TO_CHAR (number conversion) TO_DATE
TO_LOB TO_MULTI_BYTE TO_NUMBER TO_SINGLE_BYTE TRANSLATE ... USING
Miscellaneous Single-Row Functions
The following single-row functions do not fall into any of the other single-row function categories.
BFILENAME DUMP EMPTY_[B | C]LOB GREATEST LEAST NLS_CHARSET_DECL_LEN NLS_CHARSET_ID NLS_CHARSET_NAME NVL NVL2 SYS_CONTEXT SYS_GUID UID USER USERENV VSIZE
Aggregate Functions
Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause, the elements of the select list can be aggregate functions, GROUP BY expressions, constants, or expressions involving one of these. Oracle applies the aggregate functions to each group of rows and returns a single result row for each group. If you omit the GROUP BY clause, Oracle applies aggregate functions in the select list to all the rows in the queried table or view. You use aggregate functions in the HAVING clause to eliminate groups from the output based on the results of the aggregate functions, rather than on the values of the individual rows of the queried table or view.
See Also: In the description of SELECT, the "GROUP BY Examples" on page 7-582 and the "HAVING" clause on page 7-579 for more information on the GROUP BY clause and HAVING clauses.
4-6 SQL Reference
SQL Functions
Many (but not all) aggregate functions that take a single argument accept these options:
s
DISTINCT causes an aggregate function to consider only distinct values of the argument expression. ALL causes an aggregate function to consider all values, including all duplicates.
s
For example, the DISTINCT average of 1, 1, 1, and 3 is 2. The ALL average is 1.5. If you specify neither option, the default is ALL. All aggregate functions except COUNT(*) and GROUPING ignore nulls. You can use the NVL function in the argument to an aggregate function to substitute a value for a null. COUNT never returns null, but returns either a number or zero. For all the remaining aggregate functions, if the data set contains no rows, or contains only rows with nulls as arguments to the aggregate function, then the function returns null. The aggregate functions are:
AVG CORR COUNT COVAR_POP COVAR_SAMP GROUPING MAX MIN REGR_ (linear regression) functions STDDEV STDDEV_POP STDDEV_SAMP SUM VAR_POP VAR_SAMP VARIANCE
Analytic Functions
Analytic functions compute an aggregate value based on a group of rows. The group of rows is called a window and is defined by the analytic clause. For each row, a "sliding" window of rows is defined. The window determines the range of rows used to perform the calculations for the "current row". Window sizes can be based on either a physical number of rows or a logical interval such as time. Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause. Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates.
Functions 4-7
SQL Functions
analytic_function::=
arguments analytic_function ( ) OVER ( analytic_clause )
analytic_clause::=
windowing_clause query_partition_clause ORDER_BY_clause
query_partition_clause::=
, PARTITION BY value_expr
ORDER_BY_clause::=
, ASC expr ORDER BY position c_alias DESC NULLS NULLS FIRST LAST
windowing_clause::=
UNBOUNDED BETWEEN ROWS RANGE UNBOUNDED CURRENT value_expr CURRENT PRECEDING ROW PRECEDING value_expr FOLLOWING PRECEDING ROW PRECEDING value_expr FOLLOWING AND UNBOUNDED CURRENT FOLLOWING ROW PRECEDING
4-8 SQL Reference
SQL Functions
The keywords and parameters of this syntax are:
analytic_function is the name of an analytic function (see the listings of different types of analytic functions following this table). arguments OVER analytic_clause Analytic functions take 0 to 3 arguments. indicates that the function operates on a query result set. That is, it is computed after the FROM, WHERE, GROUP BY, and HAVING clauses. You can specify analytic functions with this clause in the select list or ORDER BY clause. To filter the results of a query based on an analytic function, nest these functions within the parent query, and then filter the results of the nested subquery.
query_partition_clause
PARTITION BY partitions the query result set into groups based on one or more value_expr. If you omit this clause, the function treats all rows of the query result set as a single group. You can specify multiple analytic functions in the same query, each with the same or different PARTITION BY keys. Note: If the objects being queried have the parallel attribute, and if you specify an analytic function with the query_partition_clause, then the function computations are parallelized as well.
value_expr
Valid value expressions are constants, columns, nonanalytic functions, function expressions, or expressions involving any of these.
ORDER_BY_clause
ORDER BY specifies how data is ordered within a partition. You can order the values in a partition on multiple keys, each defined by a value_expr and each qualified by an ordering sequence. Within each function, you can specify multiple ordering expressions. Doing so is especially useful when using functions that rank values, because the second expression can resolve ties between identical values for the first expression. See Also: order_by_clause of "SELECT and Subqueries" on page 7-580 for more information on this clause. Note: Analytic functions always operate on rows in the order specified in the ORDER_BY_clause of the function. However, the ORDER_BY_clause of the function does not guarantee the order of the result. Use the ORDER_BY_clause of the query to guarantee the final result ordering. Restriction: When used in an analytic function, the ORDER_BY_clause must take an expression (expr). Position (position) and column aliases (c_alias) are invalid. Otherwise this ORDER_BY_clause is the same as that used to order the overall query or subquery.
Functions 4-9
SQL Functions
ASC | DESC NULLS FIRST | NULLS LAST
specifies the ordering sequence (ascending or descending). ASC is the default. specifies whether returned rows containing null values should appear first or last in the ordering sequence. NULLS LAST is the default for ascending order, and NULLS FIRST is the default for descending order.
windowing_clause
ROWS | RANGE These keywords define for each row a "window" (a physical or logical set of rows) used for calculating the function result. The function is then applied to all the rows in the window. The window "slides" through the query result set or partition from top to bottom.
s s
ROWS specifies the window in physical units (rows). RANGE specifies the window as a logical offset.
You cannot specify this clause unless you have specified the ORDER_BY_clause. Note: The value returned by an analytic function with a logical offset is always deterministic. However, the value returned by an analytic function with a physical offset may produce nondeterministic results unless the ordering expression results in a unique ordering. You may have to specify multiple columns in the ORDER_BY_clause to achieve this unique ordering. BETWEEN ... AND lets you specify a start point and end point for the window. The first expression (before AND) defines the start point and the second expression (after AND) defines the end point. If you omit BETWEEN and specify only one end point, Oracle considers it the start point, and the end point defaults to the current row. UNBOUNDED PRECEDING UNBOUNDED FOLLOWING CURRENT ROW specifies that the window starts at the first row of the partition. This is the start point specification and cannot be used as an end point specification. specifies that the window ends at the last row of the partition. This is the end point specification and cannot be used as a start point specification. As a start point, CURRENT ROW specifies that the window begins at the current row or value (depending on whether you have specified ROW or RANGE, respectively). In this case the end point cannot be value_expr PRECEDING. As an end point, CURRENT ROW specifies that the window ends at the current row or value (depending on whether you have specified ROW or RANGE, respectively). In this case the start point cannot be value_expr FOLLOWING.
4-10
SQL Reference
SQL Functions
value_expr PRECEDING value_expr FOLLOWING
For RANGE or ROW:
s
If value_expr FOLLOWING is the start point, then the end point must be value_expr FOLLOWING. If value_expr PRECEDING is the end point, then the start point must be value_expr PRECEDING.
s
If you are defining a logical window defined by an interval of time in numeric format, you may need to use conversion functions. See Also: "NUMTOYMINTERVAL" on page 4-63 and "NUMTODSINTERVAL" on page 4-62 for information on converting numeric times into interval literals. If you specified ROWS:
s
value_expr is a physical offset. It must be a constant or expression and must evaluate to a positive numeric value. If value_expr is part of the start point, it must evaluate to a row before the end point. value_expr is a logical offset. It must be a constant or expression that evaluates to a positive numeric value or an interval literal. See Also: "Literals" on page 2-2 for information on interval literals. You can specify only one expression in the ORDER_BY_clause If value_expr evaluates to a numeric value, the ORDER BY expr must be a NUMBER or DATE datatype. If value_expr evaluates to an interval value, the ORDER BY expr must be a DATE datatype.
s
If you specified RANGE:
s
s s
s
If you omit the windowing_clause entirely, the default is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW.
Analytic functions are commonly used in data warehousing environments. The analytic functions are:
Functions 4-11
ABS
AVG CORR COVAR_POP COVAR_SAMP COUNT CUME_DIST DENSE_RANK LAG FIRST_VALUE LAST_VALUE
LEAD MAX MIN NTILE PERCENT_RANK RATIO_TO_REPORT RANK REGR_ (linear regression) functions ROW_NUMBER
STDDEV STDDEV_POP STDDEV_SAMP SUM VAR_POP VAR_SAMP VARIANCE
See Also: Oracle8i Data Warehousing Guide for more information
on these functions, and for scenarios illustrating their use.
Object Reference Functions
Object functions manipulate REFs, which are references to objects of specified object types. The object reference functions are:
DEREF MAKE_REF REF REFTOHEX VALUE
See Also: Oracle8i Concepts and Oracle8i Application Developer's Guide - Fundamentals for more information about REFs.
Alphabetical Listing of SQL Functions
ABS
Syntax
ABS ( n )
4-12
SQL Reference
ADD_MONTHS
Purpose
ABS returns the absolute value of n.
Example
SELECT ABS(-15) "Absolute" FROM DUAL; Absolute ---------15
ACOS
Syntax
ACOS ( n )
Purpose
ACOS returns the arc cosine of n. Inputs are in the range of -1 to 1, and outputs are in the range of 0 to and are expressed in radians.
Example
SELECT ACOS(.3)"Arc_Cosine" FROM DUAL; Arc_Cosine ---------1.26610367
ADD_MONTHS
Syntax
ADD_MONTHS ( d , n )
Purpose
ADD_MONTHS 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
Functions 4-13
ASCII
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
ASCII
Syntax
ASCII ( char )
Purpose
ASCII returns the decimal representation in the database character set of the first character 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. There is no similar EBCDIC character function.
Example
SELECT ASCII('Q') FROM DUAL; ASCII('Q') ---------81
4-14
SQL Reference
ATAN
ASIN
Syntax
ASIN ( n )
Purpose
ASIN returns the arc sine of n. Inputs are in the range of -1 to 1, and outputs are in the range of -/2 to /2 and are expressed in radians.
Example
SELECT ASIN(.3) "Arc_Sine" FROM DUAL; Arc_Sine ---------.304692654
ATAN
Syntax
ATAN ( n )
Purpose
ATAN returns the arc tangent of n. Inputs are in an unbounded range, and outputs are in the range of -/2 to /2 and are expressed in radians.
Example
SELECT ATAN(.3) "Arc_Tangent" FROM DUAL; Arc_Tangent ---------.291456794
Functions 4-15
ATAN2
ATAN2
Syntax
, ATAN2 ( n / m )
Purpose
ATAN2 returns the arc tangent of n and m. Inputs are in an unbounded range, and outputs are in the range of - to , depending on the signs of n and m, and are expressed in radians. ATAN2(n,m) is the same as ATAN2(n/m)
Example
SELECT ATAN2(.3, .2) "Arc_Tangent2" FROM DUAL; Arc_Tangent2 -----------.982793723
AVG
Syntax
DISTINCT ALL AVG ( expr ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
AVG returns average value of expr. You can use it as an aggregate or analytic function. If you specify DISTINCT, you can specify only the query_partition_clause of the analytic_clause. The ORDER_BY_clause and windowing_clause are not allowed.
See Also: "Aggregate Functions" on page 4-6.
4-16
SQL Reference
BFILENAME
Aggregate Example
The following example calculates the average salary of all employees in the EMP table:
SELECT AVG(sal) "Average" FROM emp; Average ---------2077.21429
Analytic Example
The following example calculates, for each employee in the EMP table, the average salary of the employees reporting to the same manager who were hired in the range just before through just after the employee:
SELECT mgr, ename, hiredate, sal, AVG(sal) OVER (PARTITION BY mgr ORDER BY hiredate ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS c_mavg FROM emp; MGR ---------7566 7566 7698 7698 7698 7698 7698 7782 7788 7839 7839 7839 7902 ENAME ---------FORD SCOTT ALLEN WARD TURNER MARTIN JAMES MILLER ADAMS JONES BLAKE CLARK SMITH KING HIREDATE SAL C_MAVG --------- ---------- ---------03-DEC-81 3000 3000 19-APR-87 3000 3000 20-FEB-81 1600 1425 22-FEB-81 1250 1450 08-SEP-81 1500 1333.33333 28-SEP-81 1250 1233.33333 03-DEC-81 950 1100 23-JAN-82 1300 1300 23-MAY-87 1100 1100 02-APR-81 2975 2912.5 01-MAY-81 2850 2758.33333 09-JUN-81 2450 2650 17-DEC-80 800 800 17-NOV-81 5000 5000
BFILENAME
Syntax
BFILENAME ( ' directory ' , ' filename ' )
Functions 4-17
CEIL
Purpose
BFILENAME returns a BFILE locator that is associated with a physical LOB binary file on the server's file system. A directory is an alias for a full pathname on the server's file system where the files are actually located, and 'filename' is the name of the file in the server's file system. Neither 'directory' nor 'filename' needs to point to an existing object on the file system at the time you specify BFILENAME. However, you must associate a BFILE value with a physical file before performing subsequent SQL, PL/SQL, DBMS_LOB package, or OCI operations.
See Also:
s
Oracle8i Application Developer's Guide - Large Objects (LOBs) and Oracle Call Interface Programmer's Guide for more information on LOBs. "CREATE DIRECTORY" on page 7-282.
s
Example
INSERT INTO file_tbl VALUES (BFILENAME ('lob_dir1', 'image1.gif'));
CEIL
Syntax
CEIL ( n )
Purpose
CEIL returns smallest integer greater than or equal to n.
Example
SELECT CEIL(15.7) "Ceiling" FROM DUAL; Ceiling ---------16
4-18
SQL Reference
CHR
CHARTOROWID
Syntax
CHARTOROWID ( char )
Purpose
CHARTOROWID converts a value from CHAR or VARCHAR2 datatype to ROWID datatype.
Example
SELECT ename FROM emp WHERE ROWID = CHARTOROWID('AAAAfZAABAAACp8AAO'); ENAME ---------LEWIS
CHR
Syntax
USING CHR ( n NCHAR_CS )
Purpose
CHR returns the character having the binary equivalent to n in either the database character set or the national character set. If USING NCHAR_CS is not specified, this function returns the character having the binary equivalent to n as a VARCHAR2 value in the database character set. If USING NCHAR_CS is specified, this function returns the character having the binary equivalent to n as a NVARCHAR2 value in the national character set.
Example 1
SELECT CHR(67)||CHR(65)||CHR(84) "Dog" FROM DUAL;
Functions 4-19
CONCAT
Dog --CAT
Example 2
SELECT CHR(16705 USING NCHAR_CS) FROM DUAL; C A
CONCAT
Syntax
CONCAT ( char1 , char2 )
Purpose
CONCAT returns char1 concatenated with char2. This function is equivalent to the concatenation operator (||). For information on this operator, see "Concatenation Operator" 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
4-20
SQL Reference
CONVERT
CONVERT
Syntax
, CONVERT ( char , dest_char_set source_char_set )
Purpose
CONVERT returns smallest integer greater than or equal to expr. Converts a character string from one character set to another.
s
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.
s
s
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.
Example
SELECT CONVERT('Gro', 'US7ASCII', 'WE8HP') "Conversion" FROM DUAL; Conversion ---------Gross
Common character sets include:
s
US7ASCII: US 7-bit ASCII character set WE8DECDEC: West European 8-bit character set
s
Functions 4-21
CORR
s
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
s
s
s
s
CORR
Syntax
OVER CORR ( expr1 , expr2 ) ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
CORR returns the coefficient of correlation of a set of number pairs. You can use it as an aggregate or analytic function. Both expr1 and expr2 are number expressions. Oracle applies the function to the set of (expr1 , expr2) after eliminating the pairs for which either expr1 or expr2 is null. Then Oracle makes the following computation:
COVAR_POP(expr1, expr2) / (STDDEV_POP(expr1) * STDDEV_POP(expr2))
The function returns a value of type NUMBER. If the function is applied to an empty set, it returns null.
See Also: "Aggregate Functions" on page 4-6.
Aggregate Example
The following example calculates the coefficient of correlation between the salaries and commissions of the employees whose manager is 7698 from the EMP table:
SELECT mgr, CORR(sal, comm) FROM EMP GROUP BY mgr HAVING mgr = 7698; MGR CORR(SAL,COMM)
4-22
SQL Reference
COS
---------- -------------7698 -.69920974
Analytic Example
The following example returns the cumulative coefficient of correlation of monthly sales and monthly profits from the SALES table for year 1998:
SELECT s_month, CORR(SUM(s_amount), SUM(s_profit)) OVER (ORDER BY s_month) AS CUM_CORR FROM sales WHERE s_year=1998 GROUP BY s_month ORDER BY s_month; S_MONTH CUM_CORR ---------- ---------6 8 1 11 .860554259
Correlation functions require more than one row on which to operate, so the first row in the preceding example has no value calculated for it.
COS
Syntax
COS ( n )
Purpose
COS 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
Functions 4-23
COSH
COSH
Syntax
COSH ( n )
Purpose
COSH returns the hyperbolic cosine of n.
Example
SELECT COSH(0) "Hyperbolic cosine of 0" FROM DUAL; Hyperbolic cosine of 0 ---------------------1
COUNT
Syntax
* COUNT ( DISTINCT ALL expr OVER ) ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
COUNT returns the number of rows in the query. You can use it as an aggregate or analytic function. If you specify DISTINCT, you can specify only the query_partition_clause of the analytic_clause. The ORDER_BY_clause and windowing_clause are not allowed. If you specify expr, COUNT returns the number of rows where expr is not null. You can count either all rows, or only distinct values of expr.
4-24
SQL Reference
COUNT
If you specify the asterisk (*), this function returns all rows, including duplicates and nulls. COUNT never returns null.
See Also: "Aggregate Functions" on page 4-6.
Aggregate Examples
SELECT COUNT(*) "Total" FROM emp; Total ---------14 SELECT COUNT(mgr) "Count" FROM emp; Count ---------13 SELECT COUNT(DISTINCT mgr) "Managers" FROM emp; Managers ---------6
Analytic Example
The following example calculates, for each employee in the EMP table, the moving count of employees earning salaries in the range $50 less than through $150 greater than the employee's salary.
SELECT ename, sal, COUNT(*) OVER (ORDER BY sal RANGE BETWEEN 50 PRECEDING AND 150 FOLLOWING) AS mov_count FROM emp; ENAME SAL MOV_COUNT ---------- ---------- ---------SMITH 800 2 JAMES 950 2 ADAMS 1100 3 WARD 1250 3 MARTIN 1250 3 MILLER 1300 3 TURNER 1500 2 ALLEN 1600 1
Functions 4-25
COVAR_POP
CLARK BLAKE JONES SCOTT FORD KING
2450 2850 2975 3000 3000 5000
1 4 3 3 3 1
COVAR_POP
Syntax
OVER COVAR_POP ( expr1 , expr2 ) ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
COVAR_POP returns the population covariance of a set of number pairs. You can use it as an aggregate or analytic function. Both expr1 and expr2 are number expressions. Oracle applies the function to the set of (expr1 , expr2) pairs after eliminating all pairs for which either expr1 or expr2 is null. Then Oracle makes the following computation:
(SUM(expr1 * expr2) - SUM(expr2) * SUM(expr1) / n) / n
where n is the number of (expr1 , expr2) pairs where neither expr1 nor expr2 is null. The function returns a value of type NUMBER. If the function is applied to an empty set, it returns null.
See Also: "Aggregate Functions" on page 4-6.
Aggregate Example
The following example calculates the population covariance for the amount of sales and sale profits for each year from the table SALES.
SELECT s_year, COVAR_POP(s_amount, s_profit) AS COVAR_POP, COVAR_SAMP(s_amount, s_profit) AS COVAR_SAMP FROM sales GROUP BY s_year;
4-26
SQL Reference
COVAR_SAMP
S_YEAR COVAR_POP COVAR_SAMP ---------- ---------- ---------1998 3747965.53 4060295.99 1999 360536.162 400595.736
Analytic Example
See "COVAR_SAMP" on page 4-27.
COVAR_SAMP
Syntax
OVER COVAR_SAMP ( expr1 , expr2 ) ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
COVAR_SAMP returns the sample covariance of a set of number pairs. You can use it as an aggregate or analytic function. Both expr1 and expr2 are number expressions. Oracle applies the function to the set of (expr1 , expr2) pairs after eliminating all pairs for which either expr1 or expr2 is null. Then Oracle makes the following computation:
(SUM(expr1 * expr2) - SUM(expr1) * SUM(expr2) / n) / (n-1)
where n is the number of (expr1 , expr2) pairs where neither expr1 nor expr2 is null. The function returns a value of type NUMBER. If the function is applied to an empty set, it returns null.
See Also: "Aggregate Functions" on page 4-6.
Aggregate Example
See "COVAR_POP" on page 4-26.
Functions 4-27
CUME_DIST
Analytic Example
The following example calculates cumulative sample covariance of the amount of sales and sale profits in 1998.
SELECT s_year, s_month, s_day, COVAR_POP(s_amount, s_profit) OVER (ORDER BY s_month, s_day) AS CUM_COVP, COVAR_SAMP(s_amount, s_profit) OVER (ORDER BY s_month, s_day) AS CUM_COVS FROM sales WHERE s_year=1998 ORDER BY s_year, s_month, s_day; S_YEAR S_MONTH S_DAY ---------- ---------- ---------1998 6 5 1998 6 9 1998 6 9 1998 6 10 1998 8 21 1998 8 25 1998 8 25 1998 8 26 1998 11 9 1998 11 9 1998 11 10 1998 11 10 1998 11 11 CUM_COVP ---------0 4940952.6 4940952.6 5281752.33 6092799.46 4938283.61 4938283.61 4612074.09 4556799.53 4556799.53 4014833.65 4014833.65 3747965.53 CUM_COVS ---------7411428.9 7411428.9 7042336.44 7615999.32 5761330.88 5761330.88 5270941.82 5063110.59 5063110.59 4379818.52 4379818.52 4060295.99
CUME_DIST
Syntax
query_partition_clause CUME_DIST ( ) OVER ( ORDER_BY_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
CUME_DIST (cumulative distribution) is an analytic function. It computes the relative position of a specified value in a group of values. For a row R, assuming
4-28
SQL Reference
DENSE_RANK
ascending ordering, the CUME_DIST of R is the number of rows with values lower than or equal to the value of R, divided by the number of rows being evaluated (the entire query result set or a partition). The range of values returned by CUME_DIST is >0 to <=1. Tie values always evaluate to the same cumulative distribution value.
Example
The following example calculates the salary percentile for each employee within each job category excluding job categories PRESIDENT and MANAGER. For example, 50% of clerks have salaries less than or equal to James.
SELECT job, ename, sal, CUME_DIST() OVER (PARTITION BY job ORDER BY sal) AS cume_dist FROM emp WHERE job NOT IN ('MANAGER', 'PRESIDENT'); JOB --------ANALYST ANALYST CLERK CLERK CLERK CLERK SALESMAN SALESMAN SALESMAN SALESMAN ENAME SAL CUME_DIST ---------- ---------- ---------SCOTT 3000 1 FORD 3000 1 SMITH 800 .25 JAMES 950 .5 ADAMS 1100 .75 MILLER 1300 1 WARD 1250 .5 MARTIN 1250 .5 TURNER 1500 .75 ALLEN 1600 1
DENSE_RANK
Syntax
query_partition_clause DENSE_RANK ( ) OVER ( ORDER_BY_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
DENSE_RANK is an analytic function. It computes the rank of each row returned from a query with respect to the other rows, based on the values of the value_exprs
Functions 4-29
DEREF
in the ORDER_BY_clause. Rows with equal values for the ranking criteria receive the same rank. The ranks are consecutive integers beginning with 1. The largest rank value is the number of unique values returned by the query. Rank values are not skipped in the event of ties.
Example
The following statement selects the department name, employee name, and salary of all employees who work in the RESEARCH or SALES department, and then computes a rank for each unique salary in each of the two departments. The salaries that are equal receive the same rank. Compare this example with the example for "RANK" on page 4-67.
SELECT dname, ename, sal, DENSE_RANK() OVER (PARTITION BY dname ORDER BY sal) as drank FROM emp, dept WHERE emp.deptno = dept.deptno AND dname IN ('SALES', 'RESEARCH'); DNAME -------------RESEARCH RESEARCH RESEARCH RESEARCH RESEARCH SALES SALES SALES SALES SALES SALES ENAME SAL DRANK ---------- ---------- ---------SMITH 800 1 ADAMS 1100 2 JONES 2975 3 FORD 3000 4 SCOTT 3000 4 JAMES 950 1 MARTIN 1250 2 WARD 1250 2 TURNER 1500 3 ALLEN 1600 4 BLAKE 2850 5
DEREF
Syntax
DEREF ( expr )
4-30
SQL Reference
DUMP
Purpose
DEREF returns the object reference of argument expr, where expr must return a REF to an object.
Example
CREATE TYPE emp_type AS OBJECT (eno NUMBER, ename VARCHAR2(20), salary NUMBER); CREATE TABLE emp_table OF emp_type (primary key (eno, ename)); CREATE TABLE dept_table (dno NUMBER, mgr REF emp_type SCOPE IS emp_table); INSERT INTO emp_table VALUES (10, 'jack', 50000); INSERT INTO dept_table SELECT 10, REF(e) FROM emp_table e; SELECT DEREF(mgr) from dept_table; DEREF(MGR)(ENO, ENAME, SALARY) -------------------------------------------------------EMP_TYPE(10, 'jack', 50000)
DUMP
Syntax
, , , DUMP ( expr return_fmt ) start_position length
Purpose
DUMP returns a VARCHAR2 value containing the datatype code, length in bytes, and internal representation of expr. The returned result is always in the database character set. For the datatype corresponding to each code, see Table 21 on page 2-13. The argument return_fmt specifies the format of the return value and can have any of the following values:
s
8
returns result in octal notation
s
10 returns result in decimal notation
Functions 4-31
DUMP
s
16 returns result in hexadecimal notation 17 returns result as single characters
s
By default, the return value contains no character set information. To retrieve the character set name of expr, specify any of the format values above, plus 1000. For example, a return_fmt of 1008 returns the result in octal, plus provides the character set name of expr. 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 a null.
Example 1
SELECT DUMP('abc', 1016) FROM DUAL; DUMP('ABC',1016) -----------------------------------------Typ=96 Len=3 CharacterSet=WE8DEC: 61,62,63
Example 2
SELECT DUMP(ename, 8, 3, 2) "OCTAL" FROM emp WHERE ename = 'SCOTT'; OCTAL ---------------------------Type=1 Len=5: 117,124
Example 3
SELECT DUMP(ename, 10, 3, 2) "ASCII" FROM emp WHERE ename = 'SCOTT'; ASCII ---------------------------Type=1 Len=5: 79,84
4-32
SQL Reference
EXP
EMPTY_[B | C]LOB
Syntax
EMPTY_BLOB ( EMPTY_CLOB )
Purpose
EMPTY_BLOB and EMPTY_CLOB returns an empty LOB locator that can be used to initialize a LOB variable or in an INSERT or UPDATE statement to initialize a LOB column or attribute to EMPTY. EMPTY means that the LOB is initialized, but not populated with data. You cannot use the locator returned from this function as a parameter to the DBMS_LOB package or the OCI.
Example
INSERT INTO lob_tab1 VALUES (EMPTY_BLOB()); UPDATE lob_tab1 SET clob_col = EMPTY_BLOB();
EXP
Syntax
EXP ( n )
Purpose
EXP returns e raised to the nth power, where e = 2.71828183 ...
Example
SELECT EXP(4) "e to the 4th power" FROM DUAL; e to the 4th power -----------------54.59815
Functions 4-33
FIRST_VALUE
FIRST_VALUE
Syntax
FIRST_VALUE ( expr ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
FIRST_VALUE is an analytic function. It returns the first value in an ordered set of values.
Examples
The following example selects, for each employee in Department 20, the name of the employee with the highest salary.
SELECT deptno, ename, sal, FIRST_VALUE(ename) OVER (ORDER BY sal DESC ROWS UNBOUNDED PRECEDING) AS rich_emp FROM (SELECT * FROM emp WHERE deptno = 20 ORDER BY empno); DEPTNO ---------20 20 20 20 20 ENAME SAL RICH_EMP ---------- ---------- ---------SCOTT 3000 SCOTT FORD 3000 SCOTT JONES 2975 SCOTT ADAMS 1100 SCOTT SMITH 800 SCOTT
The example illustrates the nondeterministic nature of the FIRST_VALUE function. Scott and Ford have the same salary, so are in adjacent rows. Scott appears first because the rows returned by the subquery are ordered by EMPNO. However, if the rows returned by the subquery are ordered by EMPNO in descending order, as in the next example, the function returns a different value:
SELECT deptno, ename, sal, FIRST_VALUE(ename) OVER (ORDER BY sal DESC ROWS UNBOUNDED PRECEDING) AS fv FROM (SELECT * FROM emp WHERE deptno = 20 ORDER BY empno desc); DEPTNO ---------20 20 ENAME SAL FV ---------- ---------- ---------FORD 3000 FORD SCOTT 3000 FORD
4-34
SQL Reference
FLOOR
20 JONES 20 ADAMS 20 SMITH
2975 FORD 1100 FORD 800 FORD
The following example shows how to make the FIRST_VALUE function deterministic by ordering on a unique key.
SELECT deptno, ename, sal, hiredate, FIRST_VALUE(ename) OVER (ORDER BY sal DESC, hiredate ROWS UNBOUNDED PRECEDING) AS fv FROM (SELECT * FROM emp WHERE deptno = 20 ORDER BY empno desc); DEPTNO ---------20 20 20 20 20 ENAME SAL ---------- ---------FORD 3000 SCOTT 3000 JONES 2975 ADAMS 1100 SMITH 800 HIREDATE --------03-DEC-81 19-APR-87 02-APR-81 23-MAY-87 17-DEC-80 FV ---------FORD FORD FORD FORD FORD
FLOOR
Syntax
FLOOR ( n )
Purpose
FLOOR returns largest integer equal to or less than n.
Example
SELECT FLOOR(15.7) "Floor" FROM DUAL; Floor ---------15
Functions 4-35
GREATEST
GREATEST
Syntax
, GREATEST ( expr )
Purpose
GREATEST returns the greatest of the list of exprs. All exprs after the first are implicitly converted to the datatype of the first expr before the comparison. Oracle compares the exprs using nonpadded 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 character set 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
GROUPING
Syntax
GROUPING ( expr )
Purpose
This function is applicable only in a SELECT statement that contains a GROUP BY extension, such as ROLLUP or CUBE. These operations produce superaggregate rows that contain nulls representing the set of all values. You can use the GROUPING function to distinguish a null that represents the set of all values in a superaggregate row from an actual null.
4-36
SQL Reference
HEXTORAW
The expr in the GROUPING function must match one of the expressions in the GROUP BY clause. The function returns a value of 1 if the value of expr in the row is a null representing the set of all values. Otherwise, it returns zero. The datatype of the value returned by the GROUPING function is Oracle NUMBER. See the group_by_clause of the SELECT statement on page 7-578 for a discussion of these terms.
Example
In the following example, if the GROUPING function returns 1 (indicating a superaggregate row rather than a data row from the table), the string "All Jobs" appears instead of the null that would otherwise appear:
SELECT DECODE(GROUPING(dname), 1, 'All Departments', dname) AS dname, DECODE(GROUPING(job), 1, 'All Jobs', job) AS job, COUNT(*) "Total Empl", AVG(sal) * 12 "Average Sal" FROM emp, dept WHERE dept.deptno = emp.deptno GROUP BY ROLLUP (dname, job); DNAME --------------ACCOUNTING ACCOUNTING ACCOUNTING ACCOUNTING RESEARCH RESEARCH RESEARCH RESEARCH SALES SALES SALES SALES All Departments JOB Total Empl Average Sa --------- ---------- ---------CLERK 1 15600 MANAGER 1 29400 PRESIDENT 1 60000 All Jobs 3 35000 ANALYST 2 36000 CLERK 2 11400 MANAGER 1 35700 All Jobs 5 26100 CLERK 1 11400 MANAGER 1 34200 SALESMAN 4 16800 All Jobs 6 18800 All Jobs 14 24878.5714
HEXTORAW
Syntax
HEXTORAW ( char )
Functions 4-37
INITCAP
Purpose
HEXTORAW converts char containing hexadecimal digits to a raw value.
Example
INSERT INTO graphics (raw_column) SELECT HEXTORAW('7D') FROM DUAL;
INITCAP
Syntax
INITCAP ( char )
Purpose
INITCAP 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') "Capitals" FROM DUAL; Capitals --------The Soap
INSTR
Syntax
, , INSTR ( char1 , char2 n ) m
Purpose
INSTR 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
4-38
SQL Reference
INSTRB
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.
Example 1
SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL; Instring ---------14
Example 2
SELECT INSTR('CORPORATE FLOOR','OR', -3, 2) "Reversed Instring" FROM DUAL; Reversed Instring ----------------2
INSTRB
Syntax
, , INSTRB ( char1 , char2 n ) m
Purpose
INSTRB is 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.
Functions 4-39
LAG
Example
This example assumes a double-byte database character set.
SELECT INSTRB('CORPORATE FLOOR','OR',5,2) "Instring in bytes" FROM DUAL; Instring in bytes ----------------27
LAG
Syntax
, LAG ( value_expr offset , default ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
LAG is an analytic function. It provides access to more than one row of a table at the same time without a self-join. Given a series of rows returned from a query and a position of the cursor, LAG provides access to a row at a given physical offset prior to that position. If you do not specify offset, its default is 1. The optional default value is returned if the offset goes beyond the scope of the window. If you do not specify default, its default value is null.
Example
The following example provides, for each salesperson in the EMP table, the salary of the employee hired just before:
SELECT ename, hiredate, sal, LAG(sal, 1, 0) OVER (ORDER BY hiredate) as prev_sal FROM emp WHERE job = 'SALESMAN'; ENAME HIREDATE SAL PREV_SAL
4-40
SQL Reference
LAST_DAY
---------ALLEN WARD TURNER MARTIN
--------- ---------- ---------20-FEB-81 1600 0 22-FEB-81 1250 1600 08-SEP-81 1500 1250 28-SEP-81 1250 1500
LAST_DAY
Syntax
LAST_DAY ( d )
Purpose
LAST_DAY 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 1
SELECT SYSDATE, LAST_DAY(SYSDATE) "Last", LAST_DAY(SYSDATE) - SYSDATE "Days Left" FROM DUAL; SYSDATE Last Days Left --------- --------- ---------23-OCT-97 31-OCT-97 8
Example 2
SELECT TO_CHAR( ADD_MONTHS( LAST_DAY(hiredate),5), 'DD-MON-YYYY') "Five months" FROM emp WHERE ename = 'MARTIN'; Five months ----------28-FEB-1982
Functions 4-41
LAST_VALUE
LAST_VALUE
Syntax
LAST_VALUE ( expr ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
LAST_VALUE is an analytic function. It returns the last value in an ordered set of values.
Examples
The following example returns the hiredate of the employee earning the highest salary.
SELECT ename, sal, hiredate, LAST_VALUE(hiredate) OVER (ORDER BY sal ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM emp WHERE deptno=20 ORDER BY hiredate); ENAME SAL HIREDATE LV ---------- ---------- --------- --------SMITH 800 17-DEC-80 19-APR-87 ADAMS 1100 23-MAY-87 19-APR-87 JONES 2975 02-APR-81 19-APR-87 FORD 3000 03-DEC-81 19-APR-87 SCOTT 3000 19-APR-87 19-APR-87
This example illustrates the nondeterministic nature of the LAST_VALUE function. Ford and Scott have the same salary, so they are in adjacent rows. Ford appears first because the rows in the subquery are ordered by HIREDATE. However, if the rows are ordered by hiredate in descending order, as in the next example, the function returns a different value:
SELECT ename, sal, hiredate, LAST_VALUE(hiredate) OVER (ORDER BY sal ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM emp WHERE deptno=20 ORDER BY hiredate DESC); ENAME SAL HIREDATE LV
4-42
SQL Reference
LAST_VALUE
---------- ---------- --------- --------SMITH 800 17-DEC-80 03-DEC-81 ADAMS 1100 23-MAY-87 03-DEC-81 JONES 2975 02-APR-81 03-DEC-81 SCOTT 3000 19-APR-87 03-DEC-81 FORD 3000 03-DEC-81 03-DEC-81
The following two examples show how to make the LAST_VALUE function deterministic by ordering on a unique key. By ordering within the function by both salary and hiredate, you can ensure the same result regardless of the ordering in the subquery.
SELECT ename, sal, hiredate, LAST_VALUE(hiredate) OVER (ORDER BY sal, hiredate ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM emp WHERE deptno=20 ORDER BY hiredate); ENAME SAL HIREDATE LV ---------- ---------- --------- --------SMITH 800 17-DEC-80 19-APR-87 ADAMS 1100 23-MAY-87 19-APR-87 JONES 2975 02-APR-81 19-APR-87 FORD 3000 03-DEC-81 19-APR-87 SCOTT 3000 19-APR-87 19-APR-87 SELECT ename, sal, hiredate, LAST_VALUE(hiredate) OVER (ORDER BY sal, hiredate ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS lv FROM (SELECT * FROM emp WHERE deptno=20 ORDER BY hiredate DESC); ENAME SAL HIREDATE LV ---------- ---------- --------- --------SMITH 800 17-DEC-80 19-APR-87 ADAMS 1100 23-MAY-87 19-APR-87 JONES 2975 02-APR-81 19-APR-87 FORD 3000 03-DEC-81 19-APR-87 SCOTT 3000 19-APR-87 19-APR-87
Functions 4-43
LEAD
LEAD
Syntax
, LEAD ( value_expr offset , default ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
LEAD is an analytic function. It provides access to more than one row of a table at the same time without a self-join. Given a series of rows returned from a query and a position of the cursor, LEAD provides access to a row at a given physical offset beyond that position. If you do not specify offset, its default is 1. The optional default value is returned if the offset goes beyond the scope of the table. If you do not specify default, its default value is null.
Example
The following example provides, for each employee in the EMP table, the hiredate of the employee hired just after:
SELECT ename, hiredate, LEAD(hiredate, 1) OVER (ORDER BY hiredate) AS next_hire_date FROM emp; ENAME ---------SMITH ALLEN WARD JONES BLAKE CLARK TURNER MARTIN KING JAMES FORD MILLER HIREDATE --------17-DEC-80 20-FEB-81 22-FEB-81 02-APR-81 01-MAY-81 09-JUN-81 08-SEP-81 28-SEP-81 17-NOV-81 03-DEC-81 03-DEC-81 23-JAN-82 NEXT_HIRE --------20-FEB-81 22-FEB-81 02-APR-81 01-MAY-81 09-JUN-81 08-SEP-81 28-SEP-81 17-NOV-81 03-DEC-81 03-DEC-81 23-JAN-82 19-APR-87
4-44
SQL Reference
LENGTH
SCOTT ADAMS
19-APR-87 23-MAY-87 23-MAY-87
LEAST
Syntax
, LEAST ( expr )
Purpose
LEAST returns the least of the list of exprs. All exprs after the first are implicitly converted to the datatype of the first expr before the comparison. Oracle compares the exprs using nonpadded 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
LENGTH
Syntax
LENGTH ( char )
Purpose
LENGTH 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"
Functions 4-45
LENGTHB
FROM DUAL; Length in characters -------------------7
LENGTHB
Syntax
LENGTHB ( char )
Purpose
LENGTHB 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
This example assumes a double-byte database character set.
SELECT LENGTHB ('CANDIDE') "Length in bytes" FROM DUAL; Length in bytes --------------14
LN
Syntax
LN ( n )
Purpose
LN returns the natural logarithm of n, where n is greater than 0.
Example
SELECT LN(95) "Natural log of 95" FROM DUAL;
4-46
SQL Reference
LOWER
Natural log of 95 ----------------4.55387689
LOG
Syntax
LOG ( m , n )
Purpose
LOG 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
LOWER
Syntax
LOWER ( char )
Purpose
LOWER returns char, with all letters lowercase. The return value has the same datatype as the argument char (CHAR or VARCHAR2).
Example
SELECT LOWER('MR. SCOTT MCMILLAN') "Lowercase" FROM DUAL; Lowercase
Functions 4-47
LPAD
-------------------mr. scott mcmillan
LPAD
Syntax
, LPAD ( char1 , n char2 )
Purpose
LPAD 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 multibyte 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
, LTRIM ( char set )
4-48
SQL Reference
MAKE_REF
Purpose
LTRIM removes characters from the left of char, with all the leftmost characters that appear in set removed; set defaults to a single blank. If char is a character literal, you must enclose it in single quotes. 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') "LTRIM example" FROM DUAL; LTRIM example -----------XxyLAST WORD
MAKE_REF
Syntax
, table MAKE_REF ( view , key )
Purpose
MAKE_REF creates a REF to a row of an object view or a row in an object table whose object identifier is primary key based.
See Also: Oracle8i Application Developer's Guide - Fundamentals for more information about object views.
Example
CREATE TABLE emp (eno NUMBER, ename VARCHAR2(20), salary NUMBER, PRIMARY KEY (eno, ename)); CREATE TYPE emp_type AS OBJECT (eno NUMBER, ename CHAR(20), salary NUMBER); CREATE VIEW emp_view OF emp_type WITH OBJECT IDENTIFIER (eno, ename) AS SELECT * FROM emp; SELECT MAKE_REF(emp_view, 1, 'jack') FROM DUAL;
Functions 4-49
MAX
MAKE_REF(EMP_VIEW,1,'JACK') -----------------------------------------------------000067030A0063420D06E06F3C00C1E03400400B40DCB10000001C26010001000200 2900000000000F0600810100140100002A0007000A8401FE0000001F02C102146A61 636B2020202020202020202020202020202000000000000000000000000000000000 00000000
MAX
Syntax
DISTINCT ALL MAX ( expr ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
MAX returns maximum value of expr. You can use it as an aggregate or analytic function. If you specify DISTINCT, you can specify only the query_partition_clause of the analytic_clause. The ORDER_BY_clause and windowing_clause are not allowed.
See Also: "Aggregate Functions" on page 4-6
Aggregate Example
SELECT MAX(sal) "Maximum" FROM emp; Maximum ---------5000
Analytic Example
The following example calculates, for each employee, the highest salary of the employees reporting to the same manager as the employee.
SELECT mgr, ename, sal,
4-50
SQL Reference
MAX
MAX(sal) OVER (PARTITION BY mgr) AS mgr_max FROM emp; MGR ---------7566 7566 7698 7698 7698 7698 7698 7782 7788 7839 7839 7839 7902 ENAME SAL MGR_MAX ---------- ---------- ---------SCOTT 3000 3000 FORD 3000 3000 ALLEN 1600 1600 WARD 1250 1600 JAMES 950 1600 TURNER 1500 1600 MARTIN 1250 1600 MILLER 1300 1300 ADAMS 1100 1100 JONES 2975 2975 CLARK 2450 2975 BLAKE 2850 2975 SMITH 800 800 KING 5000 5000
If you enclose this query in the parent query with a predicate, you can determine the employee who makes the highest salary in each department:
SELECT mgr, ename, sal FROM (SELECT mgr, ename, sal, MAX(sal) OVER (PARTITION BY mgr) AS rmax_sal FROM emp) WHERE sal = rmax_sal; MGR ---------7566 7566 7698 7782 7788 7839 7902 ENAME SAL ---------- ---------SCOTT 3000 FORD 3000 ALLEN 1600 MILLER 1300 ADAMS 1100 JONES 2975 SMITH 800 KING 5000
Functions 4-51
MIN
MIN
Syntax
DISTINCT ALL MIN ( expr ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
MIN returns minimum value of expr. You can use it as an aggregate or analytic function. If you specify DISTINCT, you can specify only the query_partition_clause of the analytic_clause. The ORDER_BY_clause and windowing_clause are not allowed.
See Also: "Aggregate Functions" on page 4-6
Aggregate Example
SELECT MIN(hiredate) "Earliest" FROM emp; Earliest --------17-DEC-80
Analytic Example
The following example determines, for each employee, the employees who were hired on or before the same date as the employee. It then determines the subset of employees reporting to the same manager as the employee, and returns the lowest salary in that subset.
SELECT mgr, ename, hiredate, sal, MIN(sal) OVER(PARTITION BY mgr ORDER BY hiredate RANGE UNBOUNDED PRECEDING) as p_cmin FROM emp; MGR ENAME HIREDATE SAL P_CMIN ---------- ---------- --------- ---------- ---------7566 FORD 03-DEC-81 3000 3000
4-52
SQL Reference
MOD
7566 7698 7698 7698 7698 7698 7782 7788 7839 7839 7839 7902
SCOTT ALLEN WARD TURNER MARTIN JAMES MILLER ADAMS JONES BLAKE CLARK SMITH KING
19-APR-87 20-FEB-81 22-FEB-81 08-SEP-81 28-SEP-81 03-DEC-81 23-JAN-82 23-MAY-87 02-APR-81 01-MAY-81 09-JUN-81 17-DEC-80 17-NOV-81
3000 1600 1250 1500 1250 950 1300 1100 2975 2850 2450 800 5000
3000 1600 1250 1250 1250 950 1300 1100 2975 2850 2450 800 5000
MOD
Syntax
MOD ( m , n )
Purpose
MOD returns remainder of m divided by n. Returns m if n is 0.
Example
SELECT MOD(11,4) "Modulus" FROM DUAL; Modulus ---------3
This function behaves differently from the classical mathematical modulus function when m is negative. The classical modulus can be expressed using the MOD function with this formula:
m - n * FLOOR(m/n)
The following 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"
Functions 4-53
MONTHS_BETWEEN
FROM test_mod_table; M N MOD(M,N) Classical Modulus ---------- ---------- ---------- ----------------11 4 3 3 11 -4 3 -1 -11 4 -3 1 -11 -4 -3 -3
See Also: "FLOOR" on page 4-35.
MONTHS_BETWEEN
Syntax
MONTHS_BETWEEN ( d1 , d2 )
Purpose
MONTHS_BETWEEN 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 considers the difference in time components of d1 and d2.
Example
SELECT MONTHS_BETWEEN (TO_DATE('02-02-1995','MM-DD-YYYY'), TO_DATE('01-01-1995','MM-DD-YYYY') ) "Months" FROM DUAL; Months ---------1.03225806
4-54
SQL Reference
NEXT_DAY
NEW_TIME
Syntax
NEW_TIME ( d , z1 , z2 )
Purpose
NEW_TIME 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:
s
AST, ADT: Atlantic Standard or Daylight Time BST. BDT: Bering Standard or Daylight Time CST, CDT: Central Standard or Daylight Time EST. EDT: Eastern Standard or Daylight Time GMT: Greenwich Mean Time HST, HDT: Alaska-Hawaii Standard Time or Daylight Time. MST, MDT: Mountain Standard or Daylight Time NST: Newfoundland Standard Time PST, PDT: Pacific Standard or Daylight Time YST, YDT: Yukon Standard or Daylight Time
s
s
s
s
s
s
s
s
s
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 the date language of your session, either the full name or the abbreviation. The minimum number of letters required is the number of letters in the abbreviated version. Any characters immediately
Functions 4-55
NLS_CHARSET_DECL_LEN
following the valid abbreviation are ignored. The return value has the same hours, minutes, and seconds component as the argument d.
Example
This example returns the date of the next Tuesday after March 15, 1998.
SELECT NEXT_DAY('15-MAR-98','TUESDAY') "NEXT DAY" FROM DUAL; NEXT DAY --------16-MAR-98
NLS_CHARSET_DECL_LEN
Syntax
NLS_CHARSET_DECL_LEN ( bytecnt , csid )
Purpose
NLS_CHARSET_DECL_LEN returns the declaration width (in number of characters) of an NCHAR column. The bytecnt argument is the width of the column. The csid argument is the character set ID of the column.
Example
SELECT NLS_CHARSET_DECL_LEN (200, nls_charset_id('ja16eucfixed')) FROM DUAL; NLS_CHARSET_DECL_LEN(200,NLS_CHARSET_ID('JA16EUCFIXED')) -------------------------------------------------------100
NLS_CHARSET_ID
Syntax
NLS_CHARSET_ID ( text )
4-56
SQL Reference
NLS_CHARSET_NAME
Purpose
NLS_CHARSET_ID returns the NLS character set ID number corresponding to NLS character set name, text. The text argument is a run-time VARCHAR2 value. The text value 'CHAR_CS' returns the database character set ID number of the server. The text value 'NCHAR_CS' returns the national character set ID number of the server. Invalid character set names return null.
Example
SELECT NLS_CHARSET_ID('ja16euc') FROM DUAL; NLS_CHARSET_ID('JA16EUC') ------------------------830
See Also: Oracle8i National Language Support Guide for a list of
character set names.
NLS_CHARSET_NAME
Syntax
NLS_CHARSET_NAME ( n )
Purpose
NLS_CHARSET_NAME returns the name of the NLS character set corresponding to ID number n. The character set name is returned as a VARCHAR2 value in the database character set. If n is not recognized as a valid character set ID, this function returns null.
Example
SELECT NLS_CHARSET_NAME(2) FROM DUAL; NLS_CH -----WE8DEC
Functions 4-57
NLS_INITCAP
See Also: Oracle8i National Language Support Guide for a list of
character set IDs.
NLS_INITCAP
Syntax
, NLS_INITCAP ( char ' nlsparam ' )
Purpose
NLS_INITCAP 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 'nlsparam' 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. These requirements can result in a return value of a different length than the char. If you omit 'nlsparam', this function uses the default sort sequence for your session.
Example
SELECT NLS_INITCAP ('ijsland', 'NLS_SORT = XDutch') "Capitalized" FROM DUAL; Capital ------IJsland
See Also: Oracle8i National Language Support Guide for
information on sort sequences.
4-58
SQL Reference
NLSSORT
NLS_LOWER
Syntax
, NLS_LOWER ( char ' nlsparam ' )
Purpose
NLS_LOWER returns char, with all letters lowercase. The 'nlsparam' can have the same form and serve the same purpose as in the NLS_INITCAP function.
Example
SELECT NLS_LOWER ('CITTA''', 'NLS_SORT = XGerman') "Lowercase" FROM DUAL; Lower ----citt
NLSSORT
Syntax
, NLSSORT ( char ' nlsparam ' )
Purpose
NLSSORT returns the string of bytes used to sort char. The value of 'nlsparams' can have the form
'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.
Functions 4-59
NLS_UPPER
Example
This function can be used to specify comparisons based on a linguistic sort sequence rather than on the binary value of a string:
SELECT ename FROM emp WHERE NLSSORT (ename, 'NLS_SORT = German') > NLSSORT ('S', 'NLS_SORT = German') ORDER BY ename; ENAME ---------SCOTT SMITH TURNER WARD
See Also: Oracle8i National Language Support Guide for
information on sort sequences.
NLS_UPPER
Syntax
, NLS_UPPER ( char ' NLS_param = param_value ' )
Purpose
NLS_UPPER returns char, with all letters uppercase. The 'nlsparam' can have the same form and serve the same purpose as in the NLS_INITCAP function.
Example
SELECT NLS_UPPER ('groe', 'NLS_SORT = XGerman') "Uppercase" FROM DUAL; Upper ----GROSS
See Also: "NLS_INITCAP" on page 4-58.
4-60
SQL Reference
NTILE
NTILE
Syntax
query_partition_clause NTILE ( expr ) OVER ( ORDER_BY_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
NTILE is an analytic function. It divides an ordered dataset into a number of buckets indicated by expr and assigns the appropriate bucket number to each row. The buckets are numbered 1 through expr, and expr must resolve to a positive constant for each partition. The number of rows in the buckets can differ by at most 1. The remainder values (the remainder of number of rows divided by buckets) are distributed 1 per bucket, starting with bucket 1. If expr is greater than the number of rows, a number of buckets equal to the number of rows will be filled, and the remaining buckets will be empty.
Example
The following example divides the values in the SAL column into 4 buckets. The SAL column has 14 values, so the two extra values (the remainder of 14 / 4) are allocated to buckets 1 and 2, which therefore have one more value than buckets 3 or 4.
SELECT ename, sal, NTILE(4) OVER (ORDER BY sal DESC) AS quartile FROM emp; ENAME SAL QUARTILE ---------- ---------- ---------KING 5000 1 SCOTT 3000 1 FORD 3000 1 JONES 2975 1 BLAKE 2850 2 CLARK 2450 2 ALLEN 1600 2 TURNER 1500 2
Functions 4-61
NUMTODSINTERVAL
MILLER WARD MARTIN ADAMS JAMES SMITH
1300 1250 1250 1100 950 800
3 3 3 4 4 4
NUMTODSINTERVAL
Note: This function is restricted to use with analytic functions. It
accepts only numbers as arguments, and returns interval literals. See "Analytic Functions" on page 4-7 and "Interval" on page 2-5.
Syntax
NUMTODSINTERVAL ( n , ' char_expr ' )
Purpose
NUMTODSINTERVAL converts n to an INTERVAL DAY TO SECOND literal. n can be a number or an expression resolving to a number. The value for char_expr specifies the unit of n and must resolve to one of the following string values: 'DAY' s 'HOUR' s 'MINUTE' s 'SECOND' char_expr is case-insensitive. Leading and trailing values within the parentheses are ignored. By default, precision of the return is 9.
s
Example
The following example calculates for each employee, the number of employees hired, by the same manager, within the last 100 days from his/her hiredate:
SELECT mgr, ename, hiredate, COUNT(*) OVER (PARTITION BY mgr ORDER BY hiredate RANGE NUMTODSINTERVAL(100, 'day') PRECEDING) AS t_count FROM emp;
4-62
SQL Reference
NUMTOYMINTERVAL
MGR ---------7566 7566 7698 7698 7698 7698 7698 7782 7788 7839 7839 7839 7902
ENAME ---------FORD SCOTT ALLEN WARD TURNER MARTIN JAMES MILLER ADAMS JONES BLAKE CLARK SMITH KING
HIREDATE T_COUNT --------- ---------03-DEC-81 1 19-APR-87 1 20-FEB-81 1 22-FEB-81 2 08-SEP-81 1 28-SEP-81 2 03-DEC-81 3 23-JAN-82 1 23-MAY-87 1 02-APR-81 1 01-MAY-81 2 09-JUN-81 3 17-DEC-80 1 17-NOV-81 1
NUMTOYMINTERVAL
Note: This function is restricted to use with analytic functions. It
accepts only numbers as arguments, and returns interval literals. See "Analytic Functions" on page 4-7 and "Interval" on page 2-5.
Syntax
NUMTOYMINTERVAL ( n , ' char_expr ' )
Purpose
NUMTOYMINTERVAL converts number n to an INTERVAL YEAR TO MONTH literal. n can be a number or an expression resolving to a number. The value for char_expr specifies the unit of n, and must resolve to one of the following string values:
s
'YEAR' 'MONTH'
s
char_expr is case-insensitive. Leading and trailing values within the parentheses are ignored. By default, precision of the return is 9.
Functions 4-63
NVL
Example
The following example calculates, for each employee, the total salary of employees hired in the past one year from his/her hiredate.
SELECT ename, hiredate, sal, SUM(sal) OVER (ORDER BY hiredate RANGE NUMTOYMINTERVAL(1,'year') PRECEDING) AS t_sal FROM emp; ENAME ---------SMITH ALLEN WARD JONES BLAKE CLARK TURNER MARTIN KING JAMES FORD MILLER SCOTT ADAMS HIREDATE SAL T_SAL --------- ---------- ---------17-DEC-80 800 800 20-FEB-81 1600 2400 22-FEB-81 1250 3650 02-APR-81 2975 6625 01-MAY-81 2850 9475 09-JUN-81 2450 11925 08-SEP-81 1500 13425 28-SEP-81 1250 14675 17-NOV-81 5000 19675 03-DEC-81 950 23625 03-DEC-81 3000 23625 23-JAN-82 1300 24125 19-APR-87 3000 3000 23-MAY-87 1100 4100
NVL
Syntax
NVL ( expr1 , expr2 )
Purpose
If expr1 is null, NVL returns expr2; if expr1 is not null, NVL 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')
4-64
SQL Reference
NVL2
"COMMISSION" FROM emp WHERE deptno = 30; ENAME ---------ALLEN WARD MARTIN BLAKE TURNER JAMES COMMISSION ------------------------------------300 500 1400 NOT APPLICABLE 0 NOT APPLICABLE
NVL2
Syntax
NVL2 ( expr1 , expr2 , expr3 )
Purpose
If expr1 is not null, NVL2 returns expr2. If expr1 is null, NVL2 returns expr3. The argument expr1 can have any datatype. The arguments expr2 and expr3 can have any datatypes except LONG. If the datatypes of expr2 and expr3 are different, Oracle converts expr3 to the datatype of expr2 before comparing them unless expr3 is a null constant. In that case, a datatype conversion is not necessary. The datatype of the return value is always the same as the datatype of expr2, unless expr2 is character data, in which case the return value's datatype is VARCHAR2.
Example
The following example shows whether the income of each employee in department 30 is made up of salary plus commission, or just salary, depending on whether the COMM column of EMP is null or not.
SELECT ename, NVL2(TO_CHAR(COMM), 'SAL & COMM', 'SAL') income FROM emp WHERE deptno = 30; ENAME INCOME ---------- ---------ALLEN SAL & COMM
Functions 4-65
PERCENT_RANK
WARD MARTIN BLAKE TURNER JAMES
SAL & COMM SAL & COMM SAL SAL & COMM SAL
PERCENT_RANK
Syntax
query_partition_clause PERCENT_RANK ( ) OVER ( ORDER_BY_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
PERCENT_RANK is an analytic function, and is similar to the CUME_DIST (cumulative distribution) function. For a row R, PERCENT_RANK calculates the rank of R minus 1, divided by 1 less than the number of rows being evaluated (the entire query result set or a partition). The range of values returned by PERCENT_RANK is 0 to 1, inclusive. The first row in any set has a PERCENT_RANK of 0.
Example
The following example calculates, for each employee, the percent rank of the employee's salary within the department:
SELECT deptno, ename, sal, PERCENT_RANK() OVER (PARTITION BY deptno ORDER BY sal DESC) AS pr FROM emp; DEPTNO ---------10 10 10 20 20 20 20 20 ENAME SAL PR ---------- ---------- ---------KING 5000 0 CLARK 2450 .5 MILLER 1300 1 SCOTT 3000 0 FORD 3000 0 JONES 2975 .5 ADAMS 1100 .75 SMITH 800 1
4-66
SQL Reference
RANK
30 30 30 30 30 30
BLAKE ALLEN TURNER WARD MARTIN JAMES
2850 1600 1500 1250 1250 950
0 .2 .4 .6 .6 1
POWER
Syntax
POWER ( m , n )
Purpose
POWER 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
RANK
Syntax
query_partition_clause RANK ( ) OVER ( ORDER_BY_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
RANK is an analytic function. It computes the rank of each row returned from a query with respect to the other rows returned by the query, based on the values of the value_exprs in the ORDER_BY_clause. Rows with equal values for the ranking
Functions 4-67
RATIO_TO_REPORT
criteria receive the same rank. Oracle then adds the number of tied rows to the tied rank to calculate the next rank. Therefore, the ranks may not be consecutive numbers.
Example
The following statement ranks the employees within each department based on their salary and commission. Identical salary values receive the same rank and cause nonconsecutive ranks. Compare this example with the example for "DENSE_RANK" on page 4-29.
SELECT deptno, ename, sal, comm, RANK() OVER (PARTITION BY deptno ORDER BY sal DESC, comm) as rk FROM emp; DEPTNO ---------10 10 10 20 20 20 20 20 30 30 30 30 30 30 ENAME SAL COMM RK ---------- ---------- ---------- ---------KING 5000 1 CLARK 2450 2 MILLER 1300 3 SCOTT 3000 1 FORD 3000 1 JONES 2975 3 ADAMS 1100 4 SMITH 800 5 BLAKE 2850 1 ALLEN 1600 300 2 TURNER 1500 0 3 WARD 1250 500 4 MARTIN 1250 1400 5 JAMES 950 6
RATIO_TO_REPORT
Syntax
query_partition_clause RATIO_TO_REPORT ( expr ) OVER ( )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
4-68
SQL Reference
RAWTOHEX
Purpose
RATIO_TO_REPORT is an analytic function. It computes the ratio of a value to the sum of a set of values. If expr evaluates to null, the ratio-to-report value also evaluates to null. The set of values is determined by the query_partition_clause. If you omit that clause, the ratio-to-report is computed over all rows returned by the query.
Example
The following example calculates the ratio-to-report of each salesperson's salary to the total of all salespeople's salaries:
SELECT ename, sal, RATIO_TO_REPORT(sal) OVER () AS rr FROM emp WHERE job = 'SALESMAN'; ENAME SAL RR ---------- ---------- ---------ALLEN 1600 .285714286 WARD 1250 .223214286 MARTIN 1250 .223214286 TURNER 1500 .267857143
RAWTOHEX
Syntax
RAWTOHEX ( raw )
Purpose
RAWTOHEX converts raw to a character value containing its hexadecimal equivalent.
Example
SELECT RAWTOHEX(raw_column) "Graphics" FROM graphics; Graphics -------7D
Functions 4-69
REF
REF
Syntax
REF ( correlation_variable )
Purpose
In a SQL statement, REF takes as its argument a correlation variable (table alias) associated with a row of an object table or an object view. A REF value is returned for the object instance that is bound to the variable or row.
Example
CREATE TYPE emp_type AS OBJECT (eno NUMBER, ename VARCHAR2(20), salary NUMBER); CREATE TABLE emp_table OF emp_type (primary key (eno, ename)); INSERT INTO emp_table VALUES (10, 'jack', 50000); SELECT REF(e) FROM emp_table e; REF(E) ----------------------------------------------------0000280209420D2FEABD9400C3E03400400B40DCB1420D2FEABD9300C3E03400400B 40DCB1004049EE0000
See Also: Oracle8i Concepts.
REFTOHEX
Syntax
REFTOHEX ( r )
Purpose
REFTOHEX converts argument r to a character value containing its hexadecimal equivalent.
4-70
SQL Reference
REGR_ (linear regression) functions
Example
CREATE TYPE emp_type AS OBJECT (eno NUMBER, ename VARCHAR2(20), salary NUMBER); CREATE TABLE emp_table OF emp_type (primary key (eno, ename)); CREATE TABLE dept (dno NUMBER, mgr REF emp_type SCOPE IS emp); INSERT INTO emp_table VALUES (10, 'jack', 50000); INSERT INTO dept SELECT 10, REF(e) FROM emp_table e; SELECT REFTOHEX(mgr) FROM dept; REFTOHEX(MGR) -----------------------------------------------------0000220208420D2FEABD9400C3E03400400B40DCB1420D2FEABD9300C3E03400400B 40DCB1
REGR_ (linear regression) functions
The linear regression functions are:
s
REGR_SLOPE REGR_INTERCEPT REGR_COUNT REGR_R2 REGR_AVGX REGR_AVGY REGR_SXX REGR_SYY REGR_SXY
s
s
s
s
s
s
s
s
Functions 4-71
REGR_ (linear regression) functions
Syntax
REGR_SLOPE REGR_INTERCEPT REGR_COUNT REGR_R2 REGR_AVGX REGR_AVGY REGR_SXX REGR_SYY REGR_SXY ( expr1 , expr2 ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
The linear regression functions fit an ordinary-least-squares regression line to a set of number pairs. You can use them as both aggregate and analytic functions.
See Also: "Aggregate Functions" on page 4-6
Oracle applies the function to the set of (expr1, expr2) pairs after eliminating all pairs for which either expr1 or expr2 is null. Oracle computes all the regression functions simultaneously during a single pass through the data. expr1 is interpreted as a value of the dependent variable (a "y value"), and expr2 is interpreted as a value of the independent variable (an "x value"). Both expressions must be numbers.
s
REGR_SLOPE returns the slope of the line. The return value is a number and can be null. After the elimination of null (expr1, expr2) pairs, it makes the following computation:
COVAR_POP(expr1, expr2) / VAR_POP(expr2)
s
REGR_INTERCEPT returns the y-intercept of the regression line. The return value is a number and can be null. After the elimination of null (expr1, expr2) pairs, it makes the following computation:
4-72
SQL Reference
REGR_ (linear regression) functions
AVG(expr1) - REGR_SLOPE(expr1, expr2) * AVG(expr2)
s
REGR_COUNT returns an integer that is the number of non-null number pairs used to fit the regression line. REGR_R2 returns the coefficient of determination (also called "R-squared" or "goodness of fit") for the regression. The return value is a number and can be null. VAR_POP(expr1) and VAR_POP(expr2) are evaluated after the elimination of null pairs. The return values are:
NULL if VAR_POP(expr2) = 0
s
1 if VAR_POP(expr1) = 0 and VAR_POP(expr2) != 0 POWER(CORR(expr1,expr),2) if VAR_POP(expr1) > 0 and VAR_POP(expr2 != 0
All of the remaining regression functions return a number and can be null:
s
REGR_AVGX evaluates the average of the independent variable (expr2) of the regression line. It makes the following computation after the elimination of null (expr1, expr2) pairs:
AVG(expr2)
s
REGR_AVGY evaluates the average of the dependent variable (expr1) of the regression line. It makes the following computation after the elimination of null (expr1, expr2) pairs:
AVG(expr1)
REGR_SXY, REGR_SXX, REGR_SYY are auxiliary functions that are used to compute various diagnostic statistics.
s
REGR_SXX makes the following computation after the elimination of null (expr1, expr2) pairs:
REGR_COUNT(expr1, expr2) * VAR_POP(expr2)
s
REGR_SYY makes the following computation after the elimination of null (expr1, expr2) pairs:
REGR_COUNT(expr1, expr2) * VAR_POP(expr1)
s
REGR_SXY makes the following computation after the elimination of null (expr1, expr2) pairs:
Functions 4-73
REGR_ (linear regression) functions
REGR_COUNT(expr1, expr2) * COVAR_POP(expr1, expr2)
The following examples are based on the SALES table, described in "COVAR_POP" on page 4-26.
REGR_SLOPE and REGR_INTERCEPT Examples
The following example determines the slope and intercept of the regression line for the amount of sales and sale profits for each year.
SELECT s_year, REGR_SLOPE(s_amount, s_profit), REGR_INTERCEPT(s_amount, s_profit) FROM sales GROUP BY s_year; S_YEAR REGR_SLOPE REGR_INTER ---------- ---------- ---------1998 128.401558 -2277.5684 1999 55.618655 226.855296
The following example determines the cumulative slope and cumulative intercept of the regression line for the amount of sales and sale profits for each day in 1998:
SELECT s_year, s_month, s_day, REGR_SLOPE(s_amount, s_profit) OVER (ORDER BY s_month, s_day) AS CUM_SLOPE, REGR_INTERCEPT(s_amount, s_profit) OVER (ORDER BY s_month, s_day) AS CUM_ICPT FROM sales WHERE s_year=1998 ORDER BY s_month, s_day; S_YEAR S_MONTH S_DAY ---------- ---------- ---------1998 6 5 1998 6 9 1998 6 9 1998 6 10 1998 8 21 1998 8 25 1998 8 25 1998 8 26 1998 11 9 1998 11 9 1998 11 10 CUM_SLOPE CUM_ICPT ---------- ---------132.093066 132.093066 131.829612 132.963737 130.681718 130.681718 128.76502 131.499934 131.499934 130.190972 401.884833 401.884833 450.65349 -153.5413 -451.47349 -451.47349 -236.50096 -1806.7535 -1806.7535 -2323.3056
4-74
SQL Reference
REGR_ (linear regression) functions
1998 1998
11 11
10 130.190972 -2323.3056 11 128.401558 -2277.5684
REGR_COUNT Examples
The following example returns the number of sales transactions in the SALES table that resulted in a profit. (None of the rows for containing a sales amount have a null in the S_PROFIT column, so the function returns the total number of rows in the SALES table.)
SELECT REGR_COUNT(s_amount, s_profit) FROM sales; REGR_COUNT ---------23
The following example computes, for each day, the cumulative number of transactions within each month for the year 1998:
SELECT s_month, s_day, REGR_COUNT(s_amount,s_profit) OVER (PARTITION BY s_month ORDER BY s_day) FROM SALES WHERE S_YEAR=1998 ORDER BY S_MONTH; S_MONTH S_DAY REGR_COUNT ---------- ---------- ---------6 5 1 6 9 3 6 9 3 6 10 4 8 21 1 8 25 3 8 25 3 8 26 4 11 9 2 11 9 2 11 10 4 11 10 4 11 11 5
REGR_R2 Examples
The following example computes the coefficient of determination of the regression line for amount of sales and sale profits:
Functions 4-75
REGR_ (linear regression) functions
SELECT REGR_R2(s_amount, s_profit) FROM sales; REGR_R2(S_ ---------.942435028
The following example computes the cumulative coefficient of determination of the regression line for monthly sales and monthly profits for each month in 1998:
SELECT s_month, REGR_R2(SUM(s_amount), SUM(s_profit)) OVER (ORDER BY s_month) FROM SALES WHERE s_year=1998 GROUP BY s_month ORDER BY s_month; S_MONTH REGR_R2(SU ---------- ---------6 8 1 11 .740553632
REGR_AVGY and REGR_AVGX Examples
The following example calculates the regression average for the amount of sales and sale profits for each year:
SELECT s_year, REGR_AVGY(s_amount, s_profit), REGR_AVGX(s_amount, s_profit) FROM sales GROUP BY s_year; S_YEAR REGR_AVGY( REGR_AVGX( ---------- ---------- ---------1998 41227.5462 338.820769 1999 7330.748 127.725
The following example calculates the cumulative averages for the amount of sales and sale profits in 1998:
SELECT s_year, s_month, s_day, REGR_AVGY(s_amount, s_profit) OVER (ORDER BY s_month, s_day) AS CUM_AMOUNT, REGR_AVGX(s_amount, s_profit) OVER (ORDER BY s_month, s_day) AS CUM_PROFIT
4-76
SQL Reference
REGR_ (linear regression) functions
FROM sales WHERE s_year=1998 ORDER BY s_month, s_day; S_YEAR S_MONTH S_DAY ---------- ---------- ---------1998 6 5 1998 6 9 1998 6 9 1998 6 10 1998 8 21 1998 8 25 1998 8 25 1998 8 26 1998 11 9 1998 11 9 1998 11 10 1998 11 10 1998 11 11 CUM_AMOUNT ---------16068 44375.6667 44375.6667 52678.25 44721.72 45333.8 45333.8 47430.7 41892.91 41892.91 40777.175 40777.175 41227.5462 CUM_PROFIT ---------118.2 332.9 332.9 396.175 337.5 350.357143 350.357143 370.1875 332.317 332.317 331.055833 331.055833 338.820769
REGR_SXY, REGR_SXX, and REGR_SYY Examples
The following example computes the REGR_SXY, REGR_SXX, and REGR_SYY values for the regression analysis of amount of sales and sale profits for each year:
SELECT s_year, REGR_SXY(s_amount, s_profit), REGR_SYY(s_amount, s_profit), REGR_SXX(s_amount, s_profit) FROM sales GROUP BY s_year; S_YEAR ---------1998 1999 REGR_SXY(S REGR_SYY(S REGR_SXX(S ---------- ---------- ---------48723551.8 6423698688 379462.311 3605361.62 200525751 64822.8841
The following example computes the cumulative REGR_SXY, REGR_SXX, and REGR_SYY statistics for amount of sales and sale profits for each month-day value in 1998:
SELECT s_year, s_month, s_day, REGR_SXY(s_amount, s_profit) OVER (ORDER BY s_month, s_day) AS CUM_SXY, REGR_SYY(s_amount, s_profit) OVER (ORDER BY s_month, s_day) AS CUM_SXY, REGR_SXX(s_amount, s_profit)
Functions 4-77
REPLACE
OVER (ORDER BY s_month, s_day) AS CUM_SXX FROM sales WHERE s_year=1998 ORDER BY s_month, s_day; S_YEAR S_MONTH S_DAY ---------- ---------- ---------1998 6 5 1998 6 9 1998 6 9 1998 6 10 1998 8 21 1998 8 25 1998 8 25 1998 8 26 1998 11 9 1998 11 9 1998 11 10 1998 11 10 1998 11 11 CUM_SXY ---------0 14822857.8 14822857.8 21127009.3 30463997.3 34567985.3 34567985.3 36896592.7 45567995.3 45567995.3 48178003.8 48178003.8 48723551.8 CUM_SXY ---------0 1958007601 1958007601 2785202281 4051329674 4541739739 4541739739 4787971157 6045196901 6045196901 6392056557 6392056557 6423698688 CUM_SXX ---------0 112215.26 112215.26 160259.968 229115.08 264520.437 264520.437 286542.049 346524.854 346524.854 370056.411 370056.411 379462.311
REPLACE
Syntax
, REPLACE ( char , search_string replacement_string )
Purpose
REPLACE 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 lets you substitute one string for another as well as to remove character strings.
Example
SELECT REPLACE('JACK and JUE','J','BL') "Changes" FROM DUAL;
4-78
SQL Reference
ROUND (Date Function)
Changes -------------BLACK and BLUE
ROUND (Number Function)
Syntax
, ROUND ( n m )
Purpose
ROUND returns n rounded to m places right of the decimal point. If m is omitted, n is rounded to 0 places. m can be negative to round off digits left of the decimal point. m must be an integer.
Example 1
SELECT ROUND(15.193,1) "Round" FROM DUAL; Round ---------15.2
Example 2
SELECT ROUND(15.193,-1) "Round" FROM DUAL; Round ---------20
ROUND (Date Function)
Syntax
, ROUND ( d fmt )
Functions 4-79
ROW_NUMBER
Purpose
ROUND returns d rounded to the unit specified by the format model fmt. If you omit fmt, d is rounded to the nearest day. See "ROUND and TRUNC Date Functions" on page 4-117 for the permitted format models to use in fmt.
Example
SELECT ROUND (TO_DATE ('27-OCT-92'),'YEAR') "New Year" FROM DUAL; New Year --------01-JAN-93
ROW_NUMBER
Syntax
query_partition_clause ROW_NUMBER ( ) OVER ( ORDER_BY_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
ROW_NUMBER is an analytic function. It assigns a unique number to each row to which it is applied (either each row in the partition or each row returned by the query), in the ordered sequence of rows specified in the ORDER_BY_clause, beginning with 1.
Example
For each department in the EMP table, the following example assigns numbers to each row in order of employee's hire date:
SELECT deptno, ename, hiredate, ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY hiredate) AS emp_id FROM emp; DEPTNO ENAME HIREDATE EMP_ID ---------- ---------- --------- ---------10 CLARK 09-JUN-81 1
4-80
SQL Reference
ROWIDTOCHAR
10 10 20 20 20 20 20 30 30 30 30 30 30
KING MILLER SMITH JONES FORD SCOTT ADAMS ALLEN WARD BLAKE TURNER MARTIN JAMES
17-NOV-81 23-JAN-82 17-DEC-80 02-APR-81 03-DEC-81 19-APR-87 23-MAY-87 20-FEB-81 22-FEB-81 01-MAY-81 08-SEP-81 28-SEP-81 03-DEC-81
2 3 1 2 3 4 5 1 2 3 4 5 6
ROW_NUMBER is a nondeterministic function. However, HIREDATE is a unique key, so the results of this application of the function are deterministic. For examples of nondeterministic behavior, see "FIRST_VALUE" on page 4-34 and "LAST_VALUE" on page 4-42.
ROWIDTOCHAR
Syntax
ROWIDTOCHAR ( rowid )
Purpose
ROWIDTOCHAR converts a rowid value to VARCHAR2 datatype. The result of this conversion is always 18 characters long.
Example
SELECT ROWID FROM offices WHERE ROWIDTOCHAR(ROWID) LIKE '%Br1AAB%'; ROWID -----------------AAAAZ6AABAAABr1AAB
Functions 4-81
RPAD
RPAD
Syntax
, RPAD ( char1 , n char2 )
Purpose
RPAD 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 multibyte character sets, the display length of a character string can differ from the number of characters in the string.
Example
SELECT RPAD('MORRISON',12,'ab') "RPAD example" FROM DUAL; RPAD example ----------------MORRISONabab
RTRIM
Syntax
, RTRIM ( char set )
Purpose
RTRIM returns char, with all the rightmost characters that appear in set removed; set defaults to a single blank. If char is a character literal, you must enclose it in single quotes. RTRIM works similarly to LTRIM.
4-82
SQL Reference
SIN
Example
SELECT RTRIM('BROWNINGyxXxy','xy') "RTRIM e.g." FROM DUAL; RTRIM e.g ------------BROWNINGyxX
See Also: "LTRIM" on page 4-48.
SIGN
Syntax
SIGN ( n )
Purpose
If n<0, SIGN returns -1. If n=0, the function returns 0. If n>0, SIGN returns 1.
Example
SELECT SIGN(-15) "Sign" FROM DUAL; Sign ----------1
SIN
Syntax
SIN ( n )
Purpose
SIN returns the sine of n (an angle expressed in radians).
Functions 4-83
SINH
Example
SELECT SIN(30 * 3.14159265359/180) "Sine of 30 degrees" FROM DUAL; Sine of 30 degrees -----------------.5
SINH
Syntax
SINH ( n )
Purpose
SINH returns the hyperbolic sine of n.
Example
SELECT SINH(1) "Hyperbolic sine of 1" FROM DUAL; Hyperbolic sine of 1 -------------------1.17520119
SOUNDEX
Syntax
SOUNDEX ( char )
Purpose
SOUNDEX 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, as follows:
4-84
SQL Reference
SQRT
s
Retain the first letter of the string and remove all other occurrences of the following letters: a, e, h, i, o, u, w, y. Assign numbers to the remaining letters (after the first) as follows:
b, f, p, v = 1 c, g, j, k, q, s, x, z = 2 d, t = 3 l = 4 m, n = 5 r = 6
s
s
If two or more letters with the same number were adjacent in the original name (before step 1), or adjacent except for any intervening h and w, omit all but the first. Return the first four bytes padded with 0.
s
Example
SELECT ename FROM emp WHERE SOUNDEX(ename) = SOUNDEX('SMYTHE'); ENAME ---------SMITH
SQRT
Syntax
SQRT ( n )
Purpose
SQRT returns square root of n. The value n cannot be negative. SQRT returns a "real" result.
Example
SELECT SQRT(26) "Square root" FROM DUAL;
Functions 4-85
STDDEV
Square root ----------5.09901951
STDDEV
Syntax
DISTINCT ALL STDDEV ( expr ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
STDDEV returns sample standard deviation of expr, a set of numbers. You can use it as both an aggregate and analytic function. It differs from STDDEV_SAMP in that STDDEV returns zero when it has only 1 row of input data, whereas STDDEV_SAMP returns a null. Oracle calculates the standard deviation as the square root of the variance defined for the VARIANCE aggregate function. If you specify DISTINCT, you can specify only the query_partition_clause of the analytic_clause. The ORDER_BY_clause and windowing_clause are not allowed.
See Also: "Aggregate Functions" on page 4-6, "VARIANCE" on
page 4-115, and "STDDEV_SAMP" on page 4-88.
Aggregate Example
SELECT STDDEV(sal) "Deviation" FROM emp; Deviation ---------1182.50322
4-86
SQL Reference
STDDEV_POP
Analytic Example
The query in the following example returns the cumulative standard deviation of salary values in Department 30 ordered by hiredate:
SELECT ENAME, SAL, STDDEV(SAL) OVER (ORDER BY HIREDATE) FROM EMP WHERE DEPTNO=30; ENAME SAL ---------- ---------ALLEN 1600 WARD 1250 BLAKE 2850 TURNER 1500 MARTIN 1250 JAMES 950 STDDEV(SAL ---------0 247.487373 841.130192 715.308791 666.520817 668.331255
STDDEV_POP
Syntax
OVER STDDEV_POP ( expr ) ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
STDDEV_POP computes the population standard deviation and returns the square root of the population variance. You can use it as both an aggregate and analytic function. The expr is a number expression, and the function returns a value of type NUMBER. This function is same as the square root of the VAR_POP function. When VAR_POP returns null, this function returns null.
See Also: "Aggregate Functions" on page 4-6 and "VAR_POP" on
page 4-113.
Functions 4-87
STDDEV_SAMP
Aggregate Example
The following example returns the population and sample standard deviations of profit from sales in the SALES table.
SELECT STDDEV_POP(s_profit), STDDEV_SAMP(s_profit) FROM sales; STDDEV_POP STDDEV_SAM ---------- ---------173.975774 177.885831
Analytic Example
The following example returns the population standard deviations of salaries in the EMP table by department:
SELECT deptno, ename, sal, STDDEV_POP(sal) OVER (PARTITION BY deptno) AS pop_std FROM emp; DEPTNO ---------10 10 10 20 20 20 20 20 30 30 30 30 30 30 ENAME SAL POP_STD ---------- ---------- ---------CLARK 2450 1546.14215 KING 5000 1546.14215 MILLER 1300 1546.14215 SMITH 800 1004.73877 ADAMS 1100 1004.73877 FORD 3000 1004.73877 SCOTT 3000 1004.73877 JONES 2975 1004.73877 ALLEN 1600 610.100174 BLAKE 2850 610.100174 MARTIN 1250 610.100174 JAMES 950 610.100174 TURNER 1500 610.100174 WARD 1250 610.100174
STDDEV_SAMP
Syntax
OVER STDDEV_SAMP ( expr ) ( analytic_clause )
4-88
SQL Reference
STDDEV_SAMP
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
STDDEV_SAMP computes the cumulative sample standard deviation and returns the square root of the sample variance. You can use it as both an aggregate and analytic function. The expr is a number expression, and the function returns a value of type NUMBER. This function is same as the square root of the VAR_SAMP function. When VAR_SAMP returns null, this function returns null.
See Also: "Aggregate Functions" on page 4-6 and "VAR_SAMP"
on page 4-114.
Aggregate Example
See the example for "STDDEV_POP" on page 4-87.
Analytic Example
The following example returns the sample standard deviation of salaries in the EMP table by department:
SELECT deptno, ename, hiredate, sal, STDDEV_SAMP(sal) OVER (PARTITION BY deptno ORDER BY hiredate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sdev FROM emp; DEPTNO ---------10 10 10 20 20 20 20 20 30 30 30 30 30 30 ENAME ---------CLARK KING MILLER SMITH JONES FORD SCOTT ADAMS ALLEN WARD BLAKE TURNER MARTIN JAMES HIREDATE SAL CUM_SDEV --------- ---------- ---------09-JUN-81 2450 17-NOV-81 5000 1803.12229 23-JAN-82 1300 1893.62967 17-DEC-80 800 02-APR-81 2975 1537.95725 03-DEC-81 3000 1263.01557 19-APR-87 3000 1095.8967 23-MAY-87 1100 1123.3321 20-FEB-81 1600 22-FEB-81 1250 247.487373 01-MAY-81 2850 841.130192 08-SEP-81 1500 715.308791 28-SEP-81 1250 666.520817 03-DEC-81 950 668.331255
Functions 4-89
SUBSTR
SUBSTR
Syntax
, SUBSTR ( char , m n )
Purpose
SUBSTR returns a portion of char, beginning at character m, n characters long.
s
If m is 0, it is treated as 1. 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. If n is omitted, Oracle returns all characters to the end of char. If n is less than 1, a null is returned.
s
s
s
Floating-point numbers passed as arguments to SUBSTR are automatically converted to integers.
SELECT SUBSTR('ABCDEFG',3,4) "Substring" FROM DUAL; Substring --------CDEF
Example 2
SELECT SUBSTR('ABCDEFG',-5,4) "Substring" FROM DUAL; Substring --------CDEF
4-90
SQL Reference
SUM
SUBSTRB
Syntax
, SUBSTRB ( char , m n )
Purpose
SUBSTRB is 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. Floating-point numbers passed as arguments to SUBSTRB are automatically converted to integers.
Example
Assume a double-byte database character set:
SELECT SUBSTRB('ABCDEFG',5,4.2) "Substring with bytes" FROM DUAL; Substring with bytes -------------------CD
SUM
Syntax
DISTINCT ALL SUM ( expr ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Functions 4-91
SUM
Purpose
SUM returns sum of values of expr. You can use it as an aggregate or analytic function.
See Also: "Aggregate Functions" on page 4-6
Aggregate Function Example
The following example calculates the sum of all salaries in the EMP table:
SELECT SUM(sal) "Total" FROM emp; Total ---------29025
Analytic Example
The following example calculates, for each manager, a cumulative total of salaries of employees who answer to that manager that are equal to or less than the current salary:
SELECT mgr, ename, sal, SUM(sal) OVER (PARTITION BY mgr ORDER BY sal RANGE UNBOUNDED PRECEDING) l_csum FROM emp; MGR ---------7566 7566 7698 7698 7698 7698 7698 7782 7788 7839 7839 7839 7902 ENAME SAL L_CSUM ---------- ---------- ---------SCOTT 3000 6000 FORD 3000 6000 JAMES 950 950 WARD 1250 3450 MARTIN 1250 3450 TURNER 1500 4950 ALLEN 1600 6550 MILLER 1300 1300 ADAMS 1100 1100 CLARK 2450 2450 BLAKE 2850 5300 JONES 2975 8275 SMITH 800 800 KING 5000 5000
4-92
SQL Reference
SYS_CONTEXT
SYS_CONTEXT
Syntax
, SYS_CONTEXT ( ' namespace ' , ' attribute ' length )
Purpose
SYS_CONTEXT returns the value of attribute associated with the context namespace. You can use this function in both SQL and PL/SQL statements. The context namespace must already have been created, and the associated attribute and its value must also have been set using the DBMS_SESSION.SET_CONTEXT procedure. The namespace must be a valid SQL identifier, and the attribute name cannot exceed 30 bytes in length. The datatype of the return value is VARCHAR2. The default maximum size of the return value is 256 bytes. You can override this default by specifying the optional length parameter. The valid range of values is 1 to 4000 bytes. (If you specify an invalid value, Oracle ignores it and uses the default.) Oracle8i provides a built-in namespace called USERENV, which describes the current session. The predefined attributes of namespace USERENV are listed Table 41 on page 4-94, along with the lengths of their return strings.
See Also:
s
Oracle8i Application Developer's Guide - Fundamentals for information on using the application context feature in your application development. "CREATE CONTEXT" on page 7-261 for information on creating user-defined context namespaces. Oracle8i Supplied PL/SQL Packages Reference for information on the DBMS_SESSION.SET_CONTEXT procedure.
s
s
Example 1
The following statement returns the name of the user who logged onto the database:
SELECT SYS_CONTEXT ('USERENV', 'SESSION_USER') FROM DUAL;
Functions 4-93
SYS_CONTEXT
SYS_CONTEXT ('USERENV', 'SESSION_USER') -----------------------------------------------------SCOTT
Example 2
The following example returns the group number that was set as the value for the attribute GROUP_NO in the PL/SQL package that was associated with the context HR_APPS when HR_APPS was created:
SELECT SYS_CONTEXT ('hr_apps', 'group_no') "User Group" FROM DUAL; User Group ---------Sales
Table 41 Predefined Attributes of Namespace USERENV
Return Length (bytes) 10
Attribute TERMINAL
Return Value The operating system identifier for the client of the current session. In distributed SQL statements, this option returns the identifier for your local session. In a distributed environment, this is supported only for remote SELECTs, not for remote INSERTs, UPDATEs, or DELETEs. (The return length of this parameter may vary by operating system.) The language and territory currently used by your session, along with the database character set, in this form: language_territory.characterset
LANGUAGE
52
LANG SESSIONID INSTANCE
The ISO abbreviation for the language name, a shorter form than the existing 'LANGUAGE' parameter. The auditing session identifier. You cannot use this option in distributed SQL statements. The instance identification number of the current instance.
62 30 30
4-94
SQL Reference
SYS_CONTEXT
Table 41 Predefined Attributes of Namespace USERENV
Return Length (bytes) 30
Attribute ENTRYID
Return Value The available auditing entry identifier. You cannot use this option in distributed SQL statements. To use this keyword in USERENV, the initialization parameter AUDIT_TRAIL must be set to TRUE. TRUE if you currently have the DBA role enabled and FALSE if you do not. Returns up to 64 bytes of user session information that can be stored by an application using the DBMS_APPLICATION_INFO package. The territory of the current session. The currency of the current session. The current calendar of the current session. The date format for the session. The language used for expressing dates. BINARY or the linguistic sort basis. The name of the user whose privilege the current session is under. User ID of the user whose privilege the current session is under Database user name by which the current user is authenticated. This value remains the same throughout the duration of the session. Identifier of the database user name by which the current user is authenticated. Name of the default schema being used in the current schema. This value can be changed during the session with an ALTER SESSION SET CURRENT_SCHEMA statement. Identifier of the default schema being used in the current session. Name of the database user who opened the current session on behalf of SESSION_USER.
ISDBA CLIENT_INFO
30 64
NLS_TERRITORY NLS_CURRENCY NLS_CALENDAR NLS_DATE_FORMAT NLS_DATE_LANGUAGE NLS_SORT CURRENT_USER CURRENT_USERID SESSION_USER
62 62 62 62 62 62 30 30 30
SESSION_USERID CURRENT_SCHEMA
30 30
CURRENT_SCHEMAID PROXY_USER
30 30
Functions 4-95
SYS_CONTEXT
Table 41 Predefined Attributes of Namespace USERENV
Return Length (bytes) 30 256 30 54 30 256
Attribute PROXY_USERID DB_DOMAIN DB_NAME HOST OS_USER EXTERNAL_NAME
Return Value Identifier of the database user who opened the current session on behalf of SESSION_USER. Domain of the database as specified in the DB_DOMAIN initialization parameter. Name of the database as specified in the DB_NAME initialization parameter Name of the host machine from which the client has connected. Operating system username of the client process that initiated the database session External name of the database user. For SSL authenticated sessions using v.503 certificates, this field returns the distinguished name (DN) stored in the user certificate. IP address of the machine from which the client is connected. Network protocol being used for communication, as specified in the 'PROTOCOL=protocol' portion of the connect string. Job ID of the current session if it was established by an Oracle background process. Null if the session was not established by a background process. Job ID of the current session if it was established by a client foreground process. Null if the session was not established by a foreground process. How the user was authenticated:
s s s
IP_ADDRESS NETWORK_PROTOCOL
30 256
BG_JOB_ID
30
FG_JOB_ID
30
AUTHENTICATION_TYPE
30
s
DATABASE: username/password authentication OS: operating system external user authentication NETWORK: network protocol or ANO authentication PROXY: OCI proxy connection authentication 256
AUTHENTICATION_DATA
Data being used to authenticate the login user. For X.503 certificate authenticated sessions, this field returns the context of the certificate in HEX2 format.
4-96
SQL Reference
SYS_GUID
Table 41 Predefined Attributes of Namespace USERENV
Return Length (bytes)
Attribute
Return Value Note: You can change the return value of the AUTHENTICATION_DATA attribute using the length parameter of the syntax. Values of up to 4000 are accepted. This is the only attribute of USERENV for which Oracle implements such a change.
SYS_GUID
Syntax
SYS_GUID ( )
Purpose
SYS_GUID generates and returns a globally unique identifier (RAW value) made up of 16 bytes. On most platforms, the generated identifier consists of a host identifier and a process or thread identifier of the process or thread invoking the function, and a nonrepeating value (sequence of bytes) for that process or thread.
Example
The second line of this example returns the 32-character hexadecimal representation of the 16-byte raw value of the global unique identifier.
INSERT INTO my_table VALUES ('BOB', SYS_GUID()); SELECT SYS_GUID() FROM DUAL; SYS_GUID() -------------------------------54FA6C5E19733A05E03400400B40DCB1
Functions 4-97
SYSDATE
SYSDATE
Syntax
SYSDATE
Purpose
SYSDATE 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-1999 20:27:11
TAN
Syntax
TAN ( n )
Purpose
TAN 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
4-98
SQL Reference
TO_CHAR (date conversion)
TANH
Syntax
TANH ( n )
Purpose
TANH returns the hyperbolic tangent of n.
Example
SELECT TANH(.5) "Hyperbolic tangent of .5" FROM DUAL; Hyperbolic tangent of .5 -----------------------.462117157
TO_CHAR (date conversion)
Syntax
, , TO_CHAR ( d fmt ) ' nlsparam '
Purpose
TO_CHAR 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 "Format Models" on page 2-38. 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.
Functions 4-99
TO_CHAR (number conversion)
Example
SELECT TO_CHAR(HIREDATE, 'Month DD, YYYY') "New date format" FROM emp WHERE ename = 'BLAKE'; New date format -----------------May 01, 1981
TO_CHAR (number conversion)
Syntax
, , TO_CHAR ( n fmt ) ' nlsparam '
Purpose
TO_CHAR 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 "Format Models" on page 2-38. The 'nlsparams' specifies these characters that are returned by number format elements:
s
decimal character group separator local currency symbol international currency symbol
s
s
s
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
4-100 SQL Reference
TO_DATE
quoted string, you must use two single quotation marks around the parameter values. Ten characters are available for the currency symbol. If you omit 'nlsparams' or any one of the parameters, this function uses the default parameter values for your session.
Example 1
In this example, the output is blank padded to the left of the currency symbol.
SELECT TO_CHAR(-10000,'L99G999D99MI') "Amount" FROM DUAL; Amount -------------$10,000.00-
Example 2
SELECT TO_CHAR(-10000,'L99G999D99MI', 'NLS_NUMERIC_CHARACTERS = '',.'' NLS_CURRENCY = ''AusDollars'' ') "Amount" FROM DUAL; Amount ------------------AusDollars10.000,00-
Note: In the optional number format fmt, L designates local
currency symbol and MI designates a trailing minus sign. See Table 27 on page 2-41 for a complete listing of number format elements.
TO_DATE
Syntax
, , TO_DATE ( char fmt ) ' nlsparam '
Functions
4-101
TO_LOB
Purpose
TO_DATE 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 an integer. 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.
See Also: "Date Format Models" on page 2-45.
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_LOB
Syntax
TO_LOB ( long_column )
Purpose
TO_LOB converts LONG or LONG RAW values in the column long_column to LOB values. You can apply this function only to a LONG or LONG RAW column, and only in the SELECT list of a subquery in an INSERT statement (see "INSERT" on page 7-539). Before using this function, you must create a LOB column to receive the converted LONG values. To convert LONGs, create a CLOB column. To convert LONG RAWs, create a BLOB column.
Example
Given the following tables:
4-102 SQL Reference
TO_NUMBER
CREATE TABLE long_table (n NUMBER, long_col LONG); CREATE TABLE lob_table (n NUMBER, lob_col CLOB);
use this function to convert LONG to LOB values as follows:
INSERT INTO lob_table SELECT n, TO_LOB(long_col) FROM long_table;
TO_MULTI_BYTE
Syntax
TO_MULTI_BYTE ( char )
Purpose
TO_MULTI_BYTE returns char with all of its single-byte characters converted to their corresponding multibyte characters. Any single-byte characters in char that have no multibyte equivalents appear in the output string as single-byte characters. This function is useful only if your database character set contains both single-byte and multibyte characters.
TO_NUMBER
Syntax
, , TO_NUMBER ( char fmt ) ' nlsparam '
Purpose
TO_NUMBER 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.
Functions
4-103
TO_SINGLE_BYTE
Example 1
UPDATE emp SET sal = sal + TO_NUMBER('100.00', '9G999D99') WHERE ename = 'BLAKE';
The 'nlsparams' string in this function has the same purpose as it does in the TO_CHAR function for number conversions.
See Also: "TO_CHAR (number conversion)" on page 4-100.
Example 2
SELECT TO_NUMBER('-AusDollars100','L9G999D99', ' NLS_NUMERIC_CHARACTERS = '',.'' NLS_CURRENCY = ''AusDollars'' ') "Amount" FROM DUAL; Amount ----------100
TO_SINGLE_BYTE
Syntax
TO_SINGLE_BYTE ( char )
Purpose
TO_SINGLE_BYTE returns char with all of its multibyte characters converted to their corresponding single-byte characters. Any multibyte characters in char that have no single-byte equivalents appear in the output as multibyte characters. This function is useful only if your database character set contains both single-byte and multibyte characters.
4-104 SQL Reference
TRANSLATE
TRANSLATE
Syntax
TRANSLATE ( ' char ' , ' from ' , ' to ' )
Purpose
TRANSLATE 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 an empty string for to 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.
Example 1
The following 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') "License" FROM DUAL; License -------9XXX999
Example 2
The following 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
Functions
4-105
TRANSLATE ... USING
TRANSLATE ... USING
Syntax
CHAR_CS TRANSLATE ( text USING NCHAR_CS )
Purpose
TRANSLATE ... USING converts text into the character set specified for conversions between the database character set and the national character set. The text argument is the expression to be converted. Specifying the USING CHAR_CS argument converts text into the database character set. The output datatype is VARCHAR2. Specifying the USING NCHAR_CS argument converts text into the national character set. The output datatype is NVARCHAR2. This function is similar to the Oracle CONVERT function, but must be used instead of CONVERT if either the input or the output datatype is being used as NCHAR or NVARCHAR2.
Example 1
CREATE TABLE t1 (char_col CHAR(20), nchar_col nchar(20)); INSERT INTO t1 VALUES ('Hi', N'Bye'); SELECT * FROM t1; CHAR_COL -------Hi NCHAR_COL --------Bye
Example 2
UPDATE t1 SET nchar_col = TRANSLATE(char_col USING NCHAR_CS); UPDATE t1 SET char_col = TRANSLATE(nchar_col USING CHAR_CS); SELECT * FROM t1;
4-106 SQL Reference
TRIM
CHAR_COL -------Hi
NCHAR_COL --------Hi
Example 3
UPDATE t1 SET nchar_col = TRANSLATE('deo' USING NCHAR_CS); UPDATE t1 SET char_col = TRANSLATE(N'deo' USING CHAR_CS); SELECT * FROM t1; CHAR_COL -------deo NCHAR_COL --------deo
TRIM
Syntax
LEADING TRAILING BOTH trim_character TRIM ( trim_source ) FROM
trim_character
Purpose
TRIM enables you to trim leading or trailing characters (or both) from a character string. If trim_character or trim_source is a character literal, you must enclose it in single quotes.
s
If you specify LEADING, Oracle removes any leading characters equal to trim_character. If you specify TRAILING, Oracle removes any trailing characters equal to trim_character. If you specify BOTH or none of the three, Oracle removes leading and trailing characters equal to trim_character.
s
s
Functions
4-107
TRUNC (Number Function)
s
If you do not specify trim_character, the default value is a blank space. If you specify only trim_source, Oracle removes leading and trailing blank spaces. The function returns a value with datatype VARCHAR2. The maximum length of the value is the length of trim_source. If either trim_source or trim_character is a null value, then the TRIM function returns a null value.
s
s
s
This example trims leading and trailing zeroes from a number:
Example
SELECT TRIM (0 FROM 0009872348900) "TRIM Example" FROM DUAL; TRIM example -----------98723489
TRUNC (Number Function)
Syntax
, TRUNC ( n m )
Purpose
TRUNC returns n truncated to m decimal places. If m is omitted, n is truncated to 0 places. m can be negative to truncate (make zero) m digits left of the decimal point.
Example
SELECT TRUNC(15.79,1) "Truncate" FROM DUAL; Truncate ---------15.7 SELECT TRUNC(15.79,-1) "Truncate" FROM DUAL;
4-108 SQL Reference
UID
Truncate ---------10
TRUNC (Date Function)
Syntax
, TRUNC ( d fmt )
Purpose
TRUNC 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 "ROUND and TRUNC Date Functions" on page 4-117 for the permitted format models to use in fmt.
Example
SELECT TRUNC(TO_DATE('27-OCT-92','DD-MON-YY'), 'YEAR') "New Year" FROM DUAL; New Year --------01-JAN-92
UID
Syntax
UID
Purpose
UID returns an integer that uniquely identifies the session user (the user who logged on).
Functions
4-109
UPPER
Example
SELECT UID FROM DUAL; UID ---------19
UPPER
Syntax
UPPER ( char )
Purpose
UPPER returns char, with all letters uppercase. The return value has the same datatype as the argument char.
Example
SELECT UPPER('Large') "Uppercase" FROM DUAL; Upper ----LARGE
USER
Syntax
USER
Purpose
USER returns the name of the session user (the user who logged on) with the datatype VARCHAR2. Oracle compares values of this function with blank-padded comparison semantics.
4-110 SQL Reference
USERENV
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 ------------------------------ ---------SCOTT 19
USERENV
Syntax
USERENV ( option )
Purpose
USERENV 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 USERENV in the condition of a CHECK constraint. The argument option can have any of these values: 'ISDBA' 'LANGUAGE' returns 'TRUE' if you currently have the ISDBA role enabled and 'FALSE' if you do not. returns the language and territory currently used by your session along with the database character set in this form:
language_territory.characterset
'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. In a distributed environment, this is supported only for remote SELECTs, not for remote INSERTs, UPDATEs, or DELETEs. returns your auditing session identifier. You cannot use this option in distributed SQL statements.
'SESSIONID'
Functions
4-111
VALUE
'ENTRYID'
returns available auditing entry identifier. You cannot use this option in distributed SQL statements. To use this keyword in USERENV, the initialization parameter AUDIT_TRAIL must be set to TRUE. returns the ISO abbreviation for the language name, a shorter form than the existing 'LANGUAGE' parameter. returns the instance identification number of the current instance. returns up to 64 bytes of user session information that can be stored by an application using the DBMS_APPLICATION_INFO package. CAUTION: Some commercial applications may be using this context value. Check the applicable documentation for those applications to determine what restrictions they may impose on use of this context area. Oracle recommends that you use the application context feature or the SYS_CONTEXT function with the USERENV option. These alternatives are more secure and flexible. See Also:
s
'LANG' 'INSTANCE' 'CLIENT_INFO'
Oracle8i Concepts. for information on application context. "CREATE CONTEXT" on page 7-261 and "SYS_CONTEXT" on page 4-93.
s
Example
SELECT USERENV('LANGUAGE') "Language" FROM DUAL; Language ----------------------------------AMERICAN_AMERICA.WE8DEC
VALUE
Syntax
VALUE ( correlation_variable )
4-112 SQL Reference
VAR_POP
Purpose
In a SQL statement, VALUE takes as its argument a correlation variable (table alias) associated with a row of an object table and returns object instances stored in the object table. The type of the object instances is the same type as the object table.
Example
CREATE TYPE emp_type AS OBJECT (eno NUMBER, ename VARCHAR2(20), salary NUMBER); CREATE TABLE emp_table OF emp_type (primary key (eno, ename)); INSERT INTO emp_table VALUES (10, 'jack', 50000); SELECT VALUE(e) FROM emp_table e; VALUE(E)(ENO, ENAME, SALARY) ---------------------------------------------------EMP_TYPE(10, 'jack', 50000)
VAR_POP
Syntax
OVER VAR_POP ( expr ) ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
VAR_POP returns the population variance of a set of numbers after discarding the nulls in this set. You can use it as both an aggregate and analytic function. The expr is a number expression, and the function returns a value of type NUMBER. If the function is applied to an empty set, it returns null. The function makes the following calculation:
(SUM(expr2) - SUM(expr)2 / COUNT(expr)) / COUNT(expr)
See Also: "Aggregate Functions" on page 4-6
Functions
4-113
VAR_SAMP
Aggregate Example
The following example returns the population variance of the salaries in the EMP table:
SELECT VAR_POP(sal) FROM emp; VAR_POP(SAL) -----------1298434.31
Analytic Example
The following example calculates the cumulative population and sample variances of the monthly sales in 1998:
SELECT s_month, VAR_POP(SUM(s_amount)) OVER (ORDER BY s_month), VAR_SAMP(SUM(s_amount)) OVER (ORDER BY s_month) FROM sales WHERE s_year =1998 GROUP BY s_month; S_MONTH VAR_POP(SU VAR_SAMP(S ---------- ---------- ---------6 0 8 440588496 881176992 11 538819892 808229838
VAR_SAMP
Syntax
OVER VAR_SAMP ( expr ) ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
VAR_SAMP returns the sample variance of a set of numbers after discarding the nulls in this set. You can use it as both an aggregate and analytic function.
4-114 SQL Reference
VARIANCE
The expr is a number expression, and the function returns a value of type NUMBER. If the function is applied to an empty set, it returns null. The function makes the following calculation:
(SUM(expr2) - SUM(expr)2 / COUNT(expr)) / (COUNT(expr) - 1)
This function is similar to VARIANCE, except that given an input set of one element, VARIANCE returns 0 and VAR_SAMP returns null.
See Also: "Aggregate Functions" on page 4-6
Aggregate Example
The following example returns the sample variance of the salaries in the EMP table.
SELECT VAR_SAMP(sal) FROM emp; VAR_SAMP(SAL) ------------1398313.87
Analytic Example
See the example at "VAR_POP" on page 4-113.
VARIANCE
Syntax
DISTINCT ALL VARIANCE ( expr ) OVER ( analytic_clause )
For information on syntax and semantics, see "Analytic Functions" on page 4-7.
Purpose
VARIANCE returns variance of expr. You can use it as an aggregate or analytic function. Oracle calculates the variance of expr as follows:
s
0 if the number of rows in expr = 1
Functions
4-115
VSIZE
s
VAR_SAMP if the number of rows in expr > 1
Aggregate Example
The following example calculates the variance of all salaries in the EMP table:
SELECT VARIANCE(sal) "Variance" FROM emp; Variance ---------1389313.87
Analytic Example
The query returns the cumulative variance of salary values in Department 30 ordered by hiredate.
SELECT ename, sal, VARIANCE(sal) OVER (ORDER BY hiredate) FROM emp WHERE deptno=30; ENAME SAL ---------- ---------ALLEN 1600 WARD 1250 BLAKE 2850 TURNER 1500 MARTIN 1250 JAMES 950 VARIANCE(S ---------0 61250 707500 511666.667 444250 446666.667
VSIZE
Syntax
VSIZE ( expr )
Purpose
VSIZE returns the number of bytes in the internal representation of expr. If expr is null, this function returns null.
4-116 SQL Reference
ROUND and TRUNC Date Functions
Example
SELECT ename, VSIZE (ename) "BYTES" FROM emp WHERE deptno = 10; ENAME BYTES ---------- ---------CLARK 5 KING 4 MILLER 6
ROUND and TRUNC Date Functions
Table 42 lists the format models you can use 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.
Table 42 Date Format Models for the ROUND and TRUNC Date Functions
Rounding or Truncating Unit One greater than the first two digits of a four-digit year. Year (rounds up on July 1)
Format Model CC SCC SYYYY YYYY YEAR SYEAR YYY YY Y IYYY IY IY I Q MONTH MON MM RM WW
ISO Year
Quarter (rounds up on the sixteenth day of the second month of the quarter) Month (rounds up on the sixteenth day)
Same day of the week as the first day of the year.
Functions
4-117
User-Defined Functions
Table 42 (Cont.) Date Format Models for the ROUND and TRUNC Date Functions
Format Model IW W DDD DD J DAY DY D HH HH12 HH24 MI Rounding or Truncating Unit Same day of the week as the first day of the ISO year. Same day of the week as the first day of the month. Day
Starting day of the week
Hour
Minute
The starting day of the week used by the format models DAY, DY, and D is specified implicitly by the initialization parameter NLS_TERRITORY.
See Also: Oracle8i Reference and Oracle8i National Language
Support Guide for information on this parameter.
User-Defined Functions
You can write user-defined functions in PL/SQL or Java to provide functionality that is not available in SQL or SQL functions. User functions can appear in a SQL statement anywhere SQL functions can appear, that is, wherever an expression can occur. For example, user functions can be used in the following:
s
The select list of a SELECT statement The condition of a WHERE clause CONNECT BY, START WITH, ORDER BY, and GROUP BY clauses The VALUES clause of an INSERT statement The SET clause of an UPDATE statement
s
s
s
s
4-118 SQL Reference
User-Defined Functions
See Also:
s
"CREATE FUNCTION" on page 7-284 for information on creating functions, including restrictions on user-defined functions. Oracle8i Application Developer's Guide - Fundamentals for a complete description on the creation and use of user functions.
s
Prerequisites
User functions must be created as top-level functions or declared with a package specification before they can be named within a SQL statement. Create user functions as top-level functions by using the CREATE FUNCTION statement described in "CREATE FUNCTION" on page 7-284. To specify packaged functions, see "CREATE PACKAGE" on page 7-344. To use a user function in a SQL expression, you must own or have EXECUTE privilege on the user function. To query a view defined with a user function, you must have SELECT privileges on the view. No separate EXECUTE privileges are needed to select from the view.
Name Precedence
Within a SQL statement, the names of database columns take precedence over the names of functions with no parameters. For example, if user SCOTT creates the following two objects in his own schema:
CREATE TABLE emp(new_sal NUMBER, ...); CREATE FUNCTION new_sal RETURN NUMBER IS BEGIN ... END;
then in the following two statements, the reference to NEW_SAL refers to the column EMP.NEW_SAL:
SELECT new_sal FROM emp; SELECT emp.new_sal FROM emp;
To access the function NEW_SAL, you would enter:
SELECT scott.new_sal FROM emp;
Here are some sample calls to user functions that are allowed in SQL expressions:
circle_area (radius) payroll.tax_rate (empno) scott.payroll.tax_rate (dependent, empno)@ny
Functions
4-119
User-Defined Functions
Example To call the TAX_RATE user function from schema SCOTT, execute it
against the SS_NO and SAL columns in TAX_TABLE, and place the results in the variable INCOME_TAX, specify the following:
SELECT scott.tax_rate (ss_no, sal) INTO income_tax FROM tax_table WHERE ss_no = tax_id;
Naming Conventions
If only one of the optional schema or package names is given, the first identifier can be either a schema name or a package name. For example, to determine whether PAYROLL in the reference PAYROLL.TAX_RATE is a schema or package name, Oracle proceeds as follows:
1. 2.
Check for the PAYROLL package in the current schema. If a PAYROLL package is not found, look for a schema name PAYROLL that contains a top-level TAX_RATE function. If no such function is found, return an error. If the PAYROLL package is found in the current schema, look for a TAX_RATE function in the PAYROLL package. If no such function is found, return an error.
3.
You can also refer to a stored top-level function using any synonym that you have defined for it.
4-120 SQL Reference
5
Expressions, Conditions, and Queries
The ideal condition would be, I admit, that men should be right by instinct. Sophocles, Oedipus Rex This chapter describes how to combine the values, operators, and functions described in earlier chapters evaluate to a value. Topics include:
s
Expressions Conditions Queries and Subqueries
s
s
Expressions
An expression is a combination of one or more values, operators, and SQL functions that evaluate to a value. An expression generally assumes the datatype of its components. This simple expression evaluates to 4 and has datatype NUMBER (the same datatype as its components):
2*2
The following expression is an example of a more complex expression that uses both functions and operators. The 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:
s
The select list of the SELECT statement
Expressions, Conditions, and Queries 5-1
Expressions
s
A condition of the WHERE clause and HAVING clause The CONNECT BY, START WITH, and ORDER BY clauses The VALUES clause of the INSERT statement The SET clause of the UPDATE statement
s
s
s
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);
Expressions have several forms, as shown in the following syntax: expr::=
simple_expression compound_expression variable_expression built_in_function_expression user_defined_function_expression type_constructor_expression CAST_expression CURSOR_expression object_access_expression DECODE_expression CASE_expression expression_list
Oracle does not accept all forms of expressions in all parts of all SQL statements. You must use appropriate expression notation whenever expr appears in conditions, SQL functions, or SQL statements in other parts of this reference. The description of
5-2 SQL Reference
Expressions
each statement in Chapter 7, "SQL Statements", documents the restrictions on the expressions in the statement. The sections that follow describe and provide examples of the various forms of expressions.
Simple Expressions
A simple expression specifies column, pseudocolumn, constant, sequence number, or null. simple_expression::=
table view snapshot . column pseudocolumn text number CURRVAL sequence . NEXTVAL NULL
schema
.
In addition to the schema of a user, schema can also be "PUBLIC" (double quotation marks required), in which case it must qualify a public synonym for a table, view, or materialized view. Qualifying a public synonym with "PUBLIC" is supported only in data manipulation language (DML) statements, not data definition language (DDL) statements. The pseudocolumn can be either LEVEL, ROWID, or ROWNUM. You can use a pseudocolumn only with a table, not with a view or materialized view. NCHAR and NVARCHAR2 are not valid pseudocolumn datatypes.
See Also: "Pseudocolumns" on page 2-56 for more information on
pseudocolumns. Some valid simple expressions are:
emp.ename
Expressions, Conditions, and Queries 5-3
Expressions
'this is a text string' 10 N'this is an NCHAR string'
Compound Expressions
A compound expression specifies a combination of other expressions. compound_expression::=
( + PRIOR * / expr + || expr expr expr )
Note that some combinations of functions are inappropriate and are rejected. For example, the LENGTH function is inappropriate within an aggregate function. Some valid compound expressions are:
('CLARK' || 'SMITH') LENGTH('MOOSE') * 57 SQRT(144) + 72 my_fun(TO_CHAR(sysdate,'DD-MMM-YY')
Variable Expressions
A variable expression specifies a host variable with an optional indicator variable. Note that this form of expression can appear only in embedded SQL statements or SQL statements processed in an Oracle Call Interface (OCI) program. variable_expression::=
5-4 SQL Reference
Expressions
INDICATOR : : host_variable indicator_variable
Some valid variable expressions are:
:employee_name INDICATOR :employee_name_indicator_var :department_location
Built-In Function Expressions
A built-in function expression specifies a call to a single-row SQL function. built_in_function_expression::=
DISTINCT ALL ( function , expr )
Some valid built-in function expressions are:
LENGTH('BLAKE') ROUND(1234.567*43) SYSDATE
For information on built-in functions, see "SQL Functions" on page 4-2. See also "Aggregate Functions" on page 4-6.
Function Expressions
A function expression specifies a call to
s
A SQL built-in function (see Chapter 4, "Functions") A function in an Oracle-supplied package (see Oracle8i Supplied PL/SQL Packages Reference. A function in a user-defined package or in a standalone user-defined function (see "User-Defined Functions" on page 4-118) A user-defined operator (see "CREATE OPERATOR" on page 7-339 and Oracle8i Data Cartridge Developer's Guide)
s
s
s
Expressions, Conditions, and Queries 5-5
Expressions
function_expression::=
package schema . user_defined_operator , @ dblink . ( argument ) . function
Some valid user-defined function expressions are:
circle_area(radius) payroll.tax_rate(empno) scott.payrol.tax_rate(dependents, empno)@ny DBMS_LOB.getlength(column_name)
Type Constructor Expressions
A type constructor expression specifies a call to a type constructor. The argument to the type constructor is any expression or subquery. type_constructor_expression::=
, schema . type_name ( subquery expr )
If type_name is an object type, then the argument list must be an ordered list, where the first argument is a value whose type matches the first attribute of the object type, the second argument is a value whose type matches the second attribute of the object type, and so on. The total number of arguments to the constructor must match the total number of attributes of the object type. If type_name is a varray or nested table type, then the argument list can contain zero or more arguments. Zero arguments implies construction of an empty collection. Otherwise, each argument corresponds to an element value whose type is the element type of the collection type. If type_name is an object type, a varray, or a nested table type, the maximum number of arguments it can contain is 1000 minus some overhead.
5-6 SQL Reference
Expressions
Expression Example type constructor.
This example shows the use of an expression in the call to a
CREATE TYPE address_t AS OBJECT (no NUMBER, street CHAR(31), city CHAR(21), state CHAR(3), zip NUMBER); CREATE TYPE address_book_t AS TABLE OF address_t; DECLARE /* Object Type variable initialized via Object Type Constructor */ myaddr address_t = address_t(500, 'Oracle Parkway', 'Redwood Shores', 'CA', 94065); /* nested table variable initialized to an empty table via a constructor*/ alladdr address_book_t = address_book_t(); BEGIN /* below is an example of a nested table constructor with two elements specified, where each element is specified as an object type constructor. */ insert into employee values (666999, address_book_t(address_t(500, 'Oracle Parkway', 'Redwood Shores', 'CA', 94065), address_t(400, 'Mission Street', 'Fremont', 'CA', 94555))); END;
Subquery Example This example illustrates the use of a subquery in the call to the type constructor.
CREATE TYPE employee AS OBJECT ( empno NUMBER, ename VARCHAR2(20)); CREATE TABLE emptbl of EMPLOYEE; INSERT INTO emptbl VALUES(7377, 'JOHN'); CREATE TYPE project AS OBJECT ( pname VARCHAR2(25), empref REF employee); CREATE TABLE depttbl (dno number, proj project); INSERT INTO depttbl values(10, project('SQL Extensions', (SELECT REF(p) FROM emptbl p WHERE ename='JOHN')));
CAST Expressions
A CAST expression converts one built-in datatype or collection-typed value into another built-in datatype or collection-typed value. CAST_expression::=
Expressions, Conditions, and Queries 5-7
Expressions
expr CAST ( ( subquery ( ) subquery ) AS type_name )
MULTISET
CAST allows you to convert built-in datatypes or collection-typed values of one type into another built-in datatype or collection type. You can cast an unnamed operand (such as a date or the result set of a subquery) or a named collection (such as a varray or a nested table) into a type-compatible datatype or named collection. The type_name must be the name of a built-in datatype or collection type and the operand must be a built-in datatype or must evaluate to a collection value. For the operand, expr can be either a built-in datatype or a collection type, and subquery must return a single value of collection type or built-in type. MULTISET informs Oracle to take the result set of the subquery and return a collection value. Table 51 shows which built-in datatypes can be cast into which other built-in datatypes. (CAST does not support LONG, LONG RAW, or any of the LOB datatypes.)
Table 51 Casting Built-In Datatypes
From/ To CHAR, VARCHAR2 NUMBER DATE RAW ROWID, UROWID NCHAR, NVARCHAR2
a
CHAR, VARCHAR2 X X X X X
NUMBER X X
DATE X
RAW X
ROWID, UROWID X
NCHAR, NVARCHAR2
X X Xa X X X X X
You cannot cast a UROWID to a ROWID if the UROWID contains the value of a ROWID of an index-organized table.
To cast a named collection type into another named collection type, the elements of both collections must be of the same type. If the result set of subquery can evaluate to multiple rows, you must specify the MULTISET keyword. The rows resulting from the subquery form the elements of the collection value into which they are cast. Without the MULTISET keyword, the
5-8 SQL Reference
Expressions
subquery is treated as a scalar subquery, which is not supported in the CAST expression. In other words, scalar subqueries as arguments of the CAST operator are not valid in Oracle8i. Built-In Datatype Examples
SELECT CAST ('1997-10-22' AS DATE) FROM DUAL; SELECT * FROM t1 WHERE CAST (ROWID AS VARCHAR2) = '01234';
Collection Examples The CAST examples that follow use the following userdefined types and tables:
CREATE TYPE address_t AS OBJECT (no NUMBER, street CHAR(31), city CHAR(21), state CHAR(2)); CREATE TYPE address_book_t AS TABLE OF address_t; CREATE TYPE address_array_t AS VARRAY(3) OF address_t; CREATE TABLE emp_address (empno NUMBER, no NUMBER, street CHAR(31), city CHAR(21), state CHAR(2)); CREATE TABLE employees (empno NUMBER, name CHAR(31)); CREATE TABLE dept (dno NUMBER, addresses address_array_t);
This example casts a subquery:
SELECT e.empno, e.name, CAST(MULTISET(SELECT ea.no, ea.street, ea.city, ea.state FROM emp_address ea WHERE ea.empno = e.empno) AS address_book_t) FROM employees e;
CAST converts a varray type column into a nested table:
SELECT CAST(d.addresses AS address_book_t) FROM dept d WHERE d.dno = 111;
The following example casts a MULTISET expression with an ORDER BY clause:
CREATE TABLE projects (empid NUMBER, projname VARCHAR2(10)); CREATE TABLE employees (empid NUMBER, ename VARCHAR2(10)); CREATE TYPE projname_table_type AS TABLE OF VARCHAR2(10);
An example of a MULTISET expression with the above schema is:
SELECT e.ename, CAST(MULTISET(SELECT p.projname FROM projects p
Expressions, Conditions, and Queries 5-9
Expressions
WHERE p.empid=e.empid ORDER BY p.projname) AS projname_table_type) FROM employees e;
CURSOR Expressions
A CURSOR expression returns a nested cursor. This form of expression is similar to the PL/SQL REF cursor. CURSOR_expression::=
CURSOR ( subquery )
A nested cursor is implicitly opened when the containing row is fetched from the parent cursor. The nested cursor is closed only when:
s
The nested cursor is explicitly closed by the user The parent cursor is reexecuted The parent cursor is closed The parent cursor is cancelled An error arises during fetch on one of its parent cursors (it is closed as part of the clean-up)
s
s
s
s
Restrictions: The following restrictions apply to the CURSOR expression:
s
Nested cursors can appear only in a SELECT statement that is not nested in any other query expression, except when it is a subquery of the CURSOR expression itself. Nested cursors can appear only in the outermost SELECT list of the query specification. Nested cursors cannot appear in views. You cannot perform BIND and EXECUTE operations on nested cursors.
s
s
s
Example
SELECT d.deptno, CURSOR(SELECT e.empno, CURSOR(SELECT p.projnum, p.projname FROM projects p WHERE p.empno = e.empno)
5-10
SQL Reference
Expressions
FROM TABLE(d.employees) e) FROM dept d WHERE d.dno = 605;
Object Access Expressions
An object access expression specifies attribute reference and method invocation. object_access_expression::=
, . attribute table_alias . column . , argument method ( ) argument . method ( )
object_table_alias
The column parameter can be an object or REF column. When a type's member function is invoked in the context of a SQL statement, if the SELF argument is null, Oracle returns null and the function is not invoked. Examples in this section use the following user-defined types and tables:
CREATE OR REPLACE TYPE employee_t AS OBJECT (empid NUMBER, name VARCHAR2(31), birthdate DATE, MEMBER FUNCTION age RETURN NUMBER, PRAGMA RESTRICT_REFERENCES (age, RNPS, WNPS, WNDS) ); CREATE OR REPLACE TYPE BODY employee_t AS MEMBER FUNCTION age RETURN NUMBER IS var NUMBER; BEGIN var := TRUNC(MONTHS_BETWEEN(SYSDATE, birthdate) /12); RETURN(var); END; END; CREATE TABLE department (dno NUMBER, manager EMPLOYEE_T);
Expressions, Conditions, and Queries 5-11
Expressions
Examples The following examples update and select from the object columns and
method defined above.
UPDATE department d SET d.manager.empid = 100; SELECT d.manager.name, d.manager.age() FROM department d;
DECODE Expressions
A DECODE expression uses the special DECODE syntax: DECODE_expression::=
, DECODE ( expr , search , result
,
default ) ;
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 nonpadded comparison semantics. For information on these semantics, see the section"Datatype Comparison Rules" on page 2-32. The search, result, and default values can be derived from expressions. 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 "Data Conversion" on page 2-36. 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.
5-12
SQL Reference
Expressions
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, 20, 30, 40, 'ACCOUNTING', 'RESEARCH', 'SALES', 'OPERATION', 'NONE')
CASE Expressions
CASE expressions let you use IF ... THEN ... ELSE logic in SQL statements without having to invoke procedures. The syntax is: CASE_expression::=
, CASE WHEN condition THEN expr1
ELSE
expr2 END
Oracle searches for the first WHEN ... THEN pair for which condition is true.
s
If Oracle finds such a pair, then the result of the CASE expression is expr1. If Oracle does not find such a pair,
s
s
If an ELSE clause is specified, the result of the CASE expression is expr2. If no ELSE clause is specified, the result of the CASE expression in null.
s
At least one occurrence of expr1 or expr2 must be non-null.
Note: The maximum number of arguments in a CASE expression is 255, and each WHEN ... THEN pair counts as two arguments. To avoid exceeding the limit of 128 choices, you can nest CASE expressions. That is expr1 can itself be a CASE expression. Example The following statement finds the average salary of all employees in the
EMP table. If an employee's salary is less than $2000, the CASE expression uses $2000 instead.
SELECT AVG(CASE WHEN e.sal > 2000 THEN e.sal ELSE 2000 END) from emp e;
Expressions, Conditions, and Queries 5-13
Conditions
Expression List
An expression list is a series of expressions separated by a comma. The entire series is enclosed in parentheses. expression_list::=
, ( expr )
An expression list can contain up to 1000 expressions. Some valid expression lists are:
(10, 20, 40) ('SCOTT', 'BLAKE', 'TAYLOR') (LENGTH('MOOSE') * 57, -SQRT(144) + 72, 69)
Conditions
A condition specifies a combination of one or more expressions and logical operators that evaluates to either TRUE, FALSE, or unknown. You must use this syntax whenever condition appears in SQL statements in Chapter 7, "SQL Statements". You can use a condition in the WHERE clause of these statements:
s
DELETE SELECT UPDATE
s
s
You can use a condition in any of these clauses of the SELECT statement:
s
WHERE START WITH CONNECT BY HAVING
s
s
s
A condition could be said to be of the "logical" datatype, although Oracle does not formally support such a datatype. The following simple condition always evaluates to TRUE:
5-14
SQL Reference
Conditions
1 = 1
The following more complex condition 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)
Here are some valid conditions:
name = '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
Conditions can have several forms, as shown in the following syntax. The description of each statement in Chapter 7, "SQL Statements", documents the restrictions on the conditions in the statement. The sections that follow describe the various forms of conditions. condition::=
simple_comparison_condition group_comparison_condition membership_condition range_condition NULL_condition EXISTS_condition LIKE_condition compound_condition
Expressions, Conditions, and Queries 5-15
Conditions
Simple Comparison Conditions
A simple comparison condition specifies a comparison with expressions or subquery results. simple_comparison_condition::=
= != ^= <> expr > < >= <= = != expr_list ^= <> ( subquery ) ( subquery ) expr
For information on comparison operators, see "Comparison Operators" on page 3-5.
Group Comparison Conditions
A group comparison condition specifies a comparison with any or all members in a list or subquery.
5-16
SQL Reference
Conditions
group_comparison_condition::=
= != ^= ANY <> expr > ALL < >= <= = ANY != expr_list ^= ALL <> SOME ( subquery expr_list ) , SOME ( subquery ) expr_list
See "SELECT and Subqueries" on page 7-569.
Membership Conditions
A membership condition tests for membership in a list or subquery. membership_condition::=
NOT expr IN ( subquery , NOT expr_list IN ( subquery expr_list ) )
expr_list
Expressions, Conditions, and Queries 5-17
Conditions
Range Conditions
A range condition tests for inclusion in a range. range_condition::=
NOT expr BETWEEN expr AND expr
NULL Conditions
A NULL condition tests for nulls. NULL_condition::=
NOT expr IS NULL
EXISTS Conditions
An EXISTS condition tests for existence of rows in a subquery. EXISTS_condition::=
EXISTS ( subquery )
LIKE Conditions
A LIKE condition specifies a test involving pattern matching. LIKE_condition::=
NOT char1 LIKE char2 ESCAPE ' esc_char '
Compound Conditions
A compound condition specifies a combination of other conditions.
5-18
SQL Reference
Queries and Subqueries
compound_condition::=
( NOT condition condition AND condition OR condition )
Queries and Subqueries
A query is an operation that retrieves data from one or more tables or views. In this reference, a top-level SELECT statement is called a query, and a query nested within another SQL statement is called a subquery. This section describes some types of queries and subqueries and how to use them. The full syntax of all the clauses, and the semantics of the keywords and parameters, appear in "SELECT and Subqueries" on page 7-569.
Creating Simple Queries
The list of expressions that appears after the SELECT keyword and before the FROM clause is called the select list. Each expression expr 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. However, it is always a good idea to qualify table and column references explicitly. 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. 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.
Expressions, Conditions, and Queries 5-19
Queries and Subqueries
See Also: "Hints" on page 2-63 and Oracle8i Designing and Tuning for Performance for more information on hints.
Hierarchical Queries
If a table contains hierarchical data, you can select rows in a hierarchical order using the hierarchical query clause:
START WITH condition CONNECT BY condition
START WITH CONNECT BY
specifies the root row(s) of the hierarchy. specifies the relationship between parent rows and child rows of the hierarchy. Some part of condition must use the PRIOR operator to refer to the parent row. See the PRIOR operator on page 3-16. restricts the rows returned by the query without affecting other rows of the hierarchy.
WHERE
Oracle uses the information from the hierarchical query clause clause to form the hierarchy using the following steps:
1. 2. 3.
Oracle selects the root row(s) of the hierarchy--those rows that satisfy the START WITH condition. Oracle selects the child rows of each root row. Each child row must satisfy the condition of the CONNECT BY condition with respect to one of the root rows. 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. If the query contains a WHERE clause, Oracle eliminates 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. Oracle returns the rows in the order shown in Figure 51. In the diagram children appear below their parents.
4.
5.
5-20
SQL Reference
Queries and Subqueries
Figure 51 Hierarchical Queries
ROOT 1
2
7
9
3
4
8
10
12
5
6
11
To find the children of a parent row, Oracle evaluates the PRIOR expression of the CONNECT BY condition 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 condition can contain other conditions to further filter the rows selected by the query. The CONNECT BY condition cannot contain a subquery. If the CONNECT BY condition 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.
Sorting Query Results
You can use the ORDER BY clause to order the rows selected by a query. Sorting by position is useful in the following cases:
s
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 appear only in the last component query. The ORDER BY clause orders all rows returned by the entire compound query.
s
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 Oracle8i National Language Support Guide. You can change the sort mechanism
Expressions, Conditions, and Queries 5-21
Queries and Subqueries
dynamically from one linguistic sort sequence to another using the ALTER SESSION statement. 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.
Joins
A join is a query that combines rows from two or more tables, views, or materialized views ("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. See the "Equijoin Examples" on page 7-587.
5-22
SQL Reference
Queries and Subqueries
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 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. See the "Self Join Example" on page 7-588.
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 many rows and is rarely useful. For example, the Cartesian product of two tables, each with 100 rows, has 10,000 rows. Always include a join condition unless you specifically need a Cartesian product. If a query joins three or more tables and you do not specify a join condition for a specific pair, the optimizer may choose a join order that avoids producing an intermediate Cartesian product.
Outer Joins
An outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition and 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. See the syntax for an outer join in "SELECT and Subqueries" on page 7-569. Outer join queries are subject to the following rules and restrictions:
s
The (+) operator can appear only in the WHERE clause or, in the context of leftcorrelation (that is, when specifying the TABLE clause) in the FROM clause, and can be applied only to a column of a table or view. If A and B are joined by multiple join conditions, you must use the (+) operator in all of these conditions. If you do not, Oracle will return only the rows resulting from a simple join, but without a warning or error to advise you that you do not have the results of an outer join. The (+) operator can be applied only to a column, not to an arbitrary expression. However, an arbitrary expression can contain a column marked with the (+) operator.
s
s
Expressions, Conditions, and Queries 5-23
Queries and Subqueries
s
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 with an expression. A condition cannot compare any column marked with the (+) operator with a subquery.
s
s
If the WHERE clause contains a condition that compares a column from table B with a constant, the (+) operator must be applied to the column so that Oracle returns the rows from table A for which it has generated NULLs for this column. Otherwise Oracle will return only the results of a simple join. In a query that performs outer joins of more than two pairs of tables, a single table can be the NULL-generated table for only 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.
Using Subqueries
Use subqueries for the following purposes:
s
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 materialized view ("snapshot) in a CREATE VIEW or CREATE MATERIALIZED VIEW statement To define one or more values to be assigned to existing rows in an UPDATE statement To provide values for conditions in a WHERE clause, HAVING clause, or START WITH clause of SELECT, UPDATE, and DELETE statements To provide values for a specified column in an INSERT ... VALUES list To provide values for arguments of a type constructor or a user-defined function To define a table to be operated on by a containing query. You do this by placing the subquery in the FROM clause of the containing query as you would a table name. You may use subqueries in place of tables in this way as well in INSERT, UDPATE, and DELETE statements. Subqueries so used can employ correlation variables, but only those defined within the subquery itself, not outer references. Outer references ("left-
s
s
s
s
s
s
5-24
SQL Reference
Queries and Subqueries
correlated subqueries") are allowed only in the FROM clause of a SELECT statement. See table_collection_expression on page 7-576. A subquery answers multiple-part questions. For example, to determine who works in Taylor's department, you can first use a subquery to determine the department in which Taylor works. You can then answer the original question with the parent SELECT statement. A subquery can contain another subquery. You can nest up to 255 levels of subqueries. If tables in a subquery have the same name as tables in the containing statement, you must prefix any reference to the column of the table from the containing statement with the table name or alias. To make your statements easier for you to read, always qualify the columns in a subquery with the name or alias of the table, view, or materialized view. Oracle performs a correlated subquery when the subquery references a column from a table referred to in the parent statement. A correlated subquery is evaluated once for each row processed by the parent statement. The parent statement can be a SELECT, UPDATE, or DELETE statement. See the "Correlated Subquery Examples" on page 7-595. A correlated subquery answers a multiple-part question whose answer depends on the value in each row processed by the parent statement. For example, you can use a correlated subquery to determine which employees earn more than the average salaries for their departments. In this case, the correlated subquery specifically computes the average salary for each department.
Unnesting of Nested Subqueries
Subqueries are "nested" when they appear in the WHERE clause of the parent statement. When Oracle evaluates a statement with a nested subquery, it must evaluate the subquery portion multiple times and may overlook some efficient access paths or joins. Subquery unnesting unnests and merges the body of the subquery into the body of the statement that contains it, allowing the optimizer to consider them together when evaluating access paths and joins. The optimizer can unnest most subqueries, with some exceptions. Those exceptions include subqueries that contain a CONNECT BY or START WITH clause, a ROWNUM pseudocolumn, one of the set operators, a nested aggregate function, or a correlated reference to a query block that is not the subquery's immediate outer query block.
Expressions, Conditions, and Queries 5-25
Queries and Subqueries
Assuming no restrictions exist, the optimizer automatically unnests some nested subqueries:
s
Uncorrelated IN subqueries IN and EXISTS correlated subqueries as long, as they do not contain aggregate functions or a GROUP BY clause.
s
You can enable extended subquery unnesting by instructing the optimizer to unnest additional types of subqueries:
s
You can unnest an uncorrelated NOT IN subquery by specifying the HASH_AJ or MERGE_AJ hint in the subquery. You can unnest other subqueries by specifying the UNNEST hint in the subquery
s
For information on hints, see Chapter 2, "Basic Elements of Oracle SQL".
Selecting from the DUAL Table
DUAL is a table automatically created by Oracle along with the data dictionary. DUAL 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 statement. Because DUAL has only one row, the constant is returned only once. Alternatively, you can select a constant, pseudocolumn, or expression from any table, but the value will be returned as many times as there are rows in the table. See "SQL Functions" on page 4-2 for many examples of selecting a constant value from DUAL.
Distributed Queries
Oracle's distributed database management system architecture allows you to access data in remote databases using Net8 and an Oracle server. You can identify a remote table, view, or materialized view 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 materialized view.
See Also: "Referring to Objects in Remote Databases" on page 2-79 for more information on referring to database links.
Restrictions on Distributed Queries
Distributed queries are currently subject to the restriction that all tables locked by a FOR UPDATE clause and all tables with LONG columns selected by the query must be
5-26
SQL Reference
Queries and Subqueries
located on the same database. For example, the following statement will raise an error:
SELECT emp_ny.* FROM emp_ny@ny, dept WHERE emp_ny.deptno = dept.deptno AND dept.dname = 'ACCOUNTING' FOR UPDATE OF emp_ny.sal;
The following statement fails 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;
In addition, Oracle currently does not support distributed queries that select userdefined types or object REFs on remote tables.
Expressions, Conditions, and Queries 5-27
Queries and Subqueries
5-28
SQL Reference
6
About SQL Statements
. . . he is eminently plain and direct . . . both in his syntax and in his words . . . . Matthew Arnold, On Translating Homer This chapter describes the various types of Oracle SQL statements, and provides guidelines for finding the right SQL statement for your task. Topics include:
s
Summary of SQL Statements Finding the Right SQL Statement
s
Summary of SQL Statements
The tables in the following sections provide a functional summary of SQL statements and are divided into these categories:
s
Data Definition Language (DDL) Statements Data Manipulation Language (DML) Statements Transaction Control Statements Session Control Statements System Control Statements
s
s
s
s
Data Definition Language (DDL) Statements
Data definition language (DDL) statements enable you to perform these tasks:
s
Create, alter, and drop schema objects Grant and revoke privileges and roles Analyze information on a table, index, or cluster
s
s
About SQL Statements 6-1
Summary of SQL Statements
s
Establish auditing options Add comments to the data dictionary
s
The CREATE, ALTER, and DROP commands require exclusive access to the specified object. For example, an ALTER TABLE statement fails if another user has an open transaction on the specified table. The GRANT, REVOKE, ANALYZE, AUDIT, and COMMENT commands do not require exclusive access to the specified object. For example, you can analyze a table while other users are updating the table. Oracle implicitly commits the current transaction before and after every DDL statement. Many DDL 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 DDL statement would cause this, see Oracle8i Concepts. DDL statements are supported by PL/SQL with the use of the DBMS_SQL package.
See Also: Oracle8i Supplied PL/SQL Packages Reference.
Table 61 lists the DDL statements.
6-2 SQL Reference
Summary of SQL Statements
Table 61 Data Definition Language Statements
ALTER CLUSTER ALTER DATABASE ALTER DIMENSION ALTER FUNCTION ALTER INDEX ALTER MATERIALIZED VIEW / SNAPSHOT ALTER MATERIALIZED VIEW / SHAPSHOT LOG ALTER PACKAGE ALTER PROCEDURE ALTER PROFILE ALTER RESOURCE COST ALTER ROLE ALTER ROLLBACK SEGMENT ALTER SEQUENCE ALTER SNAPSHOT ALTER SHAPSHOT LOG ALTER TABLE ALTER TABLESPACE ALTER TRIGGER ALTER TYPE ALTER USER ALTER VIEW ANALYZE ASSOCIATE STATISTICS AUDIT COMMENT CREATE CLUSTER CREATE CONTEXT CREATE CONTROLFILE CREATE DATABASE CREATE DATABASE LINK CREATE DIMENSION CREATE DIRECTORY CREATE FUNCTION CREATE INDEX CREATE INDEXTYPE CREATE LIBRARY CREATE MATERIALIZED VIEW / SHAPSHOT CREATE MATERIALIZED VIEW / SNAPSHOT LOG CREATE OPERATOR CREATE PACKAGE CREATE PACKAGE BODY CREATE PROCEDURE CREATE PROFILE CREATE ROLE CREATE ROLLBACK SEGMENT CREATE SCHEMA CREATE SEQUENCE CREATE SHAPSHOT CREATE SNAPSHOT LOG CREATE SYNONYM CREATE TABLE CREATE TABLESPACE CREATE TEMPORARY TABLESPACE CREATE TRIGGER CREATE TYPE CREATE USER CREATE VIEW DISASSOCIATE STATISTICS DROP CLUSTER DROP CONTEXT DROP DATABASE LINK DROP DIMENSION DROP DIRECTORY DROP FUNCTION DROP INDEX DROP INDEXTYPE DROP LIBRARY DROP MATERIALIZED VIEW / SNAPSHOT DROP MATERIALIZED VIEW / SNAPSHOT LOG DROP OPERATOR DROP PACKAGE DROP PROCEDURE DROP PROFILE DROP ROLE DROP ROLLBACK SEGMENT DROP SEQUENCE DROP SNAPSHOT DROP SNAPSHOT LOG DROP SYNONYM DROP TABLE DROP TABLESPACE DROP TRIGGER DROP TYPE DROP USER DROP VIEW GRANT NOAUDIT RENAME REVOKE TRUNCATE
About SQL Statements 6-3
Summary of SQL Statements
Data Manipulation Language (DML) Statements
Data manipulation language (DML) statements query and manipulate data in existing schema objects. These statements do not implicitly commit the current transaction.
Table 62 Data Manipulation Language Statements
Statement CALL DELETE EXPLAIN PLAN INSERT LOCK TABLE SELECT UPDATE
The CALL and EXPLAIN PLAN statements are supported in PL/SQL only when executed dynamically. All other DML statements are fully supported in PL/SQL.
Transaction Control Statements
Transaction control statements manage changes made by DML statements.
Table 63 Transaction Control Statements
Statement COMMIT ROLLBACK SAVEPOINT SET TRANSACTION
All transaction control statements except certain forms of the COMMIT and ROLLBACK commands are supported in PL/SQL. For information on the restrictions, see "COMMIT" on page 7-230 and "ROLLBACK" on page 7-564.
6-4 SQL Reference
Finding the Right SQL Statement
Session Control Statements
Session control statements dynamically manage the properties of a user session. These statements do not implicitly commit the current transaction. PL/SQL does not support session control statements.
Table 64 Session Control Statements
Statement ALTER SESSION SET ROLE
System Control Statement
The single system control statement dynamically manages the properties of an Oracle instance. This statement does not implicitly commit the current transaction. ALTER SYSTEM is not supported in PL/SQL.
Table 65 System Control Statement
Statement ALTER SYSTEM
Embedded SQL Statements
Embedded SQL statements place DDL, DML, and transaction control statements within a procedural language program. Embedded SQL is supported by the Oracle precompilers and is documented in the following books:
s
Pro*COBOL Precompiler Programmer's Guide Pro*C/C++ Precompiler Programmer's Guide SQL*Module for Ada Programmer's Guide
s
s
Finding the Right SQL Statement
The particular SQL statement you use to accomplish a given database task is sometimes obvious and sometimes difficult to predict. For example, you create a table with the CREATE TABLE statement. However, you don't enable a constraint with the ENABLE CONSTRAINT statement, because such a statement doesn't exist. Rather, you modify the column options using the ALTER TABLE statement.
About SQL Statements 6-5
Finding the Right SQL Statement
This section lists, by database object and task, the appropriate SQL statement to use to accomplish various database tasks. You can then refer to Chapter 7, "SQL Statements", for the syntax and semantics of each SQL statement.
Note: Your ability to use the SQL statements listed in this section
depends on the version and edition of Oracle you are using, as well as the options you have installed. Be sure to read the detailed descriptions in Chapter 7, "SQL Statements", before using these statements.
Database Object / Task application application server auditing call
Operation allowing to connect as a user allowing to connect as a user of database events limit CPU time for limit data blocks read
SQL Statement ALTER USER proxy_clause ALTER USER proxy_clause CREATE TRIGGER CPU_PER_CALL parameter LOGICAL_READS_PER_CALL parameter ALTER SYSTEM CHECKPOINT ALTER DATABASE MOUNT prohibited ALTER CLUSTER allocate_extent_clause ANALYZE ALTER CLUSTER parallel_clause prohibited ALTER CLUSTER physical_attributes_clause prohibited ALTER CLUSTER deallocate_unused_clause ALTER TABLE add_column_options, modify_column_options CREATE TABLE
checkpoint clone database cluster
perform explicitly mount cluster key, change columns of extent, allocate for migrated or chained rows, identify parallelism of, change rename storage characteristics of, change tablespace of, change unused space in, release
column
add to a table or modify define
6-6 SQL Reference
Finding the Right SQL Statement
Database Object / Task
Operation drop from a table generate derived values automatically organization of, define
SQL Statement ALTER TABLE drop_column_clause CREATE TRIGGER CREATE TABLE ALTER SESSION ALTER FUNCTION ... COMPILE ALTER TABLE add_column_options, modify_column_options CREATE TRIGGER ALTER TABLE enable_disable_clause, drop_constraint_clause CREATE TABLE ALTER DATABASE controlfile_clauses ALTER DATABASE CREATE STANDBY CONTROLFILE ALTER SESSION SET NLS_CURRENCY ALTER TABLE cache_clause CREATE TABLE ALTER DATABASE CONVERT CREATE SYNONYM ALTER DATABASE CHARACTER SET ALTER DATABASE controlfile_clauses CREATE DATABASE CREATE DATABASE ALTER DATABASE CREATE DATABASE ALTER DATABASE RESET COMPATIBILITY ALTER DATABASE RENAME GLOBAL_NAME
commit operation compilation constraint
prevent procedure or function from issuing avoid run-time of add to a table or modify business, enforce enable, disable, or drop specify
control file
back up standby, create
currency symbol data
reset for session frequently used, caching specify as temporary or permanent
data dictionary data independence database
convert from Oracle7 to Oracle8i provide character set of, change create script for database character set for, specify datafiles for, specify datafiles of, modify datafiles, establish number of downgrade to an earlier release global name of, change
About SQL Statements 6-7
Finding the Right SQL Statement
Database Object / Task
Operation
SQL Statement
global name resolution, enable for ALTER SESSION SET GLOBAL_NAMES the session instances, establish number of media recovery, design media recovery, perform ongoing mount move a subset to a different Oracle database national character set for, specify national character set of, change open parallelize recovery of place in read-only mode place in read-write mode place in sustained standby recovery mode prepare to re-create recover redo log file groups, establish number of redo log files for, specify redo log files of, create or modify redo log files, establish number of redo log, choose mode for upgrade to Oracle8i database character set specify for a database database events database link transparent logging of close CREATE DATABASE ALTER DATABASE general_recovery_clause ALTER DATABASE managed_recovery_clause ALTER DATABASE MOUNT ALTER TABLE exchange_partition_clause CREATE DATABASE ALTER DATABASE CHARACTER SET ALTER DATABASE OPEN ALTER DATABASE parallel_clause ALTER DATABASE OPEN ALTER DATABASE OPEN ALTER DATABASE general_recovery_clause ALTER DATABASE controlfile_clauses ALTER DATABASE recover_clauses CREATE DATABASE CREATE DATABASE ALTER DATABASE CREATE DATABASE CREATE DATABASE ALTER DATABASE CREATE DATABASE CREATE TRIGGER ALTER SESSION
6-8 SQL Reference
Finding the Right SQL Statement
Database Object / Task database security datafile
Operation enforce authorizations automatic extension of, allow create put online reconstruct damaged reconstruct lost or damaged recover specified replace an old, for recovery resize take offline begin or end backup of number of, establish for a database online, update instance information on specify for a database
SQL Statement CREATE TRIGGER ALTER DATABASE DATAFILE autoextend_clause ALTER DATABASE CREATE DATAFILE ALTER DATABASE DATAFILE ONLINE ALTER DATABASE general_recovery_clause ALTER DATABASE CREATE DATAFILE ALTER DATABASE general_recovery_clause ALTER DATABASE CREATE DATAFILE ALTER DATABASE DATAFILE RESIZE ALTER DATABASE DATAFILE ONLINE/ OFFLINE ALTER TABLESPACE ... BACKUP CREATE DATABASE ALTER SYSTEM check_datafiles_clause CREATE DATABASE See Table 29, "Date Format Elements" on page 2-45. ALTER SESSION SET NLS_NUMERIC_CHARACTERS ALTER DIMENSION ... ADD ALTER DIMENSION
dates decimal character dimension
format of reset for session add a level, hierarchy, or attribute to change the relationships of
drop a level, hierarchy, or attribute ALTER DIMENSION ... DROP from explicitly compile dispatcher processes multi-threaded server, manage ALTER DIMENSION ... COMPILE MTS_ parameters of ALTER SYSTEM
About SQL Statements 6-9
Finding the Right SQL Statement
Database Object / Task domain index
Operation alter rebuild
SQL Statement ALTER INDEX ... PARAMETERS ALTER INDEX rebuild_clause ALTER SESSION SET MAX_DUMP_FILE_SIZE ALTER SESSION SET NLS_LANGUAGE ALTER SESSION CREATE OR REPLACE FUNCTION CREATE OR REPLACE FUNCTION ALTER FUNCTION ALTER INDEX ... [rebuild_clause] DISABLE ALTER INDEX ... [rebuild_clause] ENABLE GLOBAL_NAMES parameter of ALTER SYSTEM ALTER SESSION SET HASH_MULTIBLOCK_IO_COUNT ALTER SESSION SET HASH_JOIN_ENABLED ... ALTER SESSION SET HASH_AREA_SIZE ALTER INDEX rebuild_clause
dump file error messages function
limit the size of language in which displayed, change allow to or prevent from committing a transaction declaration of, change definition of, change recompile explicitly
function-based index disable disabled, re-enable global names hash join operations enforce resolution of data blocks for, allocate in queries, enable or disable memory for, allocate index allow DML operations during rebuilding of
based on a function; see "function- CREATE INDEX ... column_expression based index" based on an indextype; see "domain index" CREATE INDEX domain_index_clause
collect statistics during rebuilding ALTER INDEX rebuild_clause of default attribute values of, change ALTER INDEX partitioning_clauses degree of parallelism for, change direct-load INSERT operations, write to a log ALTER INDEX parallel_clause ALTER INDEX physical_attributes_clause
6-10
SQL Reference
Finding the Right SQL Statement
Database Object / Task
Operation extent for, allocate new key compression, enable
SQL Statement ALTER INDEX allocate_extent_clause ALTER INDEX rebuild_clause
key values, eliminate repetition of ALTER INDEX rebuild_clause merge block contents of physical attributes of a partition of, change physical attributes of a subpartition of, change the physical attributes of, change re-create rebuild operations, write to a log SQL*Loader operations against, write to a log store bytes in reverse order tablespace for, specify tell Oracle not to use unused space, release rename index partition create-time attributes, change ALTER INDEX rebuild_clause ALTER INDEX physical_attributes_clause ALTER INDEX physical_attributes_clause ALTER INDEX physical_attributes_clause ALTER INDEX rebuild_clause ALTER INDEX rebuild_clause ALTER INDEX physical_attributes_clause ALTER INDEX rebuild_clause ALTER INDEX rebuild_clause ALTER INDEX ... [rebuild_clause] UNUSABLE ALTER INDEX deallocate_unused_clause ALTER INDEX rebuild_clause ALTER INDEX rebuild_clause
log direct-load INSERT operations ALTER INDEX physical_attributes_clause log SQL*Loader operations against move to a different tablespace physical attributes of, change physical, logging, or storage characteristics of, change re-create ALTER INDEX physical_attributes_clause ALTER INDEX rebuild_clause ALTER INDEX physical_attributes_clause ALTER INDEX partitioning_clauses ALTER INDEX rebuild_clause
About SQL Statements 6-11
Finding the Right SQL Statement
Database Object / Task
Operation remove from the database specify a tablespace for split into two partitions tell Oracle not to use
SQL Statement ALTER INDEX partitioning_clauses ALTER INDEX rebuild_clause ALTER INDEX partitioning_clauses ALTER INDEX ... UNUSABLE ALTER INDEX rebuild_clause
index subpartition
change a create-time attributes, change
log direct-load INSERT operations ALTER INDEX physical_attributes_clause log SQL*Loader operations against move to a different tablespace physical attributes, change physical, logging, or storage characteristics, change re-create tablespace for, specify tell Oracle not to use index-organized table characteristics, change indexes on a cluster on a nested table storage table on a partitioned table on an index-organized table on columns of a table on scalar typed object attributes instance dynamically modify make an index extent available to switch to a different instance recovery continue after interruption ALTER INDEX physical_attributes_clause ALTER INDEX rebuild_clause ALTER INDEX physical_attributes_clause ALTER INDEX partitioning_clauses ALTER INDEX rebuild_clause ALTER INDEX rebuild_clause ALTER INDEX ... UNUSABLE ALTER TABLE CREATE INDEX CREATE INDEX CREATE INDEX CREATE INDEX CREATE INDEX CREATE INDEX ALTER SYSTEM ALTER INDEX allocate_extent_clause ALTER SESSION SET INSTANCE ALTER DATABASE general_recovery_clause
6-12
SQL Reference
Finding the Right SQL Statement
Database Object / Task instances Java class Java resource Java source licensing LOB columns
Operation number of, establish for a database force resolution of force compilation of force compilation of changing limits or thresholds add to a table or modify
SQL Statement CREATE DATABASE ALTER JAVA ALTER JAVA ALTER JAVA LICENSE_ parameters of ALTER SYSTEM ALTER TABLE add_column_options, modify_column_options, LOB_storage_clause CREATE SYNONYM ALTER MATERIALIZED VIEW refresh_clause ALTER MATERIALIZED VIEW ALTER MATERIALIZED VIEW LOG ALTER MATERIALIZED VIEW parallel_clause ALTER MATERIALIZED VIEW partitioning_clauses ALTER MATERIALIZED VIEW modify_LOB_storage_clause ALTER MATERIALIZED VIEW LOB_storage_clause ALTER MATERIALIZED VIEW ... LOGGING ALTER MATERIALIZED VIEW ... QUERY REWRITE ALTER SESSION SET QUERY_REWRITE_ENABLED
location transparency provide materialized view automatic refresh, change the mode or timing of change from rowid-based to primary-key-based degree of parallelism, specify or change divide into partitions LOB storage characteristics, change LOB storage characteristics, specify log changes to make eligible for query rewrite
make frequently accessed data accessible revalidate storage characteristics, change
ALTER MATERIALIZED VIEW ... CACHE ALTER MATERIALIZED VIEW ... COMPILE ALTER MATERIALIZED VIEW physical_attributes_clause
About SQL Statements 6-13
Finding the Right SQL Statement
Database Object / Task
Operation
SQL Statement ALTER MATERIALIZED VIEW LOG ALTER MATERIALIZED VIEW LOG ALTER MATERIALIZED VIEW LOG partitioning_clauses ALTER MATERIALIZED VIEW LOG ... physical_attributes_clause ALTER MATERIALIZED VIEW LOG ...NEW VALUES ALTER MATERIALIZED VIEW LOG ... ADD ALTER MATERIALIZED VIEW LOG ... ADD ALTER DATABASE DATAFILE END BACKUP ALTER DATABASE general_recovery_clause ALTER DATABASE ARCHIVELOG CREATE DATABASE ALTER SESSION SET NLS_ parameters create an INSTEAD OF trigger CREATE INDEX See Table 27, "Number Format Elements" on page 2-41.
materialized view log automatic refresh, change the mode and timing of change from rowid-based to primary-key-based divide into partitions physical and storage characteristics, change save both old and new values store primary key of changed rows store rowid of changed rows media recovery avoid on startup from specified redo log file prepare for national character set national language support nested table nested table columns numbers specify for a database change settings for the session update in a view indexing format
object references. See REFs online redo log outline reinitialize assign to a different category recompile rename automatically create and store ALTER DATABASE CLEAR LOGFILE ALTER OUTLINE ... CHANGE CATEGORY TO ALTER OUTLINE ... REBUILD ALTER OUTLINE ... RENAME ALTER SESSION SET CREATE_STORED_OUTLINES
6-14
SQL Reference
Finding the Right SQL Statement
Database Object / Task
Operation use to generate execution plans
SQL Statement ALTER SESSION SET USE_STORED_OUTLINES ALTER PACKAGE ALTER PACKAGE ALTER PACKAGE ALTER PACKAGE CREATE TABLE CREATE TABLE ALTER SESSION set_clause ALTER SESSION set_clause ALTER TABLE ALTER TABLE modify_default_attributes_clause ALTER TABLE logging_clause ALTER TABLE merge_partitions_clause ALTER TABLE exchange_partition_clause ALTER TABLE modify_partition_clause PASSWORD_VERIFY_FUNCTION parameter PASSWORD_REUSE_TIME parameter PASSWORD_LOCK_TIME parameter
package
avoid run-time compilation compile explicitly
package body
avoid run-time compilation recompile explicitly
parallelism
specify for a table specify for DML on a table
parameter, initialization parameter, session partition
change the setting for the current session set or change the setting of add to a table or modify default attributes, change logging characteristics, change merge with another partition point to data in a nonpartitioned table real attributes, change
password
complexity of, guarantee make unavailable number of days account will be locked after failed login attempts, specify
number of days before reuse, limit PASSWORD_REUSE_TIME parameter number of days in grace period, specify number of days usable, limit number of times reused, limit special characters in, allow PASSWORD_GRACE_TIME parameter PASSWORD_LIFE_TIME parameter PASSWORD_REUSE_MAX parameter PASSWORD_VERIFY_FUNCTION parameter
About SQL Statements 6-15
Finding the Right SQL Statement
Database Object / Task performance
Operation optimize for index access path optimize for nested loop joins
SQL Statement ALTER SESSION SET OPTIMIZER_INDEX_COST_ADJ ALTER SESSION SET OPTIMIZER_INDEX_CACHING
specify the optimizer approach for ALTER SESSION SET OPTIMIZER_MODE the session procedure allow to or prevent from committing a transaction avoid run-time compilation recompile explicitly profile resource limit, add to resource limit, change resource limit, drop from recovery recovery data redo log distributed, enable or disable discard remove changes from reset sequence of specify mode of redo log file add ALTER SESSION ALTER PROCEDURE ALTER PROCEDURE ALTER PROFILE ALTER PROFILE ALTER PROFILE ALTER SYSTEM distributed_recovery_clause ALTER DATABASE RESETLOGS ALTER DATABASE OPEN RESETLOGS ALTER DATABASE OPEN RESETLOGS CREATE DATABASE ALTER DATABASE ADD LOGFILE MEMBER
automatically generates names for ALTER DATABASE general_recovery_clause clear drop enable or disable thread rename number of, establish for a database ALTER DATABASE CLEAR LOGFILE ALTER DATABASE DROP LOGFILE ALTER DATABASE ENABLE THREAD ALTER DATABASE RENAME FILE CREATE DATABASE
archive manually or automatically ALTER SYSETM archive_log_clause number of, establish for a database CREATE DATABASE
6-16
SQL Reference
Finding the Right SQL Statement
Database Object / Task
Operation specify a path for switch manually
SQL Statement ALTER SESSION SET LOG_ARCHIVE_DEST_n ALTER SYSTEM switch_logfile_clause ANALYZE ALTER ROLE ALTER ROLLBACK SEGMENT ALTER ROLLBACK SEGMENT ALTER ROLLBACK SEGMENT ALTER ROLLBACK SEGMENT query the ROWID pseudocolumn DBMS_ROWID package; see Oracle8i Supplied PL/ SQL Packages Reference ALTER SESSION SET CURRENT_SCHEMA CREATE SYNONYM CREATE SYNONYM CREATE SYNONYM ANALYZE ALTER SEQUENCE cache_clause CREATE SEQUENCE ... ORDER ALTER SEQUENCE ... ORDER CREATE SEQUENCE See "CURRVAL and NEXTVAL" on page 2-56. CREATE SEQUENCE ... INCREMENT BY ALTER SEQUENCE ... INCREMENT BY
REFS role rollback segment
validate and update change authorization required bring online reduce in size storage characteristics, change take offline
rowid
examine extended, interpreting contents
schema schema object
change during the session reference without referencing its location reference without referencing its owner specify another name for validate structure of
sequence
cached sequence values, change number of consecutive order of values, guarantee create determine current value of increment value, set
maximum or minimum value, eliminate minimum or maximum value, set
ALTER SEQUENCE CREATE SEQUENCE ALTER SEQUENCE
About SQL Statements 6-17
Finding the Right SQL Statement
Database Object / Task
Operation
SQL Statement
preallocate values for faster access CREATE SEQUENCE ALTER SEQUENCE restart after a predefined limit CREATE SEQUENCE ... CYCLE ALTER SEQUENCE ... CYCLE starting value, set server processes session multi-threaded server, manage CPU time for, limit data blocks read, limit enable or disable parallel transactions in inactive period duration, limit private SGA space for, limit resource costs allowed, change restrict to privileged users terminate total elapsed time, limit total resources for, limit SGA shared pool flush data from shared pool flush CREATE SEQUENCE MTS_ parameters of ALTER SYSTEM CPU_PER_SESSION parameter LOGICAL_READS_PER_SESSION parameter ALTER SESSION IDLE_TIME parameter PRIVATE_SGA parameter ALTER RESOURCE COST ALTER SYSTEM restricted_session_clause ALTER SYSTEM kill_session_clause CONNECT_TIME parameter COMPOSITE_LIMIT parameter ALTER SYSTEM flush_shared_pool_clause ALTER SYSTEM flush_shared_pool_clause
snapshot. See "materialized view". sort operations standby database linguistic sequence, change activate recover statistics on a schema object, collect on a schema object, delete on scalar object attributes, collect subpartition add to a table or modify ALTER SESSION SET NLS_SORT ALTER DATABASE ACTIVATE STANDBY DATABASE ALTER DATABASE recover_clauses ANALYZE ANALYZE ANALYZE ALTER TABLE
6-18
SQL Reference
Finding the Right SQL Statement
Database Object / Task
Operation default attributes, change
SQL Statement ALTER TABLE modify_default_attributes_clause, modify_partition_clause ALTER TABLE logging_clause ALTER TABLE modify_subpartition_clause RESOURCE_LIMITS parameter of ALTER SYSTEM ALTER TABLE allocate_extent_clause ALTER TABLE physical_attributes_clause, modify_storage_clauses ALTER TABLE drop_column_clause ALTER TABLE parallel_clause ALTER TABLE logging_clause ALTER TABLE ANALYZE CREATE TABLE ALTER TABLE exchange_partition_clause CREATE TABLE ALTER TABLE ALTER TABLE deallocate_unused_clause CREATE TABLE CREATE TABLE CREATE TRIGGER CREATE TABLE ALTER TABLESPACE READ WRITE/ONLY ALTER TABLESPACE datafile/ tempfile_clauses
logging characteristics, change real attributes, change system resources table enable or disable allocate space for characteristics, change
column, drop from table degree of parallelism, change logging characteristics, change make read-only, read-write migrated or chained rows, identify organization, define partition, point to the contents of another table partitioning, specify rename unused space of, release heap or index organized include in a cluster replicate asynchronous, maintain storage characteristics of, set tablespace allow or disallow writing to datafiles, add or rename
About SQL Statements 6-19
Finding the Right SQL Statement
Database Object / Task
Operation logging characteristics, change minimum extent length, change reconstruct damaged reconstruct lost or damaged recover specified specifying for a table storage characteristics, change take online or offline user quota on, change assign to a user space quota for a user, allocate
SQL Statement ALTER TABLESPACE ALTER TABLESPACE ALTER DATABASE general_recovery_clause ALTER DATABASE CREATE DATAFILE ALTER DATABASE general_recovery_clause CREATE TABLE ALTER TABLESPACE ALTER TABLESPACE ALTER USER CREATE USER CREATE USER ALTER DATABASE TEMPFILE ALTER DATABASE TEMPFILE ALTER SESSION ALTER SESSION ALTER TABLE ALTER USER ALTER USER profile_clause ALTER USER FAILED_LOGIN_ATTEMPTS parameter SESSIONS_PER_USER parameter ALTER USER CREATE USER
tempfile
allow for automatic extension of resize
transaction
distributed, force commit of distributed, force rollback of
trigger user
enable or disable authentication, change database resources limits, change default roles, change failed attempts to log in, limit number of sessions, limit password, change resource limits, set
6-20
SQL Reference
Finding the Right SQL Statement
Database Object / Task
Operation restrict access to Oracle tablespace quota, allocate tablespaces, assign
SQL Statement ALTER SYSTEM restricted_session_clause CREATE USER CREATE USER
About SQL Statements 6-21
Finding the Right SQL Statement
6-22
SQL Reference
7
SQL Statements
A whole is that which has a beginning, a middle, and an end. Aristotle, Poetics This chapter describes, in alphabetical order, Oracle SQL statements and major clauses. The description of each statement or clause contains the following sections: Syntax shows the keywords and parameters that make up the statement. Caution: Not all keywords and parameters are valid in all circumstances. Be sure to refer to the "Keywords and Parameters" section of each statement and clause to learn about any restrictions on the syntax. Purpose Prerequisites describes the basic uses of the statement. lists privileges you must have and steps that you must take before using the statement. In addition to the prerequisites listed, most statements also require that the database be opened by your instance, unless otherwise noted. describes the purpose of each keyword and parameter. (The conventions for keywords and parameters used in this chapter are explained in the Preface of this reference.) Restrictions and usage notes also appear in this section. shows how to use various clauses and parameters of the statement.
Keywords and Parameters
Examples
SQL Statements 7-1
ALTER CLUSTER
7SQL Statements 7SQL Statements
ALTER CLUSTER
Syntax
schema ALTER CLUSTER . cluster
physical_attributes_clause K M SIZE integer parallel_clause ;
allocate_extent_clause deallocate_unused_clause
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
storage_clause: See "storage_clause" on page 7-605.
7-2 SQL Reference
ALTER CLUSTER
allocate_extent_clause::=
K M SIZE ( integer ' filename integer ' )
DATAFILE INSTANCE
ALLOCATE
EXTENT
deallocate_unused_clause::=
K M KEEP DEALLOCATE UNUSED integer
parallel_clause::=
NOPARALLEL integer PARALLEL
Purpose
To redefine storage and parallelism characteristics of a cluster. For information on creating a cluster, see "CREATE CLUSTER" on page 7-254. To remove tables from a cluster, see "DROP CLUSTER" on page 7-472 and "DROP TABLE" on page 7-501.
Note: You cannot use this statement to change the number or the
name of columns in the cluster key, and you cannot change the tablespace in which the cluster is stored.
SQL Statements 7-3
ALTER CLUSTER
Prerequisites
The cluster must be in your own schema or you must have ALTER ANY CLUSTER system privilege.
Keywords and Parameters
schema cluster is the schema containing the cluster. If you omit schema, Oracle assumes the cluster is in your own schema. is the name of the cluster to be altered.
physical_ changes the values of the PCTUSED, PCTFREE, INITRANS, and MAXTRANS parameters of the attributes_clause cluster. For a description of these parameters, see "CREATE CLUSTER" on page 7-254. storage_clause changes the storage characteristics for the cluster. See the "storage_clause" on page 7-605. Restriction: You cannot change the values of the storage parameters INITIAL and MINEXTENTS for a cluster. SIZE integer determines how many cluster keys will be stored in data blocks allocated to the cluster. For a description of the SIZE parameter, see "CREATE CLUSTER" on page 7-254. Restriction: You can change the SIZE parameter only for an indexed cluster, not for a hash cluster. allocate_extent_ clause explicitly allocates a new extent for the cluster. Restriction: You can allocate a new extent only for an indexed cluster, not for a hash cluster. SIZE specifies the size of the extent in bytes. Use K or M to specify the extent size in kilobytes or megabytes. When you explicitly allocate an extent with this clause, Oracle does not evaluate the cluster's storage parameters and determine a new size for the next extent to be allocated (as it does when you create a table). Therefore, specify SIZE if you do not want Oracle to use a default value. DATAFILE INSTANCE specifies one of the datafiles in the cluster's tablespace to contain the new extent. If you omit this parameter, Oracle chooses the datafile. 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 INSTANCE, the extent is available to all instances. Use this parameter only if you are using Oracle with the Parallel Server option in parallel mode.
7-4 SQL Reference
ALTER CLUSTER
deallocate_ unused_clause
explicitly deallocates unused space at the end of the cluster and makes the freed space available for other segments. Only unused space above the high water mark can be freed. KEEP specifies the number of bytes above the high water mark that the cluster will have after deallocation. If the number of remaining extents is less than MINEXTENTS, then MINEXTENTS is set to the current number of extents. If the initial extent becomes smaller than INITIAL, then INITIAL is set to the value of the current initial extent. If you omit KEEP, all unused space is freed.
For a more complete description of this clause, see "ALTER TABLE" on page 7-123. parallel_clause changes the default degree of parallelism for queries and DML on the cluster. See Also: The Notes to the parallel_clause of "CREATE TABLE" on page 4-381. NOPARALLEL PARALLEL specifies serial execution. This is the default. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances times the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution processes. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer. Restriction: If the tables in cluster contain any columns of LOB or user-defined object type, this statement as well as subsequent INSERT, UPDATE, or DELETE operations on cluster are executed serially without notification.
Examples
The following statement alters the CUSTOMER cluster in the schema SCOTT:
ALTER CLUSTER scott.customer SIZE 512 STORAGE (MAXEXTENTS 25);
Oracle 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. The following statement deallocates unused space from the CUSTOMER cluster, keeping 30 kilobytes of unused space for future use:
ALTER CLUSTER scott.customer DEALLOCATE UNUSED KEEP 30 K;
SQL Statements 7-5
ALTER DATABASE
ALTER DATABASE
Syntax
database ALTER DATABASE STANDBY DATABASE CLONE MOUNT CONVERT READ WRITE RESETLOGS NORESETLOGS READ OPEN ACTIVATE STANDBY DATABASE ONLY
recover_clauses RENAME GLOBAL_NAME TO , RENAME RESET FILE ' filename ' TO ' database . domain , filename ' ;
COMPATIBILITY PUBLIC
ENABLE DISABLE CHARACTER NATIONAL THREAD SET integer
THREAD
integer
character_set SET character_set
CHARACTER
datafile/tempfile_clauses logfile_clauses controlfile_clauses
7-6 SQL Reference
ALTER DATABASE
recover_clauses::=
general_recovery_clause RECOVER managed_recovery_clause parallel_clause ;
general_recovery_clause::=
AUTOMATIC FROM ' location '
CANCEL UNTIL TIME CHANGE STANDBY DATABASE , TABLESPACE STANDBY DATAFILE , TABLESPACE tablespace , DATAFILE LOGFILE ' ' filename filename DEFAULT CONTINUE CANCEL ' ' ' , filename ' tablespace UNTIL CONSISTENT WITH CONTROLFILE USING BACKUP date integer CONTROLFILE
SQL Statements 7-7
ALTER DATABASE
managed_recovery_clause::=
TIMEOUT MANAGED STANDBY DATABASE CANCEL integer IMMEDIATE
datafile/tempfile_clauses::=
AS CREATE DATAFILE ' filename ' ONLINE DROP OFFLINE
filespec
K DATAFILE ' filename ' M RESIZE integer
autoextend_clause END BACKUP K M RESIZE integer
autoextend_clause TEMPFILE , filename , DROP ONLINE OFFLINE
filespec: See "filespec" on page 7-516.
7-8 SQL Reference
ALTER DATABASE
controlfile_clauses::=
REUSE CREATE STANDBY CONTROLFILE AS ' filename ' REUSE ' BACKUP CONTROLFILE TO TRACE filename ' RESETLOGS NORESETLOGS
logfile_clauses::=
ARCHIVELOG NOARCHIVELOG , THREAD ADD LOGFILE , REUSE ADD LOGFILE MEMBER , DROP LOGFILE logfile_descriptor , DROP LOGFILE MEMBER ' filename ' , LOGFILE logfile_descriptor UNRECOVERABLE DATAFILE ' filename ' TO , logfile_descriptor integer GROUP integer filespec
UNARCHIVED CLEAR
SQL Statements 7-9
ALTER DATABASE
logfile_descriptor::=
GROUP integer , ( ' ' filename filename ' ' )
autoextend_clause::=
OFF K AUTOEXTEND NEXT ON integer M maxsize_clause
maxsize_clause::=
UNLIMITED MAXSIZE integer K M
parallel_clause::=
NOPARALLEL integer PARALLEL
Purpose
To modify, maintain, or recover an existing database.
7-10
SQL Reference
ALTER DATABASE
See Also:
s
Oracle8i Administrator's Guide for more information on using the ALTER DATABASE statement for database maintenance. Oracle8i Administrator's Guide, Oracle8i Recovery Manager User's Guide and Reference, and Oracle8i Backup and Recovery Guide for examples of performing media recovery. "CREATE DATABASE" on page 7-267 for information on creating a database.
s
s
Prerequisites
You must have ALTER DATABASE system privilege. To specify the RECOVER clause, you must also have the OSDBA role enabled.
Keywords and Parameters
database identifies the database to be altered. The database name can contain only ASCII characters. If you omit database, Oracle alters the database identified by the value of the initialization parameter DB_NAME. You can alter only the database whose control files are specified by the initialization parameter CONTROL_FILES. The database identifier is not related to the Net8 database specification.
You can use the following clauses only when the database is not mounted by your instance: MOUNT mounts the database. STANDBY DATABASE CLONE DATABASE CONVERT mounts the standby database. See Also: Oracle8i Standby Database Concepts and Administration. mounts the clone database. See Also: Oracle8i Backup and Recovery Guide.
completes the conversion of the Oracle7 data dictionary. After you use this clause, the Oracle7 data dictionary no longer exists in the Oracle database. Use this clause only when you are migrating to Oracle8i. See Also: Oracle8i Migration.
ACTIVATE STANDBY DATABASE OPEN
changes the state of a standby database to an active database. See Also: Oracle8i Standby Database Concepts and Administration. opens the database, making it available for normal use. You must mount the database before you can open it. You must activate a standby database before you can open it.
SQL Statements 7-11
ALTER DATABASE
READ ONLY
restricts users to read-only transactions, preventing them from generating redo logs. You can use this clause to make a standby database available for queries even while archive logs are being copied from the primary database site. Restrictions:
s
You cannot open a database READ ONLY if it is currently opened READ WRITE by another instance. You cannot open a database READ ONLY if it requires recovery. You cannot take tablespaces offline while the database is open READ ONLY. However, you can take datafiles offline and online, and you can recover offline datafiles and tablespaces while the database is open READ ONLY.
s s
READ WRITE RESETLOGS
opens the database in read-write mode, allowing users to generate redo logs. This is the default. resets the current log sequence number to 1 and discards any redo information that was not applied during recovery, ensuring that it will never be applied. This effectively discards all changes that are in the redo log, but not in the database. You must specify RESETLOGS to open the database after performing media recovery with an incomplete recovery using the RECOVER clause or with a backup control file. After opening the database with this clause, you should perform a complete database backup.
NORESETLOGS
leaves the log sequence number and redo log files in their current state.
Restriction: You can specify RESETLOGS and NORESETLOGS only after performing incomplete media recovery or complete media recovery with a backup control file. In any other case, Oracle uses the NORESETLOGS automatically. You can use any of the following clauses when your instance has the database mounted, open or closed, and the files involved are not in use: general_recovery_ clause lets you design media recovery for the database or standby database, or for specified tablespaces or files. See Also: Oracle8i Backup and Recovery Guide for more information on media recovery. Note: If you do not have special media requirements, Oracle Corporation recommends that you use the SQL*Plus RECOVER statement. See Also: SQL*Plus User's Guide and Reference.
7-12
SQL Reference
ALTER DATABASE
Restrictions:
s s s
You can recover the entire database only when the database is closed. Your instance must have the database mounted in exclusive mode. You can recover tablespaces or datafiles when the database is open or closed, provided that the tablespaces or datafiles to be recovered are offline. You cannot perform media recovery if you are connected to Oracle through the multithreaded server architecture.
s
AUTOMATIC
automatically generates the name of the next archived redo log file needed to continue the recovery operation. If the LOG_ARCHIVE_DEST_n parameters are defined, Oracle scans those that are valid and enabled for the first local destination. It uses that destination in conjunction with LOG_ARCHIVE_FORMAT to generate the target redo log filename. If the LOG_ARCHIVE_DEST_n parameters are not defined, Oracle uses the value of the LOG_ ARCHIVE_DEST parameter instead. If the resulting file is found, Oracle applies the redo contained in that file. If the file is not found, Oracle prompts you for a filename, displaying the generated filename as a suggestion. If you specify neither AUTOMATIC nor LOGFILE, Oracle prompts you for a filename, displaying the generated filename as a suggestion. You can then accept the generated filename or replace it with a fully qualified filename. If you know the archived filename differs from what Oracle would generate, you can save time by using the LOGFILE clause.
FROM 'location'
specifies the location from which the archived redo log file group is read. The value of location 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 or LOG_ ARCHIVE_DEST_1. recovers the standby database using the control file and archived redo log files copied from the primary database. The standby database must be mounted but not open. recovers the entire database. This is the default. You can use this clause only when the database is closed. Note: This clause recovers only online datafiles. UNTIL specifies the duration of the recovery operation.
s
STANDBY DATABASE DATABASE
CANCEL performs cancel-based recovery. This clause recovers the database until you issue the ALTER DATABASE RECOVER statement with the RECOVER CANCEL clause. 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'.
s
SQL Statements 7-13
ALTER DATABASE
s
CHANGE performs change-based recovery. This parameter recovers the database to a transaction-consistent state immediately before the system change number (SCN) specified by integer.
USING BACKUP CONTROLFILE TABLESPACE DATAFILE STANDBY TABLESPACE | DATAFILE
specifies that a backup control file is being used instead of the current control file.
recovers only the specified tablespaces. You can use this clause if the database is open or closed, provided the tablespaces to be recovered are offline. recovers the specified datafiles. You can use this clause when the database is open or closed, provided the datafiles to be recovered are offline. reconstructs a lost or damaged datafile or tablespace in the standby database using archived redo log files copied from the primary database and a control file. UNTIL [CONSISTENT WITH] CONTROLFILE specifies that the recovery of an old standby datafile or tablespace uses the current standby database control file. However, any redo in advance of the standby controlfile will not be applied. The keywords CONSISTENT WITH are optional and are provided for semantic clarity.
LOGFILE CONTINUE CONTINUE DEFAULT CANCEL managed_ recovery_clause
continues media recovery by applying the specified redo log file. continues multi-instance recovery after it has been interrupted to disable a thread. continues recovery using the redo log file that Oracle would automatically generate if no other logfile were specified. This clause is equivalent to specifying AUTOMATIC, except that Oracle does not prompt for a filename. terminates cancel-based recovery. specifies automated standby recovery mode. This mode assumes that the automated standby database is an active component of an overall standby database architecture. A primary database actively archives its redo log files to the standby site. As these archived redo logs arrive at the standby site, they become available for use by a managed standby recovery operation. Automated standby recovery is restricted to media recovery. See Also: Oracle8i Backup and Recovery Guide for more information on the parameters of this clause. Restrictions: The same restrictions apply as are listed under general_recovery_clause.
TIMEOUT integer
specifies in minutes the wait period of the managed recovery operation. The recovery process waits for integer minutes for a requested archived log redo to be available for writing to the automated standby database. If the redo log file does not become available within that time, the recovery process terminates with an error message. You can then issue the statement again to return to automated standby recovery mode. If you do not specify this clause, the database remains in automated standby recovery mode until you reissue the statement with the RECOVER CANCEL clause or until instance shutdown or failure.
7-14
SQL Reference
ALTER DATABASE
CANCEL CANCEL IMMEDIATE
terminates the managed recovery operation after applying all the redo in the current archived redo file. terminates the managed recovery operation after applying all the redo in the current archived redo file or after the next redo log file read, whichever comes first. Restriction: This clause cannot be issued from the same session that issued the RECOVER MANAGED STANDBY DATABASE statement.
parallel_clause
specifies whether the recovery of media will be parallelized. For additional information, see the Notes to the parallel_clause of "CREATE TABLE" on page 4-381. NOPARALLEL PARALLEL specifies serial execution. This is the default. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances times the value of the PARALLEL_THREADS_PER_CPU initialization parameter. specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution processes. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer.
PARALLEL integer
RENAME GLOBAL_ changes the global name of the database. The database is the new database name and can NAME be as long as eight bytes. The optional domain specifies where the database is effectively located in the network hierarchy. See Also: Oracle8i Distributed Database Systems for more information on global names. Note: 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. RENAME FILE renames datafiles, tempfiles, or redo log file members. This clause renames only files in the control file. It does not actually rename them on your operating system. You must specify each filename using the conventions for filenames on your operating system before specifying this clause. marks the database to be reset to an earlier version of Oracle when the database is next restarted. Note: RESET COMPATIBILITY works only if you have successfully disabled Oracle features that affect backward compatibility. See Also: Oracle8i Migration for more information on downgrading to an earlier version of Oracle. You can use the following clauses only when your instance has the database open: ENABLE THREAD in a parallel server, 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.
RESET COMPATIBILITY
SQL Statements 7-15
ALTER DATABASE
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 PUBLIC, the thread is available only to the instance that explicitly requests it with the initialization parameter THREAD.
DISABLE THREAD disables the specified thread, making it unavailable to all instances. You cannot disable a thread if an instance using it has the database mounted. See Also: Oracle8i Designing and Tuning for Performance for more information on enabling and disabling threads. CHARACTER SET NATIONAL CHARACTER SET CHARACTER SET changes the character set the database uses to store data. NATIONAL CHARACTER SET changes the national character set used to store data in columns specifically defined as NCHAR, NCLOB, or NVARCHAR2. Specify character_set without quotation marks. WARNING: You cannot roll back an ALTER DATABASE CHARACTER SET or ALTER DATABASE NATIONAL CHARACTER SET statement. Therefore, you should perform a full backup before issuing either of these statements. Restrictions:
s
You must have SYSDBA system privilege, and you must start up the database in restricted mode (for example, with the SQL*Plus STARTUP RESTRICT command). The current character set must be a strict subset of the character set to which you change. That is, each character represented by a codepoint value in the source character set must be represented by the same codepoint value in the target character set. For a list of valid character sets, see Oracle8i National Language Support Guide.
s
datafile/tempfile_ clauses
let you modify datafiles and tempfiles.
You can use any of the following clauses when your instance has the database mounted, open or closed, and the files involved are not in use: CREATE DATAFILE creates a new empty datafile in place of an old one. You can use this clause to re-create a datafile 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 datafile. If you omit the AS clause, Oracle creates the new file with the name and size as the file specified by 'filename'. During recovery, all archived redo logs written to since the original datafile was created must be applied to the new, empty version of the lost datafile. 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. Restriction: You cannot create a new file based on the first datafile of the SYSTEM tablespace. DATAFILE affects your database files as follows:
7-16
SQL Reference
ALTER DATABASE
ONLINE OFFLINE
brings the datafile online. takes the datafile offline. If the database is open, you must perform media recovery on the datafile before bringing it back online, because a checkpoint is not performed on the datafile before it is taken offline. DROP takes a datafile offline when the database is in NOARCHIVELOG mode.
RESIZE
attempts to increase or decrease the size of the datafile to the specified absolute size in bytes. Use K or M to specify this size in kilobytes or megabytes. There is no default, so you must specify a size. If sufficient disk space is not available for the increased size, or if the file contains data beyond the specified decreased size, Oracle returns an error.
autoextend_ clause
enables or disables the automatic extension of a datafile. If you do not specify this clause, datafiles are not automatically extended. OFF disables autoextend if it is turned on. NEXT and MAXSIZE are set to zero. Values for NEXT and MAXSIZE must be respecified in further ALTER DATABASE AUTOEXTEND statements. ON enables autoextend. NEXT specifies in bytes the size of the next increment of disk space to be automatically allocated to the datafile when more extents are required. Use K or M to specify this size in kilobytes or megabytes. The default is one data block. MAXSIZE specifies the maximum disk space allowed for automatic extension of the datafile. UNLIMITED sets no limit on allocating disk space to the datafile.
END BACKUP
avoids media recovery on database startup after an online tablespace backup was interrupted by a system failure or instance failure or SHUTDOWN ABORT.
WARNING: Do not use ALTER TABLESPACE ... END BACKUP if you have restored any of the files affected from a backup. Media recovery is fully described in Oracle8i Backup and Recovery Guide. TEMPFILE Lets you resize your temporary datafile or specify the autoextend_clause, with the same effect as with a permanent datafile. Restriction: You cannot specify TEMPFILE unless the database is open. DROP logfile_clauses drops tempfile from the database. The tablespace remains.
lets you add, drop, or modify log files.
SQL Statements 7-17
ALTER DATABASE
ARCHIVELOG
specifies that the contents of a redo log file group must be archived before the group can be reused. This mode prepares for the possibility of media recovery. Use this clause only after shutting down your instance normally or immediately with no errors and then restarting it, mounting the database in parallel server disabled mode. specifies that 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.
NOARCHIVELOG
Use the ARCHIVELOG clause and NOARCHIVELOG clause only if your instance has the database mounted in parallel server disabled mode, but not open. ADD LOGFILE adds one or more redo log file groups to the specified thread, making them available to the instance assigned the thread. THREAD integer is applicable only if you are using Oracle with the Parallel Server option in parallel mode. integer is the thread number. The number of threads you can create is limited by the value of the MAXINSTANCES parameter specified in the CREATE DATABASE statement. If you omit THREAD, the redo log file group is added to the thread assigned to your instance. GROUP integer 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 view V$LOG. Each filespec specifies a redo log file group containing one or more members, or copies. See the syntax description of filespec in "filespec" on page 7-516.
filespec
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 REUSE. 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 integer list of filenames Specify the value of the GROUP parameter that identifies the redo log file group. List all members of the redo log file group. You must fully specify each filename according to the conventions of your operating system.
7-18
SQL Reference
ALTER DATABASE
DROP LOGFILE
drops all members of a redo log file group. Specify a redo log file group as indicated for the ADD LOGFILE MEMBER clause.
s
To drop the current log file group, you must first issue an ALTER SYSTEM SWITCH LOGFILE statement. See "ALTER SYSTEM" on page 7-102. You cannot drop a redo log file group if it needs archiving. You cannot drop a redo log file group if doing so would cause the redo thread to contain less than two redo log file groups.
s s
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.
s
To drop a log file in the current log, you must first issue an ALTER SYSTEM SWITCH LOGFILE statement. See "ALTER SYSTEM" on page 7-102. You cannot use this clause to drop all members of a redo log file group that contains valid data. To perform this operation, use the DROP LOGFILE clause.
s
CLEAR LOGFILE
reinitializes an online redo log, optionally without archiving the redo log. CLEAR LOGFILE is similar to adding and dropping a redo log, except that the statement may be issued even if there are only two logs for the thread and also may be issued for the current redo log of a closed thread. UNARCHIVED You must specify UNARCHIVED if you want to reuse a redo log that was not archived. WARNING: Specifying UNARCHIVED makes backups unusable if the redo log is needed for recovery. Do not use CLEAR LOGFILE to clear a log needed for media recovery. If it is necessary to clear a log containing redo after the database checkpoint, you must first perform incomplete media recovery. The current redo log of an open thread can be cleared. The current log of a closed thread can be cleared by switching logs in the closed thread. If the CLEAR LOGFILE statement is interrupted by a system or instance failure, then the database may hang. If this occurs, reissue the statement after the database is restarted. If the failure occurred because of I/O errors accessing one member of a log group, then that member can be dropped and other members added. UNRECOVERYou must specify UNRECOVERABLE DATAFILE if you have taken the ABLE DATAFILE datafile offline with the database in ARCHIVELOG mode (that is, you specified ALTER DATABSE ... DATAFILE OFFLINE without the DROP keyword), and if the unarchived log to be cleared is needed to recover the datafile before bringing it back online. In this case, you must drop the datafile and the entire tablespace once the CLEAR LOGFILE statement completes.
controlfile_clauses
SQL Statements 7-19
ALTER DATABASE
CREATE STANDBY CONTROLFILE
creates a control file to be used to maintain a standby database. If the file already exists, you must specify REUSE. See Also: Oracle8i Standby Database Concepts and Administration.
BACKUP CONTROLFILE
backs up the current control file. TO 'filename' specifies 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 REUSE. writes SQL statements to the database's trace file rather than making a physical backup of the control file. The SQL statements can start up the database, re-create the control file, and recover and open the database appropriately, based on the created control file. You can copy the statements from the trace file into a script file, edit the statements as necessary, and use the database if all copies of the control file are lost (or to change the size of the control file).
s
TO TRACE
RESETLOGS specifies that the SQL statement written to the trace file for starting the database is ALTER DATABASE OPEN RESETLOGS. NORESETLOGS specifies that the SQL statement written to the trace file for starting the database is ALTER DATABASE OPEN NORESETLOGS.
s
Examples
The first statement below opens the database in read-only mode. The second statement returns the database to readwrite mode and clears the online redo logs:
READ ONLY / READ WRITE Example
ALTER DATABASE OPEN READ ONLY; ALTER DATABASE OPEN READ WRITE RESETLOGS;
The following statement performs tablespace recovery using parallel recovery processes:
PARALLEL Example
ALTER DATABASE RECOVER TABLESPACE binky PARALLEL;
Redo Log File Group Example The following statement adds a redo log file group with two members and identifies it with a GROUP parameter value of 3:
7-20
SQL Reference
ALTER DATABASE
ALTER DATABASE stocks ADD LOGFILE GROUP 3 ('diska:log3.log' , 'diskb:log3.log') SIZE 50K;
Redo Log File Group Member Example The following 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;
Dropping a Log File Member The following statement drops the redo log file
member added in the previous example:
ALTER DATABASE stocks DROP LOGFILE MEMBER 'diskc:log3.log';
Renaming a Log File Member The following statement renames a redo log file
member:
ALTER DATABASE stocks RENAME FILE 'diskb:log3.log' TO 'diskd:log3.log';
The above statement only changes the member of the redo log group from one file to another. The 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.
Dropping All Log File Group Members The following statement drops all
members of the redo log file group 3:
ALTER DATABASE stocks DROP LOGFILE GROUP 3;
Adding a Redo Log File Group The following statement adds a redo log file group
containing three members to thread 5 (in an Oracle Parallel Server environment) 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' );
SQL Statements 7-21
ALTER DATABASE
Disabling a Parallel Server Thread The following statement disables thread 5 in a
parallel server:
ALTER DATABASE stocks DISABLE THREAD 5;
Enabling a Parallel Server Thread The following statement enables thread 5 in a parallel server, making it available to any Oracle instance that does not explicitly request a specific thread:
ALTER DATABASE stocks ENABLE PUBLIC THREAD 5;
Creating a New Datafile The following statement creates a new datafile
'DISK2:DB1.DAT' based on the file 'DISK1:DB1.DAT':
ALTER DATABASE CREATE DATAFILE 'disk1:db1.dat' AS 'disk2:db1.dat';
Changing the Global Database Name The following 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;
Character Set Example The following statements change the database character set and national character set to the WE8ISO8859P1 character set:
ALTER DATABASE db1 CHARACTER SET WE8ISO8859P1; ALTER DATABASE db1 NATIONAL CHARACTER SET WE8ISO8859P1;
The database name is optional, and the character set name is specified without quotation marks.
Resizing a Datafile The following statement attempts to change the size of datafile
'DISK1:DB1.DAT':
ALTER DATABASE DATAFILE 'disk1:db1.dat' RESIZE 10 M;
Clearing a Log File
The following statement clears a log file:
ALTER DATABASE CLEAR LOGFILE 'disk3:log.dbf';
7-22
SQL Reference
ALTER DATABASE
The following statement performs complete recovery of the entire database, letting Oracle generate the name of the next archived redo log file needed:
Database Recovery Examples
ALTER DATABASE RECOVER AUTOMATIC DATABASE;
The following statement explicitly names a redo log file for Oracle to apply:
ALTER DATABASE RECOVER LOGFILE 'diska:arch0006.arc';
The following statement performs time-based recovery of the database:
ALTER DATABASE RECOVER AUTOMATIC UNTIL TIME '1998-10-27:14:00:00';
Oracle recovers the database until 2:00 pm on October 27, 1998. The following statement recovers the tablespace USER5:
ALTER DATABASE RECOVER TABLESPACE user5;
The following statement recovers the standby datafile /FINANCE/STBS_21.f, using the corresponding datafile in the original standby database, plus all relevant archived logs and the current standby database control file:
ALTER DATABASE RECOVER STANDBY DATAFILE '/finance/stbs_21.f' UNTIL CONTROLFILE;
The following statement recovers the standby database in automated standby recovery mode:
Managed Standby Database Examples
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE;
The following statement puts the database in automated standby recovery mode. The managed recovery process will wait up to 60 minutes for the next archive log:
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE TIMEOUT 60;
If each subsequent log arrives within 60 minutes of the last log, recovery continues indefinitely or until manually terminated.
SQL Statements 7-23
ALTER DATABASE
The following statement terminates the managed recovery operation:
ALTER DATABASE RECOVER MANAGED STANDBY DATABASE CANCEL IMMEDIATE;
The managed recovery operation terminates before the next group of redo is read from the current redo log file. Media recovery ends in the "middle" of applying redo from the current redo log file.
7-24
SQL Reference
ALTER DIMENSION
ALTER DIMENSION
Syntax
schema ALTER DIMENSION . dimension
level_clause ADD hierarchy_clause attribute_clause RESTRICT CASCADE LEVEL DROP level hierarchy level ;
HIERARCHY ATTRIBUTE
COMPILE
level_clause::=
level_table LEVEL level IS ( level_table . . level_column , level_column )
hierarchy_clause::=
join_clause HIERARCHY hierarchy ( child_level CHILD OF parent_level )
SQL Statements 7-25
ALTER DIMENSION
join_clause::=
child_key_column JOIN KEY ( , child_key_column ) REFERENCES parent_level
attribute_clause::=
dependent_column ATTRIBUTE level DETERMINES ( , dependent_column )
Purpose
To change the hierarchical relationships or dimension attributes of a dimension.
See Also: "CREATE DIMENSION" on page 7-277 for more
information on dimensions,
Prerequisites
The dimension must be in your schema or you must have the ALTER ANY DIMENSION system privilege to use this statement. A dimension is always altered under the rights of the owner.
Keywords and Parameters
The following keywords and parameters have meaning unique to ALTER DIMENSION. The remaining keywords and parameters have the same functionality that they have in the CREATE DIMENSION statement. See "CREATE DIMENSION" on page 7-277.
schema dimension is the schema of the dimension you want to modify. If you do not specify schema, Oracle assumes the dimension is in your own schema. is the name of the dimension. This dimension must already exist.
7-26
SQL Reference
ALTER DIMENSION
ADD
lets you add a level, hierarchy, or attribute to the dimension. Adding one of these elements does not invalidate any existing materialized view. Oracle processes ADD LEVEL clauses prior to any other ADD clauses.
DROP
lets you drop a level, hierarchy, or attribute from the dimension. Any level, hierarchy, or attribute you specify must already exist. Restriction: If any attributes or hierarchies reference a level, you cannot drop the level until you either drop all the referencing attributes and hierarchies or specify CASCADE. CASCADE RESTRICT causes Oracle to drop any attributes or hierarchies that reference the level, along with the level itself. prevents Oracle from dropping a level that is referenced by any attributes or hierarchies. This is the default.
COMPILE
explicitly recompiles an invalidated dimension. Oracle automatically compiles a dimension when you issue an ADD clause or DROP clause. However, if you alter an object referenced by the dimension (for example, if you drop and then re-create a table referenced in the dimension), the dimension will be invalidated, and you must recompile it explicitly.
Examples
This example modifies the TIME dimension:
ALTER DIMENSION time DROP HIERARCHY week_month; ALTER DIMENSION time DROP ATTRIBUTE cur_date; ALTER DIMENSION time ADD LEVEL day IS time_tab.t_day ADD ATTRIBUTE day DETERMINES t_holiday;
SQL Statements 7-27
ALTER FUNCTION
ALTER FUNCTION
Syntax
schema ALTER FUNCTION . function COMPILE DEBUG ;
Purpose
To recompile an invalid standalone stored function. Explicit recompilation eliminates the need for implicit run-time recompilation and prevents associated run-time compilation errors and performance overhead. The ALTER FUNCTION statement is similar to "ALTER PROCEDURE" on page 2-67. For information on how Oracle recompiles functions and procedures, see Oracle8i Concepts.
Note: This statement does not change the declaration or definition
of an existing function. To redeclare or redefine a function, use the CREATE FUNCTION statement with the OR REPLACE clause; see "CREATE FUNCTION" on page 7-284.
Prerequisites
The function must be in your own schema or you must have ALTER ANY PROCEDURE system privilege.
Keywords and Parameters
schema function COMPILE is the schema containing the function. If you omit schema, Oracle assumes the function is in your own schema. is the name of the function to be recompiled. causes Oracle to recompile the function. The COMPILE keyword is required. If Oracle does not compile the function successfully, you can see the associated compiler error messages with the SQL*Plus command SHOW ERRORS. instructs the PL/SQL compiler to generate and store the code for use by the PL/SQL debugger.
DEBUG
7-28
SQL Reference
ALTER FUNCTION
Example
To explicitly recompile the function GET_BAL owned by the user MERRIWEATHER, issue the following 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 run time. If recompiling GET_BAL results in compilation errors, Oracle returns an error, 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 run time.
SQL Statements 7-29
ALTER INDEX
ALTER INDEX
Syntax
schema ALTER INDEX . index
deallocate_unused_clause allocate_extent_clause parallel_clause physical_attributes_clause LOGGING NOLOGGING rebuild_clause PARAMETERS ENABLE DISABLE UNUSABLE RENAME COALESCE partitioning_clauses TO new_index_name ( ' alter_parameters ' ) ;
deallocate_unused_clause::=
K M KEEP DEALLOCATE UNUSED integer
7-30
SQL Reference
ALTER INDEX
allocate_extent_clause::=
K M SIZE ( integer ' filename integer ' )
DATAFILE INSTANCE
ALLOCATE
EXTENT
parallel_clause::=
NOPARALLEL integer PARALLEL
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
storage_clause: See "storage_clause" on page 7-605.
SQL Statements 7-31
ALTER INDEX
rebuild_clause::=
parallel_clause TABLESPACE ONLINE COMPUTE STATISTICS tablespace
physical_attributes_clause compression_clause PARTITION SUBPARTITION REVERSE NOREVERSE PARAMETERS ( ' rebuild_parameters ' ) partition subpartition LOGGING NOLOGGING
REBUILD
compression_clause::=
integer COMPRESS NOCOMPRESS
partitioning_clauses::=
modify_default_attributes_clause modify_partition_clause rename_partition/subpartition_clause drop_partition_clause split_partition_clause modify_subpartition_clause
7-32
SQL Reference
ALTER INDEX
modify_default_attributes_clause::=
FOR MODIFY DEFAULT ATTRIBUTES PARTITION partition
physical_attributes_clause tablespace TABLESPACE DEFAULT LOGGING NOLOGGING
modify_partition_clause::=
physical_attributes_clause LOGGING NOLOGGING deallocate_unused_clause MODIFY PARTITION partition allocate_extent_clause COALESCE UNUSABLE
rename_partition/ subpartition_clause::=
PARTITION RENAME SUBPARTITION current_name TO new_name
drop_partition_clause::=
DROP PARTITION partition_name
SQL Statements 7-33
ALTER INDEX
split_partition_clause::=
SPLIT INTO PARTITION ( partition_name_old , AT ( value_list ) ) parallel_clause
partition_description
partition_description
partition_description::=
segment_attributes_clause compression_clause partition PARTITION
modify_subpartition_clause::=
UNUSABLE MODIFY SUBPARTITION subpartition allocate_extent_clause deallocate_unused_clause
Purpose
To change or rebuild an existing index. For information on creating an index, see "CREATE INDEX" on page 7-291.
Prerequisites
The index must be in your own schema or you must have ALTER ANY INDEX system privilege. Schema object privileges are granted on the parent index, not on individual index partitions or subpartitions. You must have tablespace quota to modify, rebuild, or split an index partition or to modify or rebuild an index subpartition.
7-34
SQL Reference
ALTER INDEX
Keywords and Parameters
schema index is the schema containing the index. If you omit schema, Oracle assumes the index is in your own schema. is the name of the index to be altered. Restrictions:
s
If index is a domain index, you can specify only the PARAMETERS clause, the RENAME clause, or the rebuild_clause (with or without the PARAMETERS clause). No other clauses are valid. You cannot alter or rename a domain index that is marked LOADING or FAILED. If an index is marked FAILED, the only clause you can specify is REBUILD. For information on the LOADING and FAILED states of domain indexes, see Oracle8i Data Cartridge Developer's Guide.
s
deallocate_unused_ clause
explicitly deallocates unused space at the end of the index and makes the freed space available for other segments in the tablespace. Only unused space above the high water mark can be freed. If index is range-partitioned or hash-partitioned, Oracle deallocates unused space from each index partition. If index is a local index on a composite-partitioned table, Oracle deallocates unused space from each index subpartition. Restrictions:
s s
You cannot specify this clause for an index on a temporary table. You cannot specify this clause and also specify the rebuild_clause.
See Also: "ALTER TABLE" on page 7-123 for more information on this clause. KEEP specifies the number of bytes above the high water mark that the index will have after deallocation. If the number of remaining extents are less than MINEXTENTS, then MINEXTENTS is set to the current number of extents. If the initial extent becomes smaller than INITIAL, then INITIAL is set to the value of the current initial extent. If you omit KEEP, all unused space is freed.
See Also: "ALTER TABLE" on page 7-123 for a complete description of this clause. allocate_extent_ clause explicitly allocates a new extent for the index. For a local index on a hash-partitioned table, Oracle allocates a new extent for each partition of the index. Restriction: You cannot specify this clause for an index on a temporary table or for a range-partitioned or composite-partitioned index. SIZE specifies the size of the extent in bytes. Use K or M to specify the extent size in kilobytes or megabytes. If you omit SIZE, Oracle determines the size based on the values of the index's storage parameters.
SQL Statements 7-35
ALTER INDEX
DATAFILE INSTANCE
specifies one of the datafiles in the index's tablespace to contain the new extent. If you omit DATAFILE, Oracle chooses the datafile. 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. Use this parameter only if you are using Oracle with the Parallel Server option in parallel mode.
Explicitly allocating an extent with this clause does not change the values of the NEXT and PCTINCREASE storage parameters, so does not affect the size of the next extent to be allocated. parallel_clause changes the default degree of parallelism for queries and DML on the index. For additional information, see the Notes to the parallel_clause of "CREATE TABLE" on page 4-381. NOPARALLEL PARALLEL specifies serial execution. This is the default. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances multiplied by the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution processes. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer. Restriction: You cannot specify this clause for an index on a temporary table. physical_attributes_ lets you change the values of parameters for a nonpartitioned index, all partitions and subpartitions of a partitioned index, a specified partition, or all subpartitions of a specified clause partition. See these parameters in "CREATE TABLE" on page 4-381. Restrictions:
s s s
You cannot specify this clause for an index on a temporary table. You cannot specify the PCTUSED parameter when altering an index. You cannot change the value of the PCTFREE parameter for the index as a whole (ALTER INDEX) or for a partition (ALTER INDEX ... MODIFY PARTITION). You can specify PCTFREE in all other forms of the ALTER INDEX statement. changes the storage parameters for a nonpartitioned index, index partition, or all partitions of a partitioned index, or default values of these parameters for a partitioned index. See the "storage_clause" on page 7-605.
storage_clause
LOGGING| NOLOGGING
LOGGING|NOLOGGING specifies that subsequent Direct Loader (SQL*Loader) and directload INSERT operations against a nonpartitioned index, a range or hash index partition, or all partitions or subpartitions of a composite-partitioned index will be logged (LOGGING) or not logged (NOLOGGING) in the redo log file.
7-36
SQL Reference
ALTER INDEX
In NOLOGGING mode, data is modified with minimal logging (to mark new extents invalid and to record dictionary changes). When applied during media recovery, the extent invalidation records mark a range of blocks as logically corrupt, because the redo data is not logged. Therefore, if you cannot afford to lose this index, you must take a backup after the operation in NOLOGGING mode. If the database is run in ARCHIVELOG mode, media recovery from a backup taken before an operation in LOGGING mode will re-create the index. However, media recovery from a backup taken before an operation in NOLOGGING mode will not re-create the index. An index segment can have logging attributes different from those of the base table and different from those of other index segments for the same base table. Restriction: You cannot specify this clause for an index on a temporary table. See Also: Oracle8i Concepts and the Oracle8i Parallel Server Concepts for more information about LOGGING and parallel DML. RECOVERABLE| UNRECOVERABLE These keywords are deprecated and have been replaced with LOGGING and NOLOGGING, respectively. Although RECOVERABLE and UNRECOVERABLE are supported for backward compatibility, Oracle Corporation strongly recommends that you use the LOGGING and NOLOGGING keywords. RECOVERABLE is not a valid keyword for creating partitioned tables or LOB storage characteristics. UNRECOVERABLE is not a valid keyword for creating partitioned or indexorganized tables. Also, it can be specified only with the AS subquery clause of CREATE INDEX. rebuild_clause re-creates an existing index or one of its partitions or subpartitions. For a function-based index, this clause also enables the index. If the function on which the index is based does not exist, the rebuild statement will fail. Restrictions:
s s
You cannot rebuild an index on a temporary table. You cannot rebuild an entire partitioned index. You must rebuild each partition or subpartition, as described below. You cannot also specify the deallocate_unused_clause in this statement. You cannot change the value of the PCTFREE parameter for the index as a whole (ALTER INDEX) or for a partition (ALTER INDEX ... MODIFY PARTITION). You can specify PCTFREE in all other forms of the ALTER INDEX statement.
s s
SQL Statements 7-37
ALTER INDEX
PARTITION partition
rebuilds one partition of an index. You can also use this clause to move an index partition to another tablespace or to change a create-time physical attribute. Restriction: You cannot specify this clause for a local index on a composite-partitioned table. Instead, use the REBUILD SUBPARTITION clause. See Also: Oracle8i Administrator's Guide for more information about partition maintenance operations.
SUBPARTITION subpartition
rebuilds one subpartition of an index. You can also use this clause to move an index subpartition to another tablespace. If you do not specify TABLESPACE, the subpartition is rebuilt in the same tablespace. Restrictions: The only parameters you can specify for a subpartition are TABLESPACE and the parallel_clause.
REVERSE | NOREVERSE
specifies whether the bytes of the index block are stored in reverse order.
s
REVERSE stores the bytes of the index block in reverse order and excludes the rowid when the index is rebuilt. NOREVERSE stores the bytes of the index block without reversing the order when the index is rebuilt. Rebuilding a REVERSE index without the NOREVERSE keyword produces a rebuilt, reversekeyed index.
s
Restrictions:
s s
You cannot reverse a bitmap index or an index-organized table. You cannot specify REVERSE or NOREVERSE for a partition or subpartition.
TABLESPACE
specifies the tablespace where the rebuilt index, index partition, or index subpartition will be stored. The default is the default tablespace where the index or partition resided before you rebuilt it.
7-38
SQL Reference
ALTER INDEX
COMPRESS
enables key compression, which eliminates repeated occurrence of key column values. Use integer to specify the prefix length (number of prefix columns to compress).
s
For unique indexes, the range of valid prefix length values is from 1 to the number of key columns minus 1. The default prefix length is the number of key columns minus 1. For nonunique indexes, the range of valid prefix length values is from 1 to the number of key columns. The default prefix length is number of key columns.
s
Oracle compresses only nonpartitioned indexes that are nonunique or unique indexes of at least two columns. Restriction: You cannot specify COMPRESS for a bitmapped index. NOCOMPRESS ONLINE disables key compression. This is the default. specifies that DML operations on the table or partition are allowed during rebuilding of the index. Restriction: Parallel DML is not supported during online index building. If you specify ONLINE and then issue parallel DML statements, Oracle returns an error. COMPUTE STATISTICS enables you to collect statistics at relatively little cost during the rebuilding of an index. These statistics are stored in the data dictionary for ongoing use by the optimizer in choosing a plan of execution for SQL statements. The types of statistics collected depend on the type of index you are rebuilding. Note: If you create an index using another index (instead of a table), the original index might not provide adequate statistical information. Therefore, Oracle generally uses the base table to compute the statistics, which will improve the statistics but may negatively affect performance.
.
Additional methods of collecting statistics are available in PL/SQL packages and procedures. See Oracle8i Supplied PL/SQL Packages Reference. specifies whether the ALTER INDEX ... REBUILD operation will be logged.
LOGGING | NOLOGGING
SQL Statements 7-39
ALTER INDEX
PARAMETERS
applies only to domain indexes. This clause specifies the parameter string for altering the index (or, in the rebuild_clause, rebuilding the index). The maximum length of the parameter string is 1000 characters. This string is passed uninterpreted to the appropriate indextype routine. See Also:
s s
Oracle8i Data Cartridge Developer's Guide for more information on these routines. "CREATE INDEX" on page 7-291 for more information on domain indexes.
Restrictions:
s s
You cannot specify this clause for any indexes other than domain indexes. The parameter string is passed to the appropriate routine only if index is not marked UNUSABLE.
ENABLE
applies only to a function-based index that has been disabled because a user-defined function used by the index was dropped or replaced. This clause enables such an index if
s s
the function is currently valid, the signature of the current function matches the signature of the function when the index was created, and the function is currently marked as DETERMINISTIC.
s
Restriction: You cannot specify any other clauses of ALTER INDEX in the same statement with ENABLE. DISABLE applies only to a function-based index. This clause enables you to disable the use of a function-based index. You might want to do so, for example, while working on the body of the function. Afterward you can either rebuild the index or specify another ALTER INDEX statement with the ENABLE keyword. marks the index or index partition(s) or index subpartition(s) UNUSABLE. An unusable index must be rebuilt, or dropped and re-created, before it can be used. While one partition is marked UNUSABLE, the other partitions of the index are still valid. You can execute statements that require the index if the statements do not access the unusable partition. You can also split or rename the unusable partition before rebuilding it. Restriction: You cannot specify this clause for an index on a temporary table. RENAME TO COALESCE renames index to new_index_name. The new_index_name is a single identifier and does not include the schema name. instructs Oracle to merge the contents of index blocks where possible to free blocks for reuse. Restriction: You cannot specify this clause for an index on a temporary table. See Also: Oracle8i Administrator's Guide for more information on space management and coalescing indexes. partitioning_clauses: The remainder of the clauses of the ALTER INDEX statement are valid only for partitioned indexes.
UNUSABLE
7-40
SQL Reference
ALTER INDEX
Restrictions:
s s
You cannot specify any of these clauses for an index on a temporary table. You can combine several operations on the base index into one ALTER INDEX statement (except RENAME and REBUILD), but you cannot combine partition operations with other partition operations or with operations on the base index.
modify_default_ attributes_clause
specifies new values for the default attributes of a partitioned index. Restriction: The only attribute you can specify for an index on a hash-partitioned or composite-partitioned table is TABLESPACE. TABLESPACE LOGGING | NOLOGGING specifies the default tablespace for new partitions of an index or subpartitions of an index partition. specifies the default logging attribute of a partitioned index or an index partition.
FOR PARTITION specifies the default attributes for the subpartitions of a partition of a partition local index on a composite-partitioned table. modify_partition_ clause modifies the real physical attributes, logging attribute, or storage characteristics of index partition partition or its subpartitions. Restriction: You cannot specify the physical_attributes_clause for an index on a hashpartitioned table. Note: If the index is a local index on a composite-partitioned table, the changes you specify here will override any attributes specified earlier for the subpartitions of index, as well as establish default values of attributes for future subpartitions of that partition. To change the default attributes of the partition without overriding the attributes of subpartitions, use ALTER TABLE ... MODIFY DEFAULT ATTRIBUTES OF PARTITION. rename_partition/ subpartition_clause drop_partition_ clause split_partition_ clause renames index partition or subpartition to new_name. removes a partition and the data in it from a partitioned global index. When you drop a partition of a global index, Oracle marks the index's next partition UNUSABLE. You cannot drop the highest partition of a global index. splits a partition of a global partitioned index into two partitions, adding a new partition to the index. Splitting a partition marked UNUSABLE results in two partitions, both marked UNUSABLE. You must rebuild the partitions before you can use them. Splitting a usable partition results in two partitions populated with index data. Both new partitions are usable.
SQL Statements 7-41
ALTER INDEX
AT (value_list)
specifies the new noninclusive upper bound for split_partition_1. The value_list must evaluate to less than the presplit partition bound for partition_name_old and greater than the partition bound for the next lowest partition (if there is one). describes the two partitions resulting from the split.
INTO partition_ description modify_ subpartition_clause
specifies (optionally) the name and physical attributes of each of two partitions resulting from a split. lets you mark UNUSABLE or allocate or deallocate storage for a subpartition of a local index on a composite-partitioned table. All other attributes of such a subpartition are inherited from partition-level default attributes.
Examples
Modifying Real Attributes 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);
If the SCOTT.CUSTOMER index is partitioned, this statement also alters the default attributes of future partitions of the index. New partitions added in the future will use 5 initial transaction entries and an incremental extent of 100K.
Dropping an Index Partition The following statement drops index partition IX_
ANTARTICA:
ALTER INDEX sales_area_ix DROP PARTITION ix_antarctica;
Modifying Default Attributes
This statement alters the default attributes of local partitioned index SALES_IX3. New partitions added in the future will use 5 initial transaction entries and an incremental extent of 100K:
ALTER INDEX sales_ix3 MODIFY DEFAULT ATTRIBUTES INITRANS 5 STORAGE ( NEXT 100K );
Marking an Index Unusable The following statement marks the IDX_ACCTNO
index as UNUSABLE:
ALTER INDEX idx_acctno UNUSABLE;
7-42
SQL Reference
ALTER INDEX
Marking a Partition Unusable The following statement marks partition IDX_ FEB96 of index IDX_ACCTNO as UNUSABLE:
ALTER INDEX idx_acctno MODIFY PARTITION idx_feb96 UNUSABLE;
The following statement changes the maximum number of extents for partition BRIX_NY and changes the logging attribute:
Changing MAXEXTENTS
ALTER INDEX branch_ix MODIFY PARTITION brix_ny STORAGE( MAXEXTENTS 30 ) LOGGING;
Disabling Parallel Queries The following statement sets the parallel attributes for
index ARTIST_IX so that scans on the index will not be parallelized:
ALTER INDEX artist_ix NOPARALLEL;
Rebuilding a Partition The following statement rebuilds partition P063 in index ARTIST_IX. The rebuilding of the index partition will not be logged:
ALTER INDEX artist_ix REBUILD PARTITION p063 NOLOGGING;
Renaming an Index The following statement renames an index:
ALTER INDEX emp_ix1 RENAME TO employee_ix1;
Renaming an Index Partition The following statement renames an index partition:
ALTER INDEX employee_ix1 RENAME PARTITION emp_ix1_p3 TO employee_ix1_p3;
Splitting a Partition The following statement splits partition PARTNUM_IX_P6 in
partitioned index PARTNUM_IX into PARTNUM_IX_P5 and PARTNUM_IX_P6:
ALTER INDEX partnum_ix SPLIT PARTITION partnum_ix_p6 AT ( 5001 ) INTO ( PARTITION partnum_ix_p5 TABLESPACE ts017 LOGGING, PARTITION partnum_ix_p6 TABLESPACE ts004 );
The second partition retains the name of the old partition.
Storing Index Blocks in Reverse Order The following statement rebuilds index EMP_IX so that the bytes of the index block are stored in REVERSE order:
ALTER INDEX emp_ix REBUILD REVERSE;
SQL Statements 7-43
ALTER INDEX
Collecting Index Statistics The following statement collects statistics on the
nonpartitioned EMP_INDX index:
ALTER INDEX emp_indx REBUILD COMPUTE STATISTICS;
The type of statistics collected depends on the type of index you are rebuilding.
See Also: Oracle8i Concepts.
The following statement causes the index to be rebuilt from the existing index by using parallel parallel execution processes to scan the old and to build the new index:
PARALLEL Example
ALTER INDEX emp_idx REBUILD PARALLEL;
7-44
SQL Reference
ALTER JAVA
ALTER JAVA
Syntax
SOURCE ALTER JAVA CLASS
schema
. object_name
, RESOLVER ( ( match_string
schema_name ) )
COMPILE RESOLVE invoker_rights_clause ;
invoker_rights_clause::=
CURRENT_USER AUTHID DEFINER
Purpose
To force the resolution of a Java class schema object or compilation of a Java source schema object. (You cannot call the methods of a Java class before all its external references to Java names are associated with other classes.)
See Also: Oracle8i Java Stored Procedures Developer's Guide for more
information on resolving Java classes and compiling Java sources.
Prerequisites
The Java source or class must be in your own schema, or you must have the ALTER ANY PROCEDURE system privilege. You must also have the EXECUTE object privilege on Java classes.
Keywords and Parameters
JAVA SOURCE compiles a Java source schema object.
SQL Statements 7-45
ALTER JAVA
JAVA CLASS object_name RESOLVER
resolves a Java class schema object. specifies a previously created Java class or source schema object. Use double quotation marks to preserve lower- or mixed-case names. specifies how schemas are searched for referenced fully specified Java names, using the mapping pairs specified when the Java class or source was created. See Also: "CREATE JAVA" on page 7-311.
RESOLVE | COMPILE
are synonymous keywords. They specify that Oracle should attempt to resolve the primary Java class schema object.
s
When applied to a class, resolution of referenced names to other class schema objects occurs. When applied to a source, source compilation occurs.
s
invoker_rights_ clause
specifies whether the methods of the class execute with the privileges and in the schema of the user who defined it or with the privileges and in the schema of CURRENT_USER. For information on how CURRENT_USER is determined, see Oracle8i Concepts and Oracle8i Application Developer's Guide - Fundamentals. This clause also determines how Oracle resolves external names in queries, DML operations, and dynamic SQL statements in the member functions and procedures of the type. See Also: Oracle8i Java Stored Procedures Developer's Guide. AUTHID CURRENT_USER specifies that the methods of the class execute with the privileges of CURRENT_USER. This clause is the default and creates an "invokerrights class." This clause also specifies that external names in queries, DML operations, and dynamic SQL statements resolve in the schema of CURRENT_USER. External names in all other statements resolve in the schema in which the methods reside. AUTHID DEFINER specifies that the methods of the class execute with the privileges of the user who defined it. This clause also specifies that external names resolve in the schema where the methods reside.
Example
The following statement forces the resolution of a Java class:
ALTER JAVA CLASS "Agent" RESOLVER (("/home/java/bin/*" scott)(* public)) RESOLVE;
7-46
SQL Reference
ALTER MATERIALIZED VIEW / SNAPSHOT
ALTER MATERIALIZED VIEW / SNAPSHOT
Syntax
MATERIALIZED ALTER SNAPSHOT physical_attributes_clause , LOB_storage_clause , modify_LOB_storage_clause partitioning_clauses parallel_clause LOGGING NOLOGGING allocate_extent_clause CACHE NOCACHE VIEW schema . materialized_view / snapshot
USING
INDEX
physical_attributes_clause
refresh_clause
ENABLE QUERY DISABLE COMPILE CONSIDER FRESH ; REWRITE
LOB_storage_clause: See "ALTER TABLE" on page 7-123.
SQL Statements 7-47
ALTER MATERIALIZED VIEW / SNAPSHOT
modify_LOB_storage_clause: See "ALTER TABLE" on page 7-123. partitioning_clauses: See "ALTER TABLE" on page 7-123. parallel_clause::=
NOPARALLEL integer PARALLEL
allocate_extent_clause::=
K M SIZE ( integer ' filename integer ' )
DATAFILE INSTANCE
ALLOCATE
EXTENT
refresh_clause::=
FAST COMPLETE FORCE DEMAND ON COMMIT REFRESH START NEXT WITH PRIMARY DEFAULT USING MASTER ROLLBACK SEGMENT rollback_segment KEY MASTER ROLLBACK SEGMENT WITH date
7-48
SQL Reference
ALTER MATERIALIZED VIEW / SNAPSHOT
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
storage_clause: See the "storage_clause" on page 7-605.
Purpose
To modify an existing materialized view in one or more of the following ways:
s
To change its storage characteristics To change its refresh method, mode, or time To alter its structure so that it is a different type of materialized view To enable or disable query rewrite.
s
s
s
The terms snapshot and materialized view are synonymous in Oracle documentation. "Materialized view" is used in this reference. Both refer to a database object that contains the results of a query of one or more tables. The tables in the query are called master tables (a replication term) or detail tables (a data warehouse term). This reference uses "master tables" for consistency. The databases containing the master tables are called the master databases.
See Also:
s
"CREATE MATERIALIZED VIEW / SNAPSHOT" on page 7-318 for more information on creating materialized views. Oracle8i Replication for information on materialized views in a replication environment. Oracle8i Data Warehousing Guide for information on materialized views in a data warehousing environment.
s
s
SQL Statements 7-49
ALTER MATERIALIZED VIEW / SNAPSHOT
Prerequisites
The privileges required to alter a materialized view should be granted directly, as follows: The materialized view must be in your own schema, or you must have the ALTER ANY SNAPSHOT or ALTER ANY MATERIALIZED VIEW system privilege. To enable a materialized view for query rewrite:
s
If all of the master tables in the materialized view are in your schema, you must have the QUERY REWRITE privilege. If any of the master tables are in another schema, you must have the GLOBAL QUERY REWRITE privilege. If the materialized view is in another user's schema, both you and the owner of that schema must have the appropriate QUERY REWRITE privilege, as described in the preceding two items. In addition, the owner of the materialized view must have SELECT access to any master tables that the materialized view owner does not own.
See Also: Oracle8i Replication and Oracle8i Data Warehousing Guide.
s
s
Keywords and Parameters
schema materialized view / snapshot is the schema containing the materialized view. If you omit schema, Oracle assumes the materialized view is in your own schema. is the name of the materialized view to be altered.
physical_ changes values for the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters (or, attributes_clause when used in the USING INDEX clause, for the INITRANS and MAXTRANS parameters only) and the storage characteristics for the materialized view. See Also:
s
"ALTER TABLE" on page 7-123 for information on the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters. "storage_clause" on page 7-605 for information about storage characteristics.
s
LOGGING| NOLOGGING allocate_extent_ clause
establishes or changes the logging characteristics of the materialized view. See Also: "ALTER TABLE" on page 7-123 for information about logging characteristics. explicitly allocates a new extent for the materialized view. See Also: "ALTER TABLE" on page 7-123.
7-50
SQL Reference
ALTER MATERIALIZED VIEW / SNAPSHOT
CACHE| NOCACHE
For data that will be accessed frequently, CACHE specifies that the blocks retrieved for this table are placed at the most recently used end of the LRU list in the buffer cache when a full table scan is performed. This attribute is useful for small lookup tables. NOCACHE specifies that the blocks are placed at the least recently used end of the LRU list. See Also: "ALTER TABLE" on page 7-123 for information about specifying CACHE or NOCACHE.
LOB_storage_ clause
specifies the LOB storage characteristics. See Also: "ALTER TABLE" on page 7-123 for information about specifying the parameters of this clause. modifies the physical attributes of the LOB attribute lob_item or LOB object attribute. See Also: "ALTER TABLE" on page 7-123 for information about specifying the parameters of this clause. The syntax and general functioning of the partitioning clauses is the same as for partitioned tables, as described in "ALTER TABLE" on page 7-123. Restrictions:
s
modify_LOB_ storage_clause
partitioning_ clauses:
You cannot use the LOB_storage_clause or modify_LOB_storage_clause when modifying a materialized view. If you attempt to drop, truncate, or exchange a materialized view partition, Oracle raises an error.
s
Note: If you wish to keep the contents of the materialized view synchronized with those of the master table, Oracle Corporation recommends that you manually perform a complete refresh of all materialized views dependent on the table after dropping or truncating a table partition. parallel_clause changes the default degree of parallelism for the materialized view. NOPARALLEL PARALLEL specifies serial execution. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances multiplied by the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution processes. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer. See Also: The Notes to the parallel_clause of "CREATE TABLE" on page 4-381. MODIFY PARTITION UNUSABLE LOCAL INDEXES marks UNUSABLE all the local index partitions associated with partition.
SQL Statements 7-51
ALTER MATERIALIZED VIEW / SNAPSHOT
MODIFY PARTITION REBUILD UNUSABLE LOCAL INDEXES rebuilds the unusable local index partitions associated with partition. USING INDEX changes the value of INITRANS, MAXTRANS, and STORAGE parameters for the index Oracle uses to maintain the materialized view's data. Restriction: You cannot specify the PCTUSED or PCTFREE parameters in this clause. refresh_clause changes the default method and mode and the default times for automatic refreshes. If the contents of a materialized view's master tables are modified, the data in the materialized view must be updated to make the materialized view accurately reflect the data currently in its master table(s). This clause lets you schedule the times and specify the method and mode for Oracle to refresh the materialized view. Note: This clause only sets the default refresh options. For instructions on actually implementing the refresh, refer to Oracle8i Replication and Oracle8i Data Warehousing Guide. FAST specifies the incremental refresh method, which performs the refresh according to the changes that have occurred to the master tables. The changes are stored either in the materialized view log associated with the master table (for conventional DML changes) or in the direct loader log (for direct-load INSERTs). For both conventional DML changes and for direct-path loads, other conditions may restrict the eligibility of a materialized view for fast refresh. See Also:
s
Oracle8i Replication for restrictions on fast refresh in replication environments Oracle8i Data Warehousing Guide for restrictions on fast refresh in data warehouse environments
s
Notes:
s
When you specify FAST refresh at create time, Oracle verifies that the materialized view you are creating is eligible for fast refresh. When you change the refresh method to FAST in an ALTER MATERIALIZED VIEW statement, Oracle does not perform this verification. If the materialized view is not eligible for fast refresh, Oracle will return an error when you attempt to refresh this view. Materialized views are not eligible for fast refresh if the defining query contains an analytic function. See Also: "Analytic Functions" on page 4-7.
s
COMPLETE
specifies the complete refresh method, which is implemented by executing the materialized view's defining query. If you request a complete refresh, Oracle performs a complete refresh even if a fast refresh is possible.
7-52
SQL Reference
ALTER MATERIALIZED VIEW / SNAPSHOT
FORCE ON COMMIT
specifies that when a refresh occurs, Oracle will perform a fast refresh if one is possible or a complete refresh otherwise. specifies that a fast refresh is to occur whenever Oracle commits a transaction that operates on a master table of the materialized view. Restriction: This clause is supported only for materialized join views and single-table materialized aggregate views. See Also: Oracle8i Replication and Oracle8i Data Warehousing Guide.
ON DEMAND
specifies that the materialized view will be refreshed on demand by calling one of the three DBMS_MVIEW refresh procedures. If you omit both ON COMMIT and ON DEMAND, ON DEMAND is the default. See Also:
s
Oracle8i Supplied PL/SQL Packages Reference for information on these procedures. Oracle8i Data Warehousing Guide on the types of materialized views you can create by specifying REFRESH ON DEMAND.
s
If you specify ON COMMIT or ON DEMAND, you cannot also specify START WITH or NEXT. START WITH NEXT specifies a date expression for the first automatic refresh time. 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 with respect to the creation time of the materialized view. If you specify a START WITH value but omit the NEXT value, Oracle refreshes the materialized view 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 materialized view. WITH PRIMARY KEY changes a rowid materialized view to a primary key materialized view. Primary key materialized views allow materialized view master tables to be reorganized without affecting the materialized view's ability to continue to fast refresh. The master table must contain an enabled primary key constraint. See Also: Oracle8i Replication for detailed information about primary key materialized views. USING ROLLBACK SEGMENT changes the remote rollback segment to be used during materialized view refresh, where rollback_segment is the name of the rollback segment to be used. See Also: Oracle8i Replication for information on changing the local materialized view rollback segment using the DBMS_REFRESH package.
SQL Statements 7-53
ALTER MATERIALIZED VIEW / SNAPSHOT
s
DEFAULT specifies that Oracle will choose the rollback segment to use. If you specify DEFAULT, you cannot specify rollback_segment. MASTER specifies the remote rollback segment to be used at the remote master for the individual materialized view. (To change the local materialized view rollback segment, use the DBMS_ REFRESH package, described in Oracle8i Replication.)
s
The master rollback segment is stored on a per-materialized-view basis and is validated during materialized view creation and refresh. If the materialized view is complex, the master rollback segment, if specified, is ignored. QUERY REWRITE specifies whether the materialized view is eligible to be used for query rewrite. ENABLE enables the materialized view for query rewrite. See Also: Oracle8i Data Warehousing Guide for more information on query rewrite. Restrictions:
s
If the materialized view is in an invalid or unusable state, it is not eligible for query rewrite in spite of the ENABLE mode. You cannot enable query rewrite if the materialized view was created totally or in part from a view. You can enable query rewrite only if all user-defined functions in the materialized view are DETERMINISTIC. See Also: "CREATE FUNCTION" on page 7-284. You can enable query rewrite only if expressions in the statement are repeatable. For example, you cannot include CURRENT_TIME or USER. See Also: Oracle8i Data Warehousing Guide.
s
s
s
DISABLE
specifies that the materialized view is not eligible for use by query rewrite. (If a materialized view is in the invalid state, it is not eligible for use by query rewrite, whether or not it is disabled.) However, a disabled materialized view can be refreshed.
COMPILE
explicitly revalidates a materialized view. If an object upon which the materialized view depends is dropped or altered, the materialized view remains accessible, but it is invalid for query rewrite. You can use this clause to explicitly revalidate the materialized view to make it eligible for query rewrite. If the materialized view fails to revalidate, it cannot be refreshed or used for query rewrite.
7-54
SQL Reference
ALTER MATERIALIZED VIEW / SNAPSHOT
CONSIDER FRESH
directs Oracle to consider the materialized view fresh and therefore eligible for query rewrite in the TRUSTED or STALE_TOLERATED modes. Because Oracle cannot guarantee the freshness of the materialized view, query rewrite in ENFORCED mode is not supported. This clause also sets the staleness state of the materialized view to UNKNOWN. The staleness state is displayed in the STALENESS column of the ALL_MVIEWS, DBA_MVIEWS, and USER_MVIEWS data dictionary views. This clause is useful after performing partition maintenance operations against the master table. Such operations would otherwise render the materialized view ineligible for fast refresh, and eligible for query rewrite only in STALE_TOLERATED mode. Note: A materialized view is stale if changes have been made to the contents of any of its master tables. This clause directs Oracle to assume that the materialized view is fresh and that no such changes have been made. Therefore, actual updates to those tables pending refresh are purged with respect to the materialized view. See Also: Oracle8i Data Warehousing Guide for more information on query rewrite and the implications of performing partition maintenance operations on master tables.
Examples
Automatic Refresh Example The following statement changes the default refresh
method for the HQ_EMP materialized view to FAST:
CREATE MATERIALIZED VIEW hq_emp REFRESH COMPLETE START WTIH SYSDATE NEXT SYSDATE +1/4096 AS SELECT * FROM hq_emp; ALTER MATERIALIZED VIEW hq_emp REFRESH FAST;
The next automatic refresh of the materialized view will be a fast refresh provided it is a simple materialized view and its master table has a materialized view log that was created before the materialized view 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 materialized view was created or last altered are still used.
NEXT Example The following statement stores a new interval between automatic
refreshes for the BRANCH_EMP materialized view:
ALTER MATERIALIZED VIEW branch_emp REFRESH NEXT SYSDATE+7;
SQL Statements 7-55
ALTER MATERIALIZED VIEW / SNAPSHOT
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 materialized view was created or last altered. At the time of the next automatic refresh, Oracle refreshes the materialized view, evaluates the NEXT expression SYSDATE+7 to determine the next automatic refresh time, and continues to refresh the materialized view automatically once a week. Because the REFRESH clause does not explicitly specify a refresh method, Oracle continues to use the refresh method specified by the REFRESH clause of the CREATE MATERIALIZED VIEW or most recent ALTER MATERIALIZED VIEW statement. The following statement specifies a new refresh method, a new next refresh time, and a new interval between automatic refreshes of the SF_EMP materialized view:
Complete Refresh Example
ALTER MATERIALIZED VIEW 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 materialized view to be 9:00 a.m. tomorrow. At that point, Oracle performs a complete refresh of the materialized view, evaluates the NEXT expression, and subsequently refreshes the materialized view every week.
Enabling Query Rewrite Example The following statement enables query rewrite
on the materialized view MV1 and implicitly revalidates it.
ALTER MATERIALIZED VIEW mv1 ENABLE QUERY REWRITE;
Rollback Segment Examples The following statement changes the remote master
rollback segment used during materialized view refresh to MASTER_SEG:
ALTER MATERIALIZED VIEW inventory REFRESH USING MASTER ROLLBACK SEGMENT master_seg;
The following statement changes the remote master rollback segment used during materialized view refresh to one chosen by Oracle:
ALTER MATERIALIZED VIEW sales REFRESH USING DEFAULT MASTER ROLLBACK SEGMENT;
7-56
SQL Reference
ALTER MATERIALIZED VIEW / SNAPSHOT
The following statement changes a rowid materialized view to a primary key materialized view:
Primary Key Example
ALTER MATERIALIZED VIEW emp_rs REFRESH WITH PRIMARY KEY;
COMPILE Example
The following statement revalidates the materialized view
STORE_MV:
ALTER MATERIALIZED VIEW store_mv COMPILE;
The following statement changes the refresh method of materialized view STORE_MV to FAST;
Modifying Refresh Method Example
ALTER MATERIALIZED VIEW store_mv REFRESH FAST;
CONSIDER FRESH Example The following statement instructs Oracle that
materialized view MV1 should be considered fresh. This statement allows MV1 to be eligible for query rewrite in TRUSTED mode even after you have performed partition maintenance operations on the master tables of MV1:
ALTER MATERIALIZED VIEW mv1 CONSIDER FRESH;
SQL Statements 7-57
ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG
ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG
Syntax
MATERIALIZED ALTER SNAPSHOT physical_attributes_clause partitioning_clauses parallel_clause LOGGING NOLOGGING allocate_extent_clause CACHE ADD NOCACHE INCLUDING NEW EXCLUDING ; VALUES ROWID PRIMARY KEY ( , filter_column ) VIEW LOG ON schema . table
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
storage_clause: See "storage_clause" on page 7-605.
7-58
SQL Reference
ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG
partitioning_clauses: See "ALTER TABLE" on page 7-123. allocate_extent_clause::=
K M SIZE ( integer ' filename integer ' )
DATAFILE INSTANCE
ALLOCATE
EXTENT
parallel_clause::=
NOPARALLEL integer PARALLEL
Purpose
To alter the storage characteristics, refresh mode or time, or type of an existing materialized view log. A materialized view log is a table associated with the master table of a materialized view. The terms snapshot and materialized view are synonymous. Both refer to a table that contains the results of a query of one or more tables, each of which may be located on the same or on a remote database.
See Also:
s
"ALTER MATERIALIZED VIEW / SNAPSHOT" on page 2-47 for more information on materialized views, including refreshing them. "CREATE MATERIALIZED VIEW / SNAPSHOT" on page 7-318 for a description of the various types of materialized views
s
SQL Statements 7-59
ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG
Prerequisites
Only the owner of the master table or a user with the SELECT privilege for the master table can alter a materialized view log.
See Also: Oracle8i Replication for detailed information about the prerequisites for ALTER SNAPSHOT LOG.
Keywords and Parameters
schema table is the schema containing the master table. If you omit schema, Oracle assumes the materialized view log is in your own schema. is the name of the master table associated with the materialized view log to be altered.
physical_ changes the value of PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters for the attributes_clause table, the partition, the overflow data segment, or the default characteristics of a partitioned table. For a description of these parameters, see "CREATE TABLE" on page 4-381. See also the "Storage Example" on page 2-61. partitioning_ clauses The syntax and general functioning of the partitioning clauses is the same as for the ALTER TABLE statement; see "ALTER TABLE" on page 7-123. Restrictions:
s
You cannot use the LOB_storage_clause or modify_LOB_storage_clause when modifying a materialized view log. If you attempt to drop, truncate, or exchange a materialized view log partition, Oracle raises an error.
s
parallel_clause
specifies whether parallel operations will be supported for the materialized view log. For additional information, see the Notes to the parallel_clause of "CREATE TABLE" on page 4-381. NOPARALLEL PARALLEL specifies serial execution. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances times the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution processes. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer. LOGGING | NOLOGGING specifies the logging attribute. For information about specifying this attribute, see "ALTER TABLE" on page 7-123.
7-60
SQL Reference
ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG
allocate_extent_ clause CACHE | NOCACHE
explicitly allocates a new extent for the materialized view log. See Also: "ALTER TABLE" on page 7-123. For data that will be accessed frequently, CACHE specifies that the blocks retrieved for this log are placed at the most recently used end of the LRU list in the buffer cache when a full table scan is performed. This attribute is useful for small lookup tables. NOCACHE specifies that the blocks are placed at the least recently used end of the LRU list. See Also: "ALTER TABLE" on page 7-123 for information about specifying CACHE or NOCACHE.
ADD
augments the materialized view log so that it records the primary key values or rowid values when rows in the materialized view master table are updated. This clause can also be used to record additional filter columns. To stop recording any of this information, you must first drop the materialized view log and then re-create it. Dropping the materialized view log and then re-creating it forces each of the existing materialized views that depend on the master table to complete refresh on its next refresh. PRIMARY KEY ROWID filter_column(s) specifies that the primary-key values of all rows that are updated should be recorded in the materialized view log. specifies that the rowid values of all rows that are updated should be recorded in the materialized view log. specifies that the values of these columns should be recorded in the materialized view log for all rows that are updated. Filter columns are non-primary-key columns referenced by materialized views. For information about filter columns, see Oracle8i Replication.
NEW VALUES
specifies whether Oracle saves both old and new values in the materialized view log. INCLUDING saves both new and old values in the log. If this log is for a table on which you have a single-table materialized aggregate view, and if you want the materialized view to be eligible for fast refresh, you must specify INCLUDING. disables the recording of new values in the log. You can use this clause to avoid the overhead of recording new values. However, do not use this clause if you have a fast-refreshable single-table materialized aggregate view defined on this table.
EXCLUDING
Examples
Storage Example The following statement changes the MAXEXTENTS value of a materialized view log:
ALTER MATERIALIZED VIEW LOG ON dept STORAGE MAXEXTENTS 50;
SQL Statements 7-61
ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG
PRIMARY KEY Example The following statement alters an existing rowid materialized view log to also record primary key information:
ALTER MATERIALIZED VIEW LOG ON sales ADD PRIMARY KEY;
7-62
SQL Reference
ALTER OUTLINE
ALTER OUTLINE
Syntax
REBUILD ALTER OUTLINE outline RENAME CHANGE TO new_outline_name TO new_category_name ;
CATEGORY
Purpose
To rename a stored outline, reassign it to a different category, or regenerate it by compiling the outline's SQL statement and replacing the old outline data with the outline created under current conditions.
See Also: "CREATE OUTLINE" on page 7-342 and Oracle8i Designing and Tuning for Performance for more information on outlines.
Prerequisites
To modify an outline, you must have the ALTER ANY OUTLINE system privilege.
Keywords and Parameters
outline REBUILD RENAME TO new_ outline_name CHANGE CATEGORY TO new_category_name is the name of the outline to be modified. regenerates the execution plan for outline using current conditions. specifies an outline name to replace outline. specifies the name of the category into which the outline will be moved.
Example
The following statement regenerates a stored outline called SALARIES by compiling the outline's text and replacing the old outline data with the outline created under current conditions.
ALTER OUTLINE salaries REBUILD;
SQL Statements 7-63
ALTER PACKAGE
ALTER PACKAGE
Syntax
PACKAGE SPECIFICATION schema ALTER PACKAGE . package COMPILE DEBUG BODY ;
Purpose
To explicitly recompile either a package specification, body, or both. Explicit recompilation eliminates the need for implicit run-time recompilation and prevents associated run-time compilation errors and performance overhead. Because all objects in a package are stored as a unit, the ALTER PACKAGE statement recompiles all package objects together. You cannot use the ALTER PROCEDURE statement or ALTER FUNCTION statement to recompile individually a procedure or function that is part of a package.
Note: This statement does not change the declaration or definition
of an existing package. To redeclare or redefine a package, use the "CREATE PACKAGE" or the "CREATE PACKAGE BODY" statement with the OR REPLACE clause.
Prerequisites
The package must be in your own schema or you must have ALTER ANY PROCEDURE system privilege.
Keywords and Parameters
schema package is the schema containing the package. If you omit schema, Oracle assumes the package is in your own schema. is the name of the package to be recompiled.
7-64
SQL Reference
ALTER PACKAGE
COMPILE
recompiles the package specification or body. The COMPILE keyword is required. If recompiling the package results in compilation errors, Oracle returns an error and the body remains invalid. You can see the associated compiler error messages with the SQL*Plus command SHOW ERRORS.
SPECIFICATION recompiles only the package specification, regardless of whether it is invalid. You might want to recompile a package specification to check for compilation errors after modifying the specification. 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. 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 run time. BODY recompiles only the package body regardless of whether it is invalid. You might want to recompile a package body after modifying it. Recompiling a package body does not invalidate objects that depend upon the package specification. When you recompile a package body, Oracle first recompiles the objects on which the body depends, if any of those objects are invalid. If Oracle recompiles the body successfully, the body becomes valid. PACKAGE recompiles both the package specification and the package body if one exists, regardless of whether they are invalid. This is the default. The recompilation of the package specification and body lead to the invalidation and recompilation as described above for SPECIFICATION and BODY. For information on how Oracle maintains dependencies among schema objects, including remote objects, see Oracle8i Concepts. DEBUG instructs the PL/SQL compiler to generate and store the code for use by the PL/SQL debugger. For information on debugging packages, see Oracle8i Supplied PL/SQL Packages Reference.
Examples
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 run-time recompilation. If recompiling ACCOUNTING results in compilation errors, Oracle returns an error and ACCOUNTING remains invalid.
SQL Statements 7-65
ALTER PACKAGE
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 run time. To recompile the body of the ACCOUNTING package in the schema BLAIR, issue the following 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 run-time 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.
7-66
SQL Reference
ALTER PROCEDURE
ALTER PROCEDURE
Syntax
schema ALTER PROCEDURE . procedure COMPILE DEBUG ;
Purpose
To explicitly recompile a stand-alone stored procedure. Explicit recompilation eliminates the need for implicit run-time recompilation and prevents associated run-time compilation errors and performance overhead. To recompile a procedure that is part of a package, recompile the entire package using the ALTER PACKAGE statement (see "ALTER PACKAGE" on page 2-64).
Note: This statement does not change the declaration or definition
of an existing procedure. To redeclare or redefine a procedure, use the CREATE PROCEDURE statement with the OR REPLACE clause (see "CREATE PROCEDURE" on page 7-353) The ALTER PROCEDURE statement is quite similar to the ALTER FUNCTION statement (see "ALTER FUNCTION" on page 2-28).
Prerequisites
The procedure must be in your own schema or you must have ALTER ANY PROCEDURE system privilege.
Keywords and Parameters
schema procedure is the schema containing the procedure. If you omit schema, Oracle assumes the procedure is in your own schema. is the name of the procedure to be recompiled.
SQL Statements 7-67
ALTER PROCEDURE
COMPILE
causes Oracle to recompile the procedure. The COMPILE keyword is required. Oracle recompiles the procedure regardless of whether it is valid or invalid.
s
Oracle first recompiles objects upon which the procedure depends, if any of those 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 see the associated compiler error messages with the SQL*Plus command SHOW ERRORS.
s
s
For information on how Oracle maintains dependencies among schema objects, including remote objects, see Oracle8i Concepts. DEBUG instructs the PL/SQL compiler to generate and store the code for use by the PL/SQL debugger. For information on debugging procedures, see Oracle8i Application Developer's Guide Fundamentals.
Example
To explicitly recompile the procedure CLOSE_ACCT owned by the user HENRY, issue the following 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 run time. 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 run time.
7-68
SQL Reference
ALTER PROFILE
ALTER PROFILE
Syntax
resource_parameters ALTER PROFILE profile LIMIT password_parameters ;
resource_parameters::=
SESSIONS_PER_USER CPU_PER_SESSION CPU_PER_CALL integer CONNECT_TIME UNLIMITED IDLE_TIME DEFAULT LOGICAL_READS_PER_SESSION LOGICAL_READS_PER_CALL COMPOSITE_LIMIT K M integer PRIVATE_SGA UNLIMITED DEFAULT
SQL Statements 7-69
ALTER PROFILE
password_parameters::=
FAILED_LOGIN_ATTEMPTS PASSWORD_LIFE_TIME expr PASSWORD_REUSE_TIME UNLIMITED PASSWORD_REUSE_MAX DEFAULT PASSWORD_LOCK_TIME PASSWORD_GRACE_TIME function PASSWORD_VERIFY_FUNCTION NULL DEFAULT
Purpose
To add, modify, or remove a resource limit or password management parameter in a profile. Changes made to a profile with an ALTER PROFILE statement affect users only in their subsequent sessions, not in their current sessions. For information on creating a profile, see "CREATE PROFILE" on page 7-359.
Prerequisites
You must have ALTER PROFILE system privilege to change profile resource limits. To modify password limits and protection, you must have ALTER PROFILE and ALTER USER system privileges.
Keywords and Parameters
The keywords and parameters in the ALTER PROFILE statement all have the same meaning as in the CREATE PROFILE statement. See "CREATE PROFILE" on page 7-359.
Note: You cannot remove a limit from the DEFAULT profile.
7-70
SQL Reference
ALTER PROFILE
Examples
Making a Password Unavailable The following statement makes a password
unavailable for reuse for 90 days:
ALTER PROFILE prof LIMIT PASSWORD_REUSE_TIME 90 PASSWORD_REUSE_MAX UNLIMITED;
Setting Default Values The following statement defaults the PASSWORD_REUSE_ TIME value to its defined value in the DEFAULT profile:
ALTER PROFILE prof LIMIT PASSWORD_REUSE_TIME DEFAULT PASSWORD_REUSE_MAX UNLIMITED;
Limiting Login Attempts and Password Lock Time The following statement alters profile PROF with FAILED_LOGIN_ATTEMPTS set to 5 and PASSWORD_LOCK_TIME set to 1:
ALTER PROFILE prof LIMIT FAILED_LOGIN_ATTEMPTS 5 PASSWORD_LOCK_TIME 1;
This statement causes PROF's account to become locked for 1 day after 5 unsuccessful login attempts.
Changing Password Lifetime and Grace Period The following statement modifies profile PROF's PASSWORD_LIFE_TIME to 60 days and PASSWORD_GRACE_TIME to 10 days:
ALTER PROFILE prof LIMIT PASSWORD_LIFE_TIME 60 PASSWORD_GRACE_TIME 10;
Limiting Concurrent Sessions
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, the above statement adds the limit of 5 to the profile. If the profile already defines a limit, the above statement redefines it to 5. Any user assigned the ENGINEER profile is subsequently limited to 5 concurrent sessions.
SQL Statements 7-71
ALTER PROFILE
Removing Limits 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 in their subsequent sessions to the IDLE_TIME limit defined in the DEFAULT profile.
Limiting Idle Time
This statement defines a limit of 2 minutes of idle time for the
2;
DEFAULT profile:
ALTER PROFILE default LIMIT IDLE_TIME
This IDLE_TIME limit applies to these users:
s
Users who are not explicitly assigned any profile Users who are explicitly assigned a profile that does not define an IDLE_TIME limit
s
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.
7-72
SQL Reference
ALTER RESOURCE COST
ALTER RESOURCE COST
Syntax
CPU_PER_SESSION CONNECT_TIME ALTER RESOURCE COST LOGICAL_READS_PER_SESSION PRIVATE_SGA integer ;
Purpose
To specify or change the formula by which Oracle calculates the total resource cost used in a session. The weight that you assign to each resource determines how much the use of that resource contributes to the total resource cost. 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. Oracle calculates the total resource cost by first multiplying the amount of each resource used in the session by the resource's weight, and then summing the products for all four resources. For any session, this cost is limited by the value of the COMPOSITE_LIMIT parameter in the user's profile. Both the products and the total cost are expressed in units called service units. Although Oracle monitors the use of other resources, only the four resources shown in the syntax can contribute to the total resource cost for a session. For information on all resources, see "CREATE PROFILE" on page 7-359. 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 statement. If a session's cost exceeds the limit, Oracle aborts the session and returns an error. For information on establishing resource limits, see "CREATE PROFILE" on page 7-359. If you use the ALTER RESOURCE COST statement 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.
Prerequisites
You must have ALTER RESOURCE COST system privilege.
SQL Statements 7-73
ALTER RESOURCE COST
Keywords and Parameters
CPU_PER_SESSION CONNECT_TIME LOGICAL_READS_PER_ SESSION PRIVATE_SGA is the amount of CPU time used by a session measured in hundredth of seconds. is the elapsed time of a session measured in minutes. is the number of data blocks read during a session, including blocks read from both memory and disk. is the number of bytes of private space in the system global area (SGA) used by a session. This limit applies only if you are using the multi-threaded server architecture and allocating private space in the SGA for your session. is the weight of each resource.
integer
Example
The following 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:
cost = (100 * CPU_PER_SESSION) + (1 * CONNECT_TIME)
where the values of CPU_PER_SESSION and CONNECT_TIME are either values in the DEFAULT profile or in the profile of the user of the session. Because the above 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 COST exceeds 500. For example, a session using 0.04 seconds of CPU time and 101 minutes of elapsed time exceeds the limit. A session 0.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:
7-74
SQL Reference
ALTER RESOURCE COST
cost = (100 * CPU_PER_SESSION) + (2 * LOGICAL_READ_PER_SECOND)
where the values of CPU_PER_SESSION and LOGICAL_READS_PER_SECOND are either the values in the DEFAULT profile or in the profile of the user of this session. This ALTER RESOURCE COST statement changes the formula in these ways:
s
The statement omits a weight for the CPU_PER_SESSION resource and the resource was already assigned a weight, so the resource remains in the formula with its original weight. The statement assigns a weight to the LOGICAL_READS_PER_SESSION resource, so this resource now appears in the formula. The statement assigns a weight of 0 to the CONNECT_TIME resource, so this resource no longer appears in the formula. The statement omits a weight for the PRIVATE_SGA resource and the resource was not already assigned a weight, so the resource still does not appear in the formula.
s
s
s
SQL Statements 7-75
ALTER ROLE
ALTER ROLE
Syntax
NOT ALTER ROLE role IDENTIFIED IDENTIFIED BY password ;
EXTERNALLY GLOBALLY
Purpose
To change the authorization needed to enable a role. For information on creating a role, see "CREATE ROLE" on page 4-365. For information on enabling or disabling a role for your session, see "SET ROLE" on page 7-600.
Prerequisites
You must either have been granted the role with the ADMIN OPTION or have ALTER ANY ROLE system privilege. Before you alter a role to IDENTIFIED GLOBALLY, you must:
s
Revoke all grants of roles identified externally to the role and Revoke the grant of the role from all users, roles, and PUBLIC.
s
The one exception to this rule is that you should not revoke the role from the user who is currently altering the role.
Keywords and Parameters
The keywords and parameters in the ALTER ROLE statement all have the same meaning as in the CREATE ROLE statement. See "CREATE ROLE" on page 4-365.
7-76
SQL Reference
ALTER ROLE
Note: If you have the ALTER ANY ROLE system privilege and you
change a role that is IDENTIFIED GLOBALLY to IDENTIFIED BY password, IDENTIFIED EXTERNALLY, or NOT IDENTIFIED, then Oracle grants you the altered role with the ADMIN OPTION, as it would have if you had created the role identified nonglobally.
Examples
The following statement changes the role ANALYST to IDENTIFIED GLOBALLY:
ALTER ROLE analyst IDENTIFIED GLOBALLY;
This statement changes the password on the TELLER role to LETTER:
ALTER ROLE teller IDENTIFIED BY letter;
Users granted the TELLER role must subsequently enter the new password "letter" to enable the role.
SQL Statements 7-77
ALTER ROLLBACK SEGMENT
ALTER ROLLBACK SEGMENT
Syntax
ONLINE OFFLINE storage_clause ALTER ROLLBACK SEGMENT rollback_segment K M TO SHRINK integer ;
storage_clause: See "storage_clause" on page 7-605.
Purpose
To bring a rollback segment online or offline, to change its storage characteristics, or to shrink it to an optimal or specified size. For information on creating a rollback segment, see "CREATE ROLLBACK SEGMENT" on page 4-367.
Prerequisites
You must have ALTER ROLLBACK SEGMENT system privilege.
Keywords and Parameters
rollback_segment ONLINE specifies the name of an existing rollback segment. brings the rollback segment online. When you create a rollback segment, it is initially offline and not available for transactions. This clause 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.
7-78
SQL Reference
ALTER ROLLBACK SEGMENT
OFFLINE
takes the rollback segment offline.
s
If the rollback segment does not contain any information needed to roll back an active transaction, 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.
s
Once the rollback segment is offline, it can be brought online by any instance. To see whether a rollback segment is online or offline, query the data dictionary view DBA_ROLLBACK_SEGS. Online rollback segments have a STATUS value of IN_USE. Offline rollback segments have a STATUS value of AVAILABLE. Restriction: You cannot take the SYSTEM rollback segment offline. See Also: Oracle8i Administrator's Guide for more information on making rollback segments available and unavailable. storage_clause changes the rollback segment's storage characteristics. See the "storage_clause" on page 7-605 for syntax and additional information. Restriction: You cannot change the values of the INITIAL and MINEXTENTS for an existing rollback segment. SHRINK attempts to shrink the rollback segment to an optimal or specified size. The success and amount of shrinkage depend on the available free space in the rollback segment and how active transactions are holding space in the rollback segment. The value of integer is in bytes, unless you specify K or M for kilobytes or megabytes. If you do not specify TO integer, then the size defaults to the OPTIMAL value of the storage_ clause of the CREATE ROLLBACK SEGMENT statement that created the rollback segment. If OPTIMAL was not specified, then the size defaults to the MINEXTENTS value of the storage_clause of the CREATE ROLLBACK SEGMENT statement. Regardless of whether you specify TO integer:
s
The value to which Oracle shrinks the rollback segment is valid for the execution of the statement. Thereafter, the size reverts to the OPTIMAL value of the CREATE ROLLBACK SEGMENT statement. The rollback segment cannot shrink to less than two extents.
s
To determine the actual size of a rollback segment after attempting to shrink it, query the BYTES, BLOCKS, and EXTENTS columns of the DBA_SEGMENTS view. Restriction: For a parallel server, you can shrink only rollback segments that are online to your instance.
Examples
This statement brings the rollback segment RSONE online:
ALTER ROLLBACK SEGMENT rsone ONLINE;
SQL Statements 7-79
ALTER ROLLBACK SEGMENT
This statement changes the STORAGE parameters for RSONE:
ALTER ROLLBACK SEGMENT rsone STORAGE (NEXT 1000 MAXEXTENTS 20);
This statement attempts to resize a rollback segment to 100 megabytes:
ALTER ROLLBACK SEGMENT rsone SHRINK TO 100 M;
7-80
SQL Reference
ALTER SEQUENCE
ALTER SEQUENCE
Syntax
INCREMENT MAXVALUE
BY
integer
integer
NOMAXVALUE MINVALUE schema ALTER SEQUENCE . sequence NOMINVALUE CYCLE NOCYCLE CACHE NOCACHE ORDER NOORDER integer ; integer
Purpose
To change the increment, minimum and maximum values, cached numbers, and behavior of an existing sequence. This statement affects only future sequence numbers. For additional information on sequences, see "CREATE SEQUENCE" on page 4-371.
Prerequisites
The sequence must be in your own schema, or you must have the ALTER object privilege on the sequence, or you must have the ALTER ANY SEQUENCE system privilege.
Keywords and Parameters
The keywords and parameters in this statement serve the same purposes described in "CREATE SEQUENCE" on page 4-371. In addition:
SQL Statements 7-81
ALTER SEQUENCE
s
To restart the sequence at a different number, you must drop and re-create it (see "DROP SEQUENCE" on page 7-497). If you change the INCREMENT BY value before the first invocation of NEXTVAL, some sequence numbers will be skipped. Therefore, if you want to retain the original START WITH value, you must drop the sequence and re-create it with the original START WITH value and the new INCREMENT BY value. Oracle performs some validations. For example, a new MAXVALUE cannot be imposed that is less than the current sequence number.
s
s
Examples
This statement sets a new maximum value for the ESEQ sequence:
ALTER SEQUENCE eseq MAXVALUE 1500;
This statement turns on CYCLE and CACHE for the ESEQ sequence:
ALTER SEQUENCE eseq CYCLE CACHE 5;
7-82
SQL Reference
ALTER SESSION
7SQL Statements
ALTER SESSION
Syntax
COMMIT ADVISE ROLLBACK NOTHING CLOSE ENABLE COMMIT ALTER SESSION DISABLE ENABLE DISABLE FORCE set_clause PARALLEL DML DDL QUERY PARALLEL integer IN PROCEDURE ; DATABASE LINK dblink
set_clause::=
SET
parameter_name
=
parameter_value
Purpose
To specify or modify any of the conditions or parameters that affect your connection to the database. The statement stays in effect until you disconnect from the database.
Prerequisites
To enable and disable the SQL trace facility, you must have ALTER SESSION system privilege. You do not need any privileges to perform the other operations of this statement unless otherwise indicated.
SQL Statements 7-83
ALTER SESSION
Keywords and Parameters
ADVISE sends advice to a remote database to force a distributed transaction. The advice appears in the ADVICE column of the DBA_2PC_PENDING view on the remote database (the value 'C' for COMMIT, 'R' for ROLLBACK, and ' ' for NOTHING). If the transaction becomes in doubt, the administrator of that database can use this advice to decide whether to commit or roll back the transaction. You can send different advice to different remote databases by issuing 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. For more information on distributed transactions and how to decide whether to commit or roll back in-doubt distributed transactions, see Oracle8i Distributed Database Systems. CLOSE DATABASE LINK closes the database link dblink. When you issue a statement that uses a database link, Oracle creates a session for you on the remote database using that 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. If you want to reduce the network overhead associated with keeping the link open, use this clause to close the link explicitly if you do not plan to use it again in your session. You must first close all cursors that use the link and then end your current transaction if it uses the link. Procedures and stored functions written in PL/SQL can issue COMMIT and ROLLBACK statements. If your application would be disrupted by a COMMIT or ROLLBACK statement not issued directly by the application itself, use the DISABLE form of this clause to prevent procedures and stored functions called during your session from issuing these statements. You can subsequently allow procedures and stored functions to issue COMMIT and ROLLBACK statements in your session by issuing the ENABLE form of this clause. Some applications (such as SQL*Forms) automatically prohibit COMMIT and ROLLBACK statements in procedures and stored functions. Refer to your application documentation. Note: This statement does not apply to database triggers. Triggers can never issue COMMIT or ROLLBACK statements. PARALLEL DML specifies whether all subsequent DML, DDL, or query statements in the session will be | DDL | QUERY considered for parallel execution. This clause enables you to override the degree of parallelism of tables during the current session without changing the tables themselves. You can execute this clause for DML only between committed transactions. Uncommitted transactions must either be committed or rolled back prior to executing this clause for DML. ENABLE executes subsequent statements in the session in parallel. This is the default for DDL and query statements.
ENABLE | DISABLE COMMIT IN PROCEDURE
7-84
SQL Reference
ALTER SESSION
s
DML: executes the session's DML statements in parallel mode if a parallel hint or a parallel clause is specified. DDL: executes the session's DDL statements in parallel mode if a parallel clause is specified. QUERY: executes the session's queries in parallel mode if a parallel hint or a parallel clause is specified
s
s
Restriction: You cannot specify the optional PARALLEL integer with ENABLE. DISABLE specifies that subsequent statements will be executed serially. This is the default for DML statements.
s s s
DML: executes the session's DML statements serially. DDL: executes the session's DDL statements serially. QUERY: executes the session's queries serially.
Restriction: You cannot specify the optional PARALLEL integer with DISABLE. FORCE forces parallel execution of subsequent statements in the session. If no parallel clause or hint is specified, then a default degree of parallelism is used. This clause overrides any parallel_clause specified in subsequent statements in the session, but is overridden by a parallel hint.
s
DML: provided no parallel DML restrictions are violated, executes subsequent DML statements in the session with the default degree of parallelism, unless a specific degree is specified in this clause. DDL: executes subsequent DDL statements in the session with the default degree of parallelism, unless a specific degree is specified in this clause. Resulting database objects will have associated with them the prevailing degree of parallelism. Using FORCE DDL automatically causes all tables created in this session to be created with a default level of parallelism. The effect is the same as if you had specified the parallel_clause (with default degree) with the CREATE TABLE statement.
s
s
QUERY: executes subsequent queries with the default degree of parallelism, unless a specific degree is specified in this clause. PARALLEL integer: explicitly specifies a degree of parallelism - For force DDL, the degree overrides any parallel clause in subsequent DDL statments. - For force DML and QUERY, the degree overrides the degree currently stored for the table in the data dictionary. - A degree specified in a statement through a hint will override the degree being forced.
s
SQL Statements 7-85
ALTER SESSION
The following types of DML operations are not parallelized regardless of this clause:
s s s s
Operations on clustered tables Operations with embedded functions that either write or read database or package states Operations on tables with triggers that could fire Operations on tables or schema objects containing object types, or LONG or LOB datatypes.
For a detailed description of parallel DML features and hints, see Oracle8i Designing and Tuning for Performance. set_clause sets the session parameters that follow. You can set values for multiple parameters in the same set_clause. CAUTION: Unless otherwise indicated, the parameters described here are initialization parameters, and the descriptions indicate only the general nature of the parameters. Before changing the values of initialization parameters, please refer to their full description in Oracle8i Reference or Oracle8i National Language Support Guide. CONSTRAINT{S} = {IMMEDIATE | DEFERRED | DEFAULT } determines when conditions specified by a deferrable constraint are enforced. CONSTRAINT{S} is a session parameter only, not an initialization parameter.
s
IMMEDIATE indicates that the conditions specified by the deferrable constraint are checked immediately after each DML statement. This setting is equivalent to issuing the SET CONSTRAINTS ALL IMMEDIATE statement at the beginning of each transaction in your session. See the IMMEDIATE parameter of "SET CONSTRAINT(S)" on page 7-598. DEFERRED indicates that the conditions specified by the deferrable constraint are checked when the transaction is committed. This setting is equivalent to issuing the SET CONSTRAINTS ALL DEFERRED statement at the beginning of each transaction in your session. See the DEFERRED parameter of "SET CONSTRAINT(S)" on page 7-598. DEFAULT restores all constraints at the beginning of each transaction to their initial state of DEFERRED or IMMEDIATE.
s
s
CREATE_STORED_OUTLINES = { TRUE | FALSE | 'category_name' } determines whether Oracle should automatically create and store an outline for each query submitted during the session. CREATE_STORED_OUTLINES is not an initialization parameter.
s
TRUE enables automatic outline creation for subsequent queries in the same session. These outlines receive a unique system-generated name and are stored in the DEFAULT category. If a particular query already has an outline defined for it in the DEFAULT category, that outline will remain and a new outline will not be created. FALSE disables automatic outline creation during the session. This is the default. category_name has the same behavior as TRUE except that any outline created during the session is stored in the category_name category.
s s
7-86
SQL Reference
ALTER SESSION
CURRENT_SCHEMA = schema changes the current schema of the session to the specified schema. Subsequent unqualified references to schema objects during the session will resolve to objects in the specified schema. The setting persists for the duration of the session or until you issue another ALTER SESSION SET CURRENT_SCHEMA statement. CURRENT_SCHEMA is a session parameter only, not an initialization parameter. This setting offers a convenient way to perform operations on objects in a schema other than that of the current user without having to qualify the objects with the schema name. This setting changes the current schema, but it does not change the session user or the current user, nor does it give you any additional system or object privileges for the session. For more information on this parameter, see Oracle8i Application Developer's Guide - Fundamentals. CURSOR_SHARING = {FORCE | EXACT} determines what kind of SQL statements can share the same cursors.
s s
EXACT causes only identical SQL statements to share a cursor. FORCE forces statements that may differ in some literals, but are otherwise identical, to share a cursor, unless the literals affect the meaning of the statement.
See Also: Oracle8i Designing and Tuning for Performance for information on setting this parameter in these and other environments. DB_BLOCK_CHECKING = {TRUE | FALSE} controls whether data block checking is done. The default is FALSE. DB_FILE_MULTIBLOCK_READ_COUNT = integer specifies with integer the maximum number of blocks read in one I/O operation during a sequential scan. The default is 8. FAST_START_IO_TARGET = integer specifies the target number of I/Os (reads and writes) to and from buffer cache that Oracle should perform upon crash or instance recovery. Oracle continuously calculates the actual number of I/Os that would be needed for recovery and compares that number against the target. If the actual number is greater than the target, Oracle attempts to write additional dirty buffers to advance the checkpoint, while minimizing the affect on performance. For information on how to tune this parameter, see Oracle8i Designing and Tuning for Performance.
SQL Statements 7-87
ALTER SESSION
FLAGGER = { ENTRY | INTERMEDIATE | FULL | OFF } specifies FIPS flagging, which causes an error message to be generated when a SQL statement issued is an extension of ANSI SQL92. FLAGGER is a session parameter only, not an initialization parameter. In Oracle, there is currently no difference between Entry, Intermediate, or Full level flagging. Once flagging is set in a session, a subsequent ALTER SESSION SET FLAGGER statement will work, but generates the message, ORA-00097. This allows FIPS flagging to be altered without disconnecting the session. OFF turns off flagging. GLOBAL_NAMES = { TRUE | FALSE } When you start an instance, Oracle determines whether to enforce global name resolution for remote objects accessed in SQL statements based on the value of the initialization parameter GLOBAL_NAMES. This parameter enables or disables global name resolution for the duration of the session. TRUE enables the enforcement of global names. FALSE disables the enforcement of global names. You can also enable or disable global name resolution for your instance with the GLOBAL_NAMES parameter of the ALTER SYSTEM statement. Oracle recommends that you enable global name resolution if you use or plan to use distributed processing. For more information on global name resolution and how Oracle enforces it, see "Referring to Objects in Remote Databases" on page 2-79 and Oracle8i Distributed Database Systems. HASH_AREA_SIZE = integer specifies in bytes the amount of memory to use for hash join operations. The default is twice the value of the SORT_AREA_SIZE initialization parameter. HASH_JOIN_ENABLED = {TRUE | FALSE} enables or disables the use of the hash join operation in queries. The default is TRUE, which enables hash joins. HASH_MULTIBLOCK_IO_COUNT = integer specifies the number of data blocks to read and write during a hash join operation. The value multiplied by the DB_BLOCK_SIZE initialization parameter should not exceed 64 K. The default value for this parameter is 1. If the multi-threaded server is used, the value is always 1, and any value specified here is ignored. INSTANCE = integer in a parallel server, accesses database files as if the session were connected to the instance specified by integer. INSTANCE is a session parameter only, not an initialization parameter. For optimum performance, each instance of a parallel server uses its own private rollback segments, freelist groups, and so on. In a parallel server, you normally connect to a particular instance and access data that is partitioned primarily for your use. If you must connect to another instance, the data partitioning can be lost. Setting this parameter lets you access an instance as if you were connected to your own instance.
7-88
SQL Reference
ALTER SESSION
ISOLATION_LEVEL = { SERIALIZABLE | READ COMMITTED } specifies how transactions containing database modifications are handled. ISOLATION_ LEVEL is a session parameter only, not an initialization parameter.
s
SERIALIZABLE indicates that transactions in the session use the serializable transaction isolation mode as specified in SQL92. That is, if a serializable transaction attempts to execute a DML statement that updates rows currently being updated by another uncommitted transaction at the start of the serializable transaction, then the DML statement fails. A serializable transaction can see its own updates. READ COMMITTED indicates that transactions in the session will use the default Oracle transaction behavior. Thus, if the transaction contains DML that requires row locks held by another transaction, then the DML statement will wait until the row locks are released.
s
LOG_ARCHIVE_DEST_n = {null_string | {LOCATION=local_pathname | SERVICE=tnsnames_service} [MANDATORY | OPTIONAL] [REOPEN[=integer]]} specifies up to five session-specific valid operating system pathnames or Oracle service names (plus other related options) as destinations for archive redo log file groups (n = integers 1 through 5). For a description of the options, refer to Oracle8i Reference. Restrictions: If you set a value for this parameter,
s
You cannot have definitions for the parameters LOG_ARCHIVE_DEST and LOG_ ARCHIVE_DUPLEX_DEST in your initialization parameter file, nor can you set values for those parameters with the ALTER SYSTEM statement. You cannot start archiving to a specific location using the ALTER SYSTEM ARCHIVE LOG TO location statement.
s
LOG_ARCHIVE_DEST_STATE_n = {ENABLE | DEFER} specifies the session-specific state associated with the corresponding LOG_ARCHIVE_DEST_n parameter.
s
ENABLE specifies that any associated valid destination can be used for archiving. This is the default. DEFER specifies that Oracle will not consider for archiving any destination associated with the corresponding LOG_ARCHIVE_DEST_n parameter.
s
LOG_ARCHIVE_MIN_SUCCEED_DEST = integer specifies the session-specific minimum number of destinations that must succeed in order for the online log file to be available for reuse.
SQL Statements 7-89
ALTER SESSION
MAX_DUMP_FILE_SIZE = { size | UNLIMITED } specifies the upper limit of trace dump file size. Specify the maximum size as either a nonnegative integer that represents the number of blocks, or as UNLIMITED. If you specify UNLIMITED, no upper limit is imposed. NLS parameters: When you start an instance, Oracle establishes support based on the values of initialization parameters that begin with "NLS". You can query the dynamic performance table V$NLS_PARAMETERS to see the current NLS attributes for your session. For more information about NLS parameters, see Oracle8i National Language Support Guide. NLS_CALENDAR = 'text' explicitly specifies a new calendar type. NLS_COMP = 'text' specifies that linguistic comparison is to be used according to the NLS_SORT parameter. This parameter obviates the need to specify NLS_SORT in SQL statements. NLS_CURRENCY = 'text' explicitly specifies a new value for the L number format element (the local currency symbol). The symbol cannot exceed 10 characters. NLS_DATE_FORMAT = 'fmt' explicitly specifies a new default date format. The 'fmt' value must be a date format model as specified in the section "Date Format Elements" on page 2-45. NLS_DATE_LANGUAGE = language explicitly changes the language for names and abbreviations of days and months, and for spelled-out values of other date format elements. NLS_DUAL_CURRENCY = 'text' explicitly specifies a new "Euro" (or other) dual currency symbol. The value of text is returned by the number format element U (see "Number Format Elements" on page 2-41); text cannot exceed 10 characters. NLS_ISO_CURRENCY = territory explicitly specifies the territory whose ISO currency symbol should be used. That territory's currency symbol then becomes the value of the C number format element. NLS_LANGUAGE = language changes the language in which Oracle returns errors and other messages. This parameter also implicitly specifies new values for these items:
7-90
SQL Reference
ALTER SESSION
s
Language for day and month names and abbreviations and spelled values of other elements Linguistic sort sequences or binary sorts B.C. and A.D. indicators A.M. and P.M. meridian indicators
s s s
NLS_NUMERIC_CHARACTERS = 'text' explicitly specifies a new decimal character and group separator. The 'text' value must have this form: 'dg' where: d is the new decimal character, and g is the new group separator. The decimal character and the group separator must be two different single-byte characters, and cannot be a numeric value or any of the following characters: plus sign ("+"), minus sign or hyphen ("" ), less-than sign ("<"), or greater-than sign (">"). If the decimal character is not a period (.), you must use single quotation marks to enclose all number values that appear in expressions in your SQL statements. When not using a period for the decimal point, use the TO_NUMBER function to ensure that a valid number is retrieved. NLS_SORT = { sort | BINARY} changes the sequence into which Oracle sorts character values. sort specifies the name of a linguistic sort sequence. BINARY specifies a binary sort. The default is BINARY. NLS_TERRITORY = territory implicitly specifies new values for these items:
s s s s s
Default date format Decimal character and group separators Local currency symbol ISO currency symbol First day of the week for D date format element
OBJECT_CACHE_MAX_SIZE_PERCENT = integer specifies the percentage of the optimal cache size that the session object cache can grow beyond the optimal size. The default is 10. OBJECT_CACHE_OPTIMAL_SIZE = integer specifies (in kilobytes) the size to which the session object cache is reduced when it exceeds maximum size. The default is 100.
SQL Statements 7-91
ALTER SESSION
OPTIMIZER_INDEX_CACHING = integer lets you tune the optimizer to favor nested loops joins and IN-list iterators. The value of integer indicates the percentage of the index blocks assumed to be in the cache. OPTIMIZER_INDEX_COST_ADJ = integer let you tune optimizer behavior for access path selection to make the optimizer more likely to select an index access path than a full table scan. The value of integer is a percentage indicating the importance the optimizer attaches to the index path compared with "normal". The default is 100 (indicating 100%), which makes the optimizer cost index access paths at the regular cost. OPTIMIZER_MAX_PERMUTATIONS = integer lets you limit the amount of work the optimizer expends on optimizing queries with large joins. The value of integer is the number of permutations of the tables the optimizer will consider with large joins. OPTIMIZER_MODE = { ALL_ROWS | FIRST_ROWS | RULE | CHOOSE } specifies the approach and mode of the optimizer for your session. For information on how to choose a goal for the cost-based approach based on the characteristics of your application, see Oracle8i Concepts and Oracle8i Designing and Tuning for Performance.
s s s
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. RULE specifies the rule-based approach. (The rule-based optimizer does not use function-based indexes.) CHOOSE causes the optimizer to choose an optimization approach based on the presence of statistics in the data dictionary.
s
OPTIMIZER_PERCENT_PARALLEL = integer specifies the amount of parallelism the optimizer uses in its cost functions. The default is 0 (no parallelism). PARALLEL_BROADCAST_ENABLED = { TRUE | FALSE } lets you enhance performance during hash and merge joins. PARALLEL_INSTANCE_GROUP = ' text ' identifies the parallel instance group to be used for spawning parallel query slaves. The default is all active instances. Set this parameter only if you are running Oracle Parallel Server in parallel mode. PARALLEL_MIN_PERCENT = integer specifies the minimum percent of threads required for parallel query. The default is 0 (no parallelism).
7-92
SQL Reference
ALTER SESSION
PARTITION_VIEW_ENABLED = { TRUE | FALSE } When set to TRUE, this parameter causes the optimizer to skip unnecessary table accesses in a partition view. Note: For important information on partition views, see "Partition Views" on page 7-457. PLSQL_V2_COMPATIBILITY = { TRUE | FALSE } if TRUE, modifies the compile-time behavior of PL/SQL programs to allow language constructs that are illegal in Oracle8 and Oracle8i (PL/SQL V3), but were legal in Oracle7 (PL/SQL V2). FALSE disallows illegal Oracle7 PL/SQL V2 constructs. This is the default. See the PL/SQL User's Guide and Reference and Oracle8i Reference for more information about this session parameter. QUERY_REWRITE_ENABLED = { TRUE | FALSE } enables or disables query rewrite on all materialized views that have not been explicitly disabled. Query rewrite is disabled by default. It is also disabled by rule-based optimization (that is, if the OPTIMIZER_MODE parameter is set to RULE). For more information on query rewrite, see Oracle8i Data Warehousing Guide. This parameter has the following additional effect on the use of function-based indexes:
s
If this parameter is set to TRUE, Oracle will use function-based indexes to derive values of SQL expressions. If in addition the QUERY_REWRITE_INTEGRITY parameter is set to any value other than ENFORCED, Oracle will derive such values even if the index is based on a user-defined (rather than SQL) function. If this parameter is set to FALSE, Oracle will not use function-based indexes to derive values of SQL expressions, but it will use such indexes to obtain values of real columns in the index.
s
Enabling or disabling query rewrite does not affect descending indexes. A setting of TRUE has no effect on materialized views that cannot be created with the ENABLE QUERY REWRITE clause, such as materialized views created totally or in part from a view. QUERY_REWRITE_INTEGRITY = { ENFORCED | TRUSTED | STALE_TOLERATED } sets the minimum consistency level for query rewrite. The following values are permitted:
SQL Statements 7-93
ALTER SESSION
s
ENFORCED is the safest level. It relies only on system-enforced relationships so that data integrity and correctness can be guaranteed. This level ensures that query rewrite will not use any function-based index or any materialized view that includes a call to a userdefined function. In addition, this level ensures that query rewrite will not use any dimensional information or any constraints enabled with the RELY keyword.
s
TRUSTED specifies that materialized views created with the ON PREBUILT TABLE clause are supported, and trusted but unenforced join relationships are accepted. Query rewrite uses join information from dimensions and enables unenforced constraints with the RELY keyword. STALE_TOLERATED specifies that any stale, usable materialized view may be used.
s
This parameter does not affect descending indexes. For more information on query rewrite integrity level, see Oracle8i Data Warehousing Guide. For information on dimensions, see "CREATE DIMENSION" on page 7-277. For information on constraints enabled with the RELY keyword, see "constraint_clause" on page 7-233. REMOTE_DEPENDENCIES_MODE = { TIMESTAMP | SIGNATURE } specifies how dependencies of remote stored procedures are handled by the session. For more information, refer to Oracle8i Application Developer's Guide - Fundamentals. SESSION_CACHED_CURSORS = integer specifies the number of frequently used cursors that can be retained in the cache. The cursors can be open or closed, which is particularly useful for Oracle tools that close all session cursors associated with a form when switching to another form. In such cases, frequently used cursors do not have to be reparsed. A least recently used algorithm ages out entries in the cache to make room for new entries when needed. For more information on session cursor caching, see Oracle8i Designing and Tuning for Performance. SKIP_UNUSABLE_INDEXES = { TRUE | FALSE } controls the use and reporting of tables with unusable indexes or index partitions. SKIP_ UNUSABLE_INDEXES is a session parameter only, not an initialization parameter.
s
TRUE disables error reporting of indexes and index partitions marked UNUSABLE. Allows all operations (inserts, deletes, updates, and selects) to tables with unusable indexes or index partitions. Note: Statements that would normally use the unusable indexes or index partitions may be compiled with suboptimal optimizer plans, occasionally resulting in major degradation in response time and resource utilization.
s
FALSE enables error reporting of indexes marked UNUSABLE. Does not allow inserts, deletes, and updates to tables with unusable indexes or index partitions. This is the default.
7-94
SQL Reference
ALTER SESSION
SORT_AREA_RETAINED_SIZE = integer specifies (in bytes) the maximum amount of memory that each sort operation will retain after the first fetch is done, until the cursor ends. If you do not explicitly set this parameter in the initialization parameter file or dynamically, Oracle uses the value of the SORT_AREA_SIZE parameter. SORT_AREA_SIZE = integer specifies (in bytes) the maximum amount of memory to use for each sort operation. The default is OS-dependent. SORT_MULTIBLOCK_READ_COUNT = integer specifies the number of database blocks to read each time a sort performs a read from temporary segments. The default is 2. SQL_TRACE = { TRUE | FALSE } The SQL trace facility generates performance statistics for the processing of SQL statements. 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 own session with the SQL_TRACE parameter of the ALTER SESSION statement. TRUE enables the SQL trace facility. FALSE disables it. SQL_TRACE is an initialization parameter. However, when you change its value with an ALTER SESSION statement, the results are not reflected in the V$PARAMETER view. Therefore, in this context it is considered a session parameter only. See Also: Oracle8i Designing and Tuning for Performance for more information on the SQL trace facility, including how to format and interpret its output. STAR_TRANSFORMATION_ENABLED = { TRUE | FALSE } determines whether a cost-based query transformation will be applied to star queries. The default is FALSE. TIMED_STATISTICS = {TRUE | FALSE } specifies whether the server requests the time from the operating system when generating time-related statistics. The default is FALSE. USE_STORED_OUTLINES = { TRUE | FALSE | 'category_name' } determines whether the optimizer will use stored outlines to generate execution plans. USE_ STORED_OUTLINES is not an initialization parameter.
s
TRUE causes the optimizer to use outlines stored in the DEFAULT category when compiling requests. FALSE specifies that the optimizer should not use stored outlines. This is the default. category_name causes the optimizer to use outlines stored in the category_name category when compiling requests.
s s
SQL Statements 7-95
ALTER SESSION
Examples
PARALLEL Example
Issue the following statement to enable parallel DML mode
for the current session:
ALTER SESSION ENABLE PARALLEL DML;
ADVISE Example The following 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.
CLOSE DATABASE LINK Example This statement 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;
7-96
SQL Reference
ALTER SESSION
Date Format Example
The following statement dynamically changes the default date format for your session to 'YYYY MM DD-HH24:MI:SS':
ALTER SESSION 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 ------------------1997 08 12 14:25:56
Date Language Example The following statement changes the language for date
format elements to French:
ALTER SESSION SET NLS_DATE_LANGUAGE = French; SELECT TO_CHAR(SYSDATE, 'Day DD Month YYYY') Today FROM DUAL; TODAY --------------------------Mardi 28 Fvrier 1997
ISO Currency Example The following statement dynamically changes the ISO
currency symbol to the ISO currency symbol for the territory America:
ALTER SESSION SET NLS_ISO_CURRENCY = America; SELECT TO_CHAR( SUM(sal), 'C999G999D99') Total FROM emp; TOTAL ------------USD29,025.00
Decimal Character and Group Separator Example The following statement
dynamically changes the decimal character to comma (,) and the group separator to period (.):
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ',.' ;
SQL Statements 7-97
ALTER SESSION
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
NLS Currency Example The following statement dynamically changes the local
currency symbol to 'DM':
ALTER SESSION SET NLS_CURRENCY = 'DM'; SELECT TO_CHAR( SUM(sal), 'L999G999D99') Total FROM emp; TOTAL ------------DM29.025,00
NLS Language Example The following statement dynamically changes to French the language in which error messages are displayed:
ALTER SESSION SET NLS_LANGUAGE = FRENCH; SELECT * FROM DMP; ORA-00942: Table ou vue inexistante
Linguistic Sort Example The following 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.
SQL Trace Example To enable the SQL trace facility for your session, issue the
following statement:
ALTER SESSION SET SQL_TRACE = TRUE;
7-98
SQL Reference
ALTER SESSION
This statement enables query rewrite in the current session for all materialized views that have not been explicitly disabled:
Query Rewrite Example
ALTER SESSION SET QUERY_REWRITE_ENABLED = TRUE;
SQL Statements 7-99
ALTER SNAPSHOT
ALTER SNAPSHOT
In Oracle8i, "snapshots" are synonymous with "materialized views." Please see "ALTER MATERIALIZED VIEW / SNAPSHOT" on page 7-47.
7-100 SQL Reference
ALTER SNAPSHOT LOG
ALTER SNAPSHOT LOG
In Oracle8i, "snapshots" are synonymous with "materialized views." Please see "ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG" on page 7-58.
SQL Statements
7-101
ALTER SYSTEM
ALTER SYSTEM
Syntax
archive_log_clause GLOBAL LOCAL CHECKPOINT GLOBAL LOCAL CHECK ENABLE DISTRIBUTED DISABLE ALTER SYSTEM ENABLE RESTRICTED DISABLE FLUSH SHARED_POOL SESSION ; RECOVERY DATAFILES
end_session_clauses SWITCH SUSPEND RESUME IMMEDIATE SHUTDOWN set_clause dispatcher_name LOGFILE
end_session_clauses::=
POST_TRANSACTION DISCONNECT KILL SESSION SESSION ' ' integer1 integer1 , , integer2 integer2 ' ' IMMEDIATE
7-102 SQL Reference
ALTER SYSTEM
archive_log_clause::=
THREAD ARCHIVE LOG integer integer integer
SEQUENCE CHANGE CURRENT GROUP LOGFILE NEXT ALL START STOP
integer ' filename '
TO
'
location
'
set_clause::=
SET
parameter_name
=
parameter_value
Purpose
To dynamically alter your Oracle instance. The settings stay in effect as long as the database is mounted.
Prerequisites
You must have ALTER SYSTEM system privilege. To specify the archive_log_clause, you must have the OSDBA or OSOPER role enabled.
Keywords and Parameters
archive_log_ clause manually archives redo log files or enables or disables automatic archiving. To use this clause, your instance must have the database mounted. The database can be either open or closed unless otherwise noted.
SQL Statements
7-103
ALTER SYSTEM
Notes:
s
You can also manually archive redo log file groups with the ARCHIVE LOG SQL*Plus statement. For information on this statement, see the SQL*Plus User's Guide and Reference. You can also have Oracle archive redo log files groups automatically. For information on automatic archiving, see Oracle8i Administrator's Guide. You can always manually archive redo log file groups regardless of whether automatic archiving is enabled. specifies the thread containing the redo log file group to be archived. Set this parameter only if you are using Oracle with the Parallel Server option in parallel mode. 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. 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 use this clause only when your instance has the database open. manually archives the current redo log file group of the specified thread, forcing a log switch. If you omit the THREAD parameter, Oracle archives all redo log file groups from all enabled threads, including logs previous to current logs. You can use this clause only when your instance has the database open.
s
THREAD
SEQUENCE
CHANGE
CURRENT
Note: If you specify a redo log file group for archiving with the CHANGE or CURRENT clause, and earlier redo log file groups are not yet archived, Oracle archives all unarchived groups up to and including the specified group. GROUP manually archives the online redo log file group with the GROUP value specified by integer. 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. 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. Restriction: You must archive redo log file groups in the order in which they are filled. If you specify a redo log file group for archiving with the LOGFILE parameter, and earlier redo log file groups are not yet archived, Oracle returns an error.
LOGFILE
7-104 SQL Reference
ALTER SYSTEM
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. 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. enables automatic archiving of redo log file groups. Restriction: You can enable automatic archiving only for the thread assigned to your instance.
ALL
START
TO 'location'
specifies the primary location to which the redo log file groups are 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 parameters LOG_ARCHIVE_DEST or LOG_ ARCHIVE_DEST_n. Note: You can enhance recovery reliability by setting the related archive parameters LOG_ARCHIVE_DEST_DUPLEX and LOG_ARCHIVE_MIN_ SUCCEED_DEST.
STOP CHECKPOINT
disables automatic archiving of redo log file groups. You can disable automatic archiving only for the thread assigned to your instance.
explicitly forces Oracle to perform a checkpoint, ensuring that all changes made by committed transactions are written to datafiles on disk. You can specify this clause only when your instance has the database open. Oracle does not return control to you until the checkpoint is complete. GLOBAL LOCAL in an Oracle Parallel Server environment, performs a checkpoint for all instances that have opened the database. This is the default. in an Oracle Parallel Server environment, performs a checkpoint only for the thread of redo log file groups for your instance.
See Also: Oracle8i Concepts for more information on checkpoints. CHECK DATAFILES in a distributed database system, such as an Oracle Parallel Server environment, updates an instance's SGA from the database control file to reflect information on all online datafiles. GLOBAL LOCAL performs this synchronization for all instances that have opened the database. This is the default. performs this synchronization only for the local instance.
Your instance should have the database open. See Also: Oracle8i Parallel Server Setup and Configuration Guide.
SQL Statements
7-105
ALTER SYSTEM
DISCONNECT SESSION
disconnects the current session by destroying the dedicated server process (or virtual circuit if the connection was made by way of a multi-threaded server). To use this clause, your instance must have the database open. You must identify the session with both of the following values from the V$SESSION view: integer1 integer2 is the value of the SID column. is the value of the SERIAL# column.
If system parameters are appropriately configured, application failover will take effect. See Also: Oracle8i Parallel Server Setup and Configuration Guide for more information about application failover. POST_ TRANSACTION IMMEDIATE allows ongoing transactions to complete before the session is disconnected. If the session has no ongoing transactions, this clause has the same effect as KILL SESSION, described below. disconnects the session and recovers the entire session state immediately, without waiting for ongoing transactions to complete.
s
If you also specify POST_TRANSACTION and the session has ongoing transactions, the IMMEDIATE keyword is ignored. If you do not specify POST_TRANSACTION, or you specify POST_ TRANSACTION but the session has no ongoing transactions, this clause has the same effect as KILL SESSION IMMEDIATE, described below.
s
DISTRIBUTED RECOVERY
specifies whether or not distributed recovery is enabled. To use this clause, your instance must have the database open. ENABLE enables distributed recovery. In a single-process environment, you must use this clause to initiate distributed recovery. You may need to issue the ENABLE DISTRIBUTED RECOVERY statement more than once to recover an in-doubt transaction if the remote node involved in the transaction is not accessible. In-doubt transactions appear in the data dictionary view DBA_2PC_PENDING. See Also: Oracle8i Distributed Database Systems for more information about distributed transactions and distributed recovery. DISABLE disables distributed recovery.
RESTRICTED SESSION
specifies whether logon to Oracle is restricted ENABLE DISABLE allows only users with RESTRICTED SESSION system privilege to log on to Oracle. Existing sessions are not terminated. reverses the effect of the ENABLE RESTRICTED SESSION clause, allowing all users with CREATE SESSION system privilege to log on to Oracle. This is the default.
7-106 SQL Reference
ALTER SYSTEM
You can use this clause regardless of whether your instance has the database dismounted or mounted, open or closed. FLUSH SHARED_ clears all data from the shared pool in the system global area (SGA). The shared pool stores POOL s Cached data dictionary information and
s
Shared SQL and PL/SQL areas for SQL statements, stored procedures, function, packages, and triggers.
This statement does not clear shared SQL and PL/SQL areas for items that are currently being executed. You can use this clause regardless of whether your instance has the database dismounted or mounted, open or closed. KILL SESSION marks a session as dead, rolls back ongoing transactions, releases all session locks, and partially recovers session resources. To use this clause, your instance must have the database open, and your session and the session to be killed must be on the same instance. You must identify the session with both of the following values from the V$SESSION view: integer1 integer2 is the value of the SID column. is the value of the SERIAL# column.
If the session 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, marks the session as dead, and then returns control to you. If the waiting lasts a minute, Oracle marks the session to be killed and returns control to you with a message that the session is marked to be killed. The PMON background process then marks the session as dead when the activity is complete. Whether or not the session has an ongoing transaction, Oracle does not recover the entire session state until the session user issues a request to the session and receives a message that the session has been killed. IMMEDIATE SWITCH LOGFILE rolls back ongoing transactions, releases all session locks, recovers the entire session state, and returns control to you immediately.
explicitly forces Oracle to begin writing to a new redo log file group, regardless of whether the files in the current redo log file group are full. When you force a log switch, Oracle begins to perform a checkpoint. Oracle returns control to you immediately rather than when the checkpoint is complete. To use this clause, your instance must have the database open. suspends all I/O (datafile, control file, and file header) as well as queries, in all instances, enabling you to make copies of the database without having to handle ongoing transactions. Restrictions:
s s
SUSPEND
Do not use this clause unless you have put the database tablespaces in hot backup mode. If you start a new instance while the system is suspended, that new instance will not be suspended.
SQL Statements
7-107
ALTER SYSTEM
RESUME
makes the database available once again for queries and I/O. See Also: Oracle8i Backup and Recovery Guide for more information on the SUSPEND clause and RESUME clause.
SHUTDOWN
This clause is relevant only if your system is using Oracle's multi-threaded server architecture. It shuts down a dispatcher identified by dispatcher_name. The dispatcher_name must be a string of the form 'Dxxx', where xxx indicates the number of the dispatcher. (For a listing of dispatcher names, query the NAME column of the V$DISPATCHER dynamic performance view.)
s
If you specify IMMEDIATE, the dispatcher stops accepting new connections immediately and Oracle terminates all existing connections through that dispatcher. After all sessions are cleaned up, the dispatcher process literally shuts down. If you do not specify IMMEDIATE, the dispatcher stops accepting new connections immediately but waits for all its users to disconnect and for all its database links to terminate. Then it literally shuts down.
s
See Also: Oracle8i Administrator's Guide, Net8 Administrator's Guide, and Oracle8i Designing and Tuning for Performance for more information on dispatchers and multi-threaded server architecture. set_clause sets the system parameters that follow. You can set values for multiple parameters in the same set_clause.The DEFERRED keyword sets or modifies the value of the parameter for future sessions that connect to the database. CAUTION: Unless otherwise noted, these parameters are initialization parameters, and the descriptions provided here indicate only the general nature of the parameters. Before changing the values of initialization parameters, please refer to their full description in Oracle8i Reference and Oracle8i National Language Support Guide. AQ_TM_PROCESSES = integer is an Advanced Queuing parameter that specifies whether a time manager process is created. Accepted values are 1 (creates one time manager process to monitor messages) and 0 (does not create a time manager process). BACKGROUND_DUMP_DEST = 'text' specifies the pathname for a directory where debugging trace files for the background processes are written during Oracle operations. BACKUP_TAPE_IO_SLAVES = {TRUE | FALSE} DEFERRED specifies whether I/O slaves are used by the Recovery Manager to back up, copy, or restore data to tape. CONTROL_FILE_RECORD_KEEP_TIME = integer specifies the minimum of days before a reusable record in the control file can be reused. CORE_DUMP_DEST = 'text'
7-108 SQL Reference
ALTER SYSTEM
specifies the directory where Oracle dumps core files. CREATE_STORED_OUTLINES = { TRUE | FALSE | 'category_name' } [NOOVERRIDE] determines whether Oracle should automatically create and store an outline for each query submitted on the system. CREATE_STORED_OUTLINES is not an initialization parameter.
s
TRUE enables automatic outline creation for subsequent queries in the system. These outlines receive a unique system-generated name and are stored in the DEFAULT category. If a particular query already has an outline defined for it in the DEFAULT category, that outline will remain and a new outline will not be created. FALSE disables automatic outline creation for the system. This is the default. category_name has the same behavior as TRUE except that any outline created in the system is stored in the category_name category. NOOVERRIDE specifies that this system setting will not override the setting for any session in which this parameter was explicitly set. If you do not specify NOOVERRIDE, this setting takes effect in all sessions.
s
s
s
CURSOR_SHARING = {FORCE | EXACT} determines what kind of SQL statements can share the same cursors.
s s
EXACT causes only identical SQL statements to share a cursor. FORCE forces statements that may differ in some literals, but are otherwise identical, to share a cursor, unless the literals affect the meaning of the statement.
See Also: for information on setting this parameter in these and other environments, see Oracle8i Designing and Tuning for Performance. DB_BLOCK_CHECKING = {TRUE | FALSE} DEFERRED controls whether data block checking is done. The default is FALSE, for compatibility with earlier releases where block checking is disabled as a default. DB_BLOCK_CHECKSUM = {TRUE | FALSE} specifies whether the database writer background process and the direct loader will calculate a checksum and store it in the cache header of every data lock when writing to disk. DB_BLOCK_MAX_DIRTY_TARGET = integer limits to integer the number of dirty buffers in the cache and reduces the number of buffers that will need to be read during crash or instance recovery. This parameter does not relate to media recovery. A value of 0 disables this parameter. The minimum accepted value to enable the parameter is 1000.
SQL Statements
7-109
ALTER SYSTEM
Note: Oracle Corporation recommends that Enterprise Edition users who were using incremental checkpointing in an earlier release now use fast-start checkpointing in Oracle8i. In fast-start checkpointing, the FAST_START_IO_TARGET parameter takes the place of DB_ FILE_MAX_DIRTY_TARGET. See FAST_START_IO_TARGET below. See also Oracle8i Backup and Recovery Guide for information on fast-start checkpointing and Oracle8i Reference for information on the new parameters. DB_FILE_DIRECT_IO_COUNT = integer DEFERRED specifies the number of blocks Oracle should use for I/O during backup, restore, or directpath read and write operations. DB_FILE_MULTIBLOCK_READ_COUNT = integer specifies the maximum number of blocks read in one I/O operation during a sequential scan. FAST_START_IO_TARGET = integer specifies the target number of I/Os (reads and writes) to and from buffer cache that Oracle should perform upon crash or instance recovery. Oracle continuously calculates the actual number of I/Os that would be needed for recovery and compares that number against the target. If the actual number is greater than the target, Oracle attempts to write additional dirty buffers to advance the checkpoint, while minimizing the affect on performance. For information on how to tune this parameter, see Oracle8i Designing and Tuning for Performance. FAST_START_PARALLEL_ROLLBACK = { FALSE | LOW | HIGH} specifies the number of processes spawned to perform parallel recovery.
s s
FALSE specifies no parallel recovery. SMON will serially recover dead transactions. LOW specifies that the number of recovery servers may not exceed twice the value of the CPU_COUNT parameter. HIGH specifies that the number of recovery servers may not exceed four times the value of the CPU_COUNT parameter.
s
FIXED_DATE = { 'DD_MM_YY' | 'YYYY_MI_DD_HH24_MI-SS' } specifies a constant date for SYSDATE instead of the current date. GC_DEFER_TIME = integer specifies the time (in hundredths of seconds) that Oracle waits before responding to forcedwrite requests from other instances. GLOBAL_NAMES = {TRUE | FALSE}
7-110 SQL Reference
ALTER SYSTEM
When you start an instance, Oracle determines whether to enforce global name resolution for remote objects accessed in SQL statements based on the value of the initialization parameter GLOBAL_NAMES. This system parameter enables or disables global name resolution while your instance is running. TRUE enables the enforcement of global names. FALSE disables the enforcement of global names. You can also enable or disable global name resolution for your session with the GLOBAL_NAMES parameter of the ALTER SESSION statement. Oracle recommends that you enable global name resolution if you use or plan to use distributed processing. See Also: "Referring to Objects in Remote Databases" on page 2-79 and Oracle8i Distributed Database Systems for more information on global name resolution and how Oracle enforces it. HASH_MULTIBLOCK_IO_COUNT = integer specifies the number of data blocks to read and write during a hash join operation. The value multiplied by the DB_BLOCK_SIZE initialization parameter should not exceed 64K. The default value for this parameter is 1. If the multi-threaded server is used, the value is always 1, and any value given here is ignored. HS_AUTOREGISTER = {TRUE | FALSE} enables or disables automatic self-registration of non-Oracle system characteristics in the Oracle server's data dictionary by Heterogeneous Services agents. See Also: Oracle8i Distributed Database Systems for more information on accessing non-Oracle systems through Heterogeneous Services. JOB_QUEUE_PROCESSES = integer specifies the number of job queue processes per instance (SNPn, where n is 0 to 9 followed by A to Z). Set this parameter to 1 or higher if you wish to have your snapshots updated automatically. One job queue process is usually sufficient unless you have many snapshots that refresh simultaneously. Oracle also uses job queue processes to process requests created by the DBMS_JOB package. See Also: Oracle8i Replication for more information on managing table snapshots. LICENSE_MAX_SESSIONS = integer resets (for the current instance) the value of the initialization parameter LICENSE_MAX_ SESSIONS, which 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. A value of 0 disables the limit. If you reduce the limit on sessions below the current number of sessions, Oracle does not end existing sessions to enforce the new limit. However, users without RESTRICTED SESSION system privilege can begin new sessions only when the number of sessions falls below the new limit. Do not disable or raise session limits unless you have appropriately upgraded your Oracle license. For more information, contact your Oracle sales representative.
SQL Statements
7-111
ALTER SYSTEM
LICENSE_MAX_USERS = integer resets (for the current instance) the value of the initialization parameter LICENSE_MAX_ USERS, which establishes the limit for users connected to your database. Once this limit is reached, more users cannot connect. A value of 0 disables the limit. Restriction: You cannot reduce the limit on users below the current number of users created for the database. Do not disable or raise user limits unless you have appropriately upgraded your Oracle license. For more information, contact your Oracle sales representative. LICENSE_SESSIONS_WARNING = integer resets (for the current instance) the value of the initialization parameter LICENSE_ SESSIONS_WARNING, which establishes a warning threshold for concurrent usage. Once this threshold is reached, Oracle writes warning messages to the database ALERT file for each subsequent session. Also, users with RESTICTED SESSION system privilege receive warning messages when they begin subsequent sessions. A value of 0 disables the warning threshold. 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. LOG_ARCHIVE_DEST = string specifies a valid operating system pathname as the primary destination for all archive redo log file groups. Restrictions: If you set a value for this parameter:
s
You cannot have a value for LOG_ARCHIVE_DEST_n in your initialization parameter file, nor can you set a value for that parameter using the ALTER SESSION or ALTER SYSTEM statement. You cannot set a value for the parameter LOG_ARCHIVE_MIN_SUCCEED_DEST using the ALTER SESSION statement.
s
LOG_ARCHIVE_DEST_n = {null_string | {LOCATION=local_pathname | SERVICE=tnsnames_service} [MANDATORY | OPTIONAL] [REOPEN[=integer]]} specifies up to five valid operating system pathnames or Oracle service names (plus other related options) as destinations for archive redo log file groups (n = integers 1 through 5). For a description of the options, refer to Oracle8i Reference.
7-112 SQL Reference
ALTER SYSTEM
Restrictions: If you set a value for this parameter:
s
You cannot have definitions for the parameters LOG_ARCHIVE_DEST or LOG_ARCHIVE_ DUPLEX_DEST in your initialization parameter file, nor can you set values for those parameters using the ALTER SYSTEM statement. You cannot start archiving to a specific location using the ALTER SYSTEM ARCHIVE LOG TO location statement.
s
LOG_ARCHIVE_DEST_STATE_n = {ENABLE | DEFER} specifies the state associated with the corresponding LOG_ARCHIVE_DEST_n parameter.
s
ENABLE specifies that any associated valid destination can be used for archiving. This is the default. DEFER specifies that Oracle will not consider for archiving any destination associated with the corresponding LOG_ARCHIVE_DEST_n parameter.
s
LOG_ARCHIVE_DUPLEX_DEST = string specifies a valid operating system pathname as the secondary destination for all archive redo log file groups. Restriction: If you set a value for this parameter:
s s
You must have a definition for LOG_ARCHIVE_DEST. You cannot have a value for the parameter LOG_ARCHIVE_DEST_n in your initialization parameter file, nor can you set a value for that parameter using the ALTER SYSTEM or ALTER SESSION statement. You cannot set a value for the parameter LOG_ARCHIVE_MIN_SUCCEED_DEST using the ALTER SESSION statement.
s
LOG_ARCHIVE_MAX_PROCESSES = integer specifies the number of archiver processes that are invoked. Permitted values are integers 1 through 10, inclusive. The default is 1. LOG_ARCHIVE_MIN_SUCCEED_DEST = integer specifies the minimum number of destinations that must succeed in order for the online log file to be available for reuse. LOG_ARCHIVE_TRACE = integer controls the type of output information generated by archivelog processes. See Also:
s
Oracle8i Backup and Recovery Guide for more information on using this parameter. Oracle8i Reference for a listing of valid values.
s
LOG_CHECKPOINT_INTERVAL = integer
SQL Statements
7-113
ALTER SYSTEM
limits to integer the number of redo blocks that can exist between an incremental checkpoint and the last block written to the redo log. LOG_CHECKPOINT_TIMEOUT = integer limits the incremental checkpoint to be at the position where the last write to the redo log (sometimes called the "tail of the log") was integer seconds ago, and signifies that no buffer will remain dirty (in the cache) for more than integer seconds. The default is 1800 seconds. MAX_DUMP_FILE_SIZE = { size | 'UNLIMITED'} [DEFERRED] specifies the trace dump file size upper limit for all user sessions. Specify the maximum size as either a nonnegative integer that represents the number of blocks, or as 'UNLIMITED'. If you specify 'UNLIMITED', no upper limit is imposed. Multi-Threaded Server Parameters: When you start your instance, Oracle creates shared server processes and dispatcher processes for the multi-threaded server architecture based on the values of the MTS_SERVERS and MTS_DISPATCHERS initialization parameters. You can set the MTS_SERVERS and MTS_DISPATCHERS session parameters to perform one of the following operations while the instance is running:
s s s
s
Create additional shared server processes by increasing the minimum number of shared server processes. Terminate existing shared server processes after their current calls finish processing. Create more dispatcher processes for a specific protocol, up to a maximum across all protocols specified by the initialization parameter MTS_MAX_DISPATCHERS. Terminate existing dispatcher processes for a specific protocol after their current user processes disconnect from the instance.
See Also:
s s s
Oracle8i Concepts Oracle8i Designing and Tuning for Performance Oracle8i Parallel Server Concepts.
MTS_DISPATCHERS = 'dispatch_clause' dispatch_clause::= (PROTOCOL = protocol) | ( ADDRESS = address) | (DESCRIPTION = description ) [options_clause]
7-114 SQL Reference
ALTER SYSTEM
options_clause::= (DISPATCHERS = integer | SESSIONS = integer | CONNECTIONS = integer | TICKS = seconds | POOL = { 1 | ON | YES | TRUE | BOTH | ({IN|OUT} = ticks) | 0 | OFF | NO | FALSE | ticks} | MULTIPLEX = {1 | ON | YES | TRUE | 0 | OFF | NO | FALSE | BOTH | IN | OUT} | LISTENER = tnsname | SERVICE = service | INDEX = integer) modifies or creates the configuration of dispatcher processes. A description of the parameters appears in Oracle8i Reference. You can specify multiple MTS_DISPATCHERS parameters in a single statement for multiple network protocols. See Also: Oracle8i Administrator's Guide for more information on this parameter, see Net8 Administrator's Guide. MTS_SERVERS = integer specifies a new minimum number of shared server processes. OBJECT_CACHE_MAX_SIZE_PERCENT = integer DEFERRED specifies the percentage of the optimal cache size that the session object cache can grow past the optimal size. OBJECT_CACHE_OPTIMAL_SIZE = integer DEFERRED specifies (in kilobytes) the size to which the session object cache is reduced if it exceeds the maximum size. OPTIMIZER_MAX_PERMUTATIONS = integer NOOVERRIDE lets you limit the amount of work the optimizer expends on optimizing queries with large joins. The value of integer is the number of permutations of the tables the optimizer will consider with large joins. NOOVERRIDE specifies that this system setting will not override the setting for any session in which this parameter was explicitly set. PARALLEL_ADAPTIVE_MULTI_USER = {TRUE | FALSE} specifies that Oracle should vary the degree of parallelism based on the total perceived load on the system. PARALLEL_INSTANCE_GROUP = 'text'
SQL Statements
7-115
ALTER SYSTEM
specifies the name of the Oracle Parallel Server instance group to be used for spawning parallel query slaves. PARALLEL_THREADS_PER_CPU = integer used to compute the degree of parallelism for parallel operations where the degree of parallelism is unset. The default is operating system dependent. PLSQL_V2_COMPATIBILITY = {TRUE | FALSE} [DEFERRED] modifies the compile-time behavior of PL/SQL programs to allow language constructs that are illegal in Oracle8 and Oracle8i (PL/SQL V3), but were legal in Oracle7 (PL/SQL V2). See PL/SQL User's Guide and Reference and Oracle8i Reference for more information about this system parameter. TRUE FALSE enables Oracle8i PL/SQL V3 programs to execute Oracle7 PL/SQL V2 constructs. disallows illegal Oracle7 PL/SQL V2 constructs. This is the default.
QUERY_REWRITE_ENABLED = { TRUE | FALSE } [DEFERRED | NOOVERRIDE] enables or disables query rewrite on all materialized views that have not been explicitly disabled. By default, TRUE enables query rewrite for all sessions immediately. Query rewrite is superseded and disabled by rule-based optimization (that is, if the OPTIMIZER_MODE parameter is set to RULE). Also enables or disables use of any function-based indexes defined on the materialized view. See Also: Oracle8i Data Warehousing Guide for more information on query rewrite.
s s
DEFERRED specifies that query rewrite is enabled or disabled only for future sessions. NOOVERRIDE specifies that query rewrite is enabled or disabled for all sessions that have not explicitly set this parameter using ALTER SESSION. Enabling or disabling query rewrite does not affect queries that have already been compiled, even if they are reissued. Enabling or disabling query rewrite does not affect descending indexes. A TRUE setting has no effect on materialized views that cannot be created with the ENABLE QUERY REWRITE clause, such as materialized views created totally or in part from a view.
s
s s
QUERY_REWRITE_INTEGRITY = { ENFORCED | TRUSTED | STALE_TOLERATED } sets the minimum consistency level for query rewrite for the duration of the instance. The following values are permitted:
7-116 SQL Reference
ALTER SYSTEM
s
ENFORCED is the safest level. It relies only on system-enforced relationships so that data integrity and correctness can be guaranteed. This level ensures that query rewrite will not use any function-based index or any materialized view that includes a call to a userdefined function. In addition, this level ensures that query rewrite will not use any dimensional information or any constraints enabled with the RELY keyword.
s
TRUSTED specifies that materialized views created with the ON PREBUILT TABLE clause are supported, and trusted but unenforced join relationships are accepted. Query rewrite uses join information from dimensions and enables unenforced constraints with the RELY keyword. STALE_TOLERATED specifies that any stale, usable materialized view may be used.
s
This parameter does not affect descending indexes. See Also:
s
Oracle8i Data Warehousing Guide for more information on query rewrite integrity level. "CREATE DIMENSION" on page 7-277 for information on dimensions. "constraint_clause" on page 7-233 for information on constraints enabled with the RELY keyword.
s s
REMOTE_DEPENDENCIES_MODE = {TIMESTAMP | SIGNATURE} specifies how dependencies of remote stored procedures are handled by the server. See Also: Oracle8i Application Developer's Guide - Fundamentals. RESOURCE_LIMIT = {TRUE | FALSE} When you start an instance, Oracle enforces resource limits assigned to users based on the value of the RESOURCE_LIMIT initialization parameter. This system parameter enables or disables resource limits for subsequent sessions. TRUE enables resource limits. FALSE disables resource limits. Enabling resource limits only causes Oracle to enforce the resource limits already assigned to users. To choose resource limit values for a user, you must create a profile and assign that profile to the user. See Also: "CREATE PROFILE" on page 7-359 and "CREATE USER" on page 7-451. RESOURCE_MANAGER_PLAN = plan_name specifies the name of the resource plan Oracle should use to allocate system resources among resource consumer groups. For information on resource consumer groups and resource plans, refer to Oracle8i Administrator's Guide.
SQL Statements
7-117
ALTER SYSTEM
SORT_AREA_RETAINED_SIZE = integer DEFERRED specifies (in bytes) the maximum amount of memory that each sort operation will retain after the first fetch is done, until the cursor ends. If you do not explicitly set this parameter in the initialization parameter file or dynamically, Oracle uses the value of the SORT_AREA_SIZE parameter. SORT_AREA_SIZE = integer DEFERRED specifies (in bytes) the maximum amount of memory to use for each sort operation. The default is operating system dependent. SORT_MULTIBLOCK_READ_COUNT = integer DEFERRED specifies the number of database blocks to read each time a sort performs a read from temporary segments. The default is 2. STANDBY_ARCHIVE_DEST = string specifies a valid operating system pathname as the standby database destination for the archive redo log files. TIMED_STATISTICS = {TRUE | FALSE} specifies whether the server requests the time from the operating system when generating time-related statistics. The default is FALSE. TIMED_OS_STATISTICS = integer specifies that operating system statistics will be collected when a request is made from a client to the server or when a request completes. TRANSACTION_AUDITING = {TRUE | FALSE} DEFERRED specifies whether the transaction layer generates a special redo record containing session and user information. USE_STORED_OUTLINES = { TRUE | FALSE | 'category_name' } [NOOVERRIDE] determines whether the optimizer will use stored outlines to generate execution plans. USE_ STORED_OUTLINES is not an initialization parameter.
s
TRUE causes the optimizer to use outlines stored in the DEFAULT category when compiling requests. FALSE specifies that the optimizer should not use stored outlines. This is the default. category_name causes the optimizer to use outlines stored in the category_name category when compiling requests. NOOVERRIDE specifies that this system setting will not override the setting for any session in which this parameter was explicitly set. If you do not specify NOOVERRIDE, this setting takes effect in all sessions.
s s
s
7-118 SQL Reference
ALTER SYSTEM
USER_DUMP_DEST = 'directory_name' specifies the pathname where Oracle will write debugging trace files on behalf of a user process.
Examples
Archive Log Examples The following statement manually archives the redo log
file group with the log sequence number 4 in thread number 3:
ALTER SYSTEM ARCHIVE LOG THREAD 3 SEQUENCE 4;
The following statement manually archives the redo log file group containing the redo log entry with the SCN 9356083:
ALTER SYSTEM ARCHIVE LOG CHANGE 9356083;
The following 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$]';
This statement enables query rewrite in all sessions for all materialized views that have not been explicitly disabled:
Query Rewrite Example
ALTER SYSTEM SET QUERY_REWRITE_ENABLED = TRUE;
Restricted Session Example 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 the following statement:
ALTER SYSTEM ENABLE RESTRICTED SESSION;
You can then terminate any existing sessions using the KILL SESSION clause of the ALTER SYSTEM statement. After performing maintenance on your application, issue the following statement to allow any user with CREATE SESSION system privilege to log on:
ALTER SYSTEM
SQL Statements
7-119
ALTER SYSTEM
DISABLE RESTRICTED SESSION;
You might want to clear the shared pool before beginning performance analysis. To clear the shared pool, issue the following statement:
Shared Pool Example
ALTER SYSTEM FLUSH SHARED_POOL;
CHECKPOINT Example
The following statement forces a checkpoint:
ALTER SYSTEM CHECKPOINT;
Resource Limit Example
This ALTER SYSTEM statement dynamically enables
resource limits:
ALTER SYSTEM SET RESOURCE_LIMIT = TRUE;
Multi-Threaded Server Examples The following 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. The following 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 = '(INDEX=0)(PROTOCOL=TCP)(DISPATCHERS=5)', '(INDEX=1)(PROTOCOL=DECNet)(DISPATCHERS=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, the above statement does not affect the number of dispatchers for that protocol.
7-120 SQL Reference
ALTER SYSTEM
Licensing Examples The following 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. The following statement dynamically disables the limit for sessions on your instance. After you issue the above statement, Oracle no longer limits the number of sessions on your instance.
ALTER SYSTEM SET LICENSE_MAX_SESSIONS = 0;
The following statement dynamically changes the limit on the number of users in the database to 200. After you issue the above statement, Oracle prevents the number of users in the database from exceeding 200.
ALTER SYSTEM SET LICENSE_MAX_USERS = 200;
You may want to force a log switch to drop or rename the current redo log file group or one of its members, because you cannot drop or rename a file while Oracle is writing to it. The forced log switch affects only your instance's redo log thread. The following statement forces a log switch:
SWITCH LOGFILE Example
ALTER SYSTEM SWITCH LOGFILE;
Distributed Recovery Example The following statement enables distributed
recovery:
ALTER SYSTEM ENABLE DISTRIBUTED RECOVERY;
You may want to disable distributed recovery for demonstration or testing purposes.You can disable distributed recovery in both single-process and multiprocess mode with the following statement:
ALTER SYSTEM DISABLE DISTRIBUTED RECOVERY;
SQL Statements
7-121
ALTER SYSTEM
When your demonstration or testing are complete, you can then enable distributed recovery again by issuing an ALTER SYSTEM statement with the ENABLE DISTRIBUTED RECOVERY clause.
KILL SESSION Example 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. That user can no longer make calls to the database without beginning a new session. Consider this data from the V$SESSION dynamic performance table:
SELECT sid, serial, username FROM v$session SID SERIAL USERNAME ----- --------- ---------------1 1 2 1 3 1 4 1 5 1 7 1 8 28 OPS$BQUIGLEY 10 211 OPS$SWIFT 11 39 OPS$OBRIEN 12 13 SYSTEM 13 8 SCOTT
The following statement kills the session of the user SCOTT using the SID and SERIAL# values from V$SESSION:
ALTER SYSTEM KILL SESSION '13, 8';
DISCONNECT SESSION Example The following statement disconnects user SCOTT's session, using the SID and SERIAL# values from V$SESSION:
ALTER SYSTEM DISCONNECT SESSION '13, 8' POST_TRANSACTION;
See Also: Oracle8i Parallel Server Concepts and Oracle8i Designing
and Tuning for Performance for more information about application failover.
7-122 SQL Reference
ALTER TABLE
7SQL Statements
ALTER TABLE
Syntax
schema ALTER TABLE ADD MODIFY ( ( . table add_column_options ) )
modify_column_options
move_table_clause physical_attributes_clause LOGGING NOLOGGING modify_collection_retrieval_clause modify_storage_clauses MODIFY CONSTRAINT constraint constraint_state
drop_constraint_clause drop_column_clause allocate_extent_clause deallocate_unused_clause CACHE NOCACHE MONITORING NOMONITORING RENAME TO new_table_name
records_per_block_clause alter_overflow_clause partitioning_clauses
SQL Statements
7-123
ALTER TABLE
enable_disable_clause ENABLE parallel_clause DISABLE TABLE ALL LOCK TRIGGERS ;
add_column_options::=
, DEFAULT column datatype expr column_ref_constraint column_constraint
table_constraint table_ref_constraint
LOB_storage_clause varray_storage_clause nested_table_storage_clause ( , partition_storage_clause )
column_constraint, table_constraint, column_ref_constraint, table_ref_constraint, constraint_state: See the "constraint_clause" on page 7-233. LOB_storage_clause::=
, ( LOB ( LOB_item ) STORE AS LOB_item ) STORE AS ( LOB_parameters ( ) )
LOB_segname LOB_segname (
LOB_parameters
LOB_parameters
)
7-124 SQL Reference
ALTER TABLE
LOB_parameters::=
TABLESPACE ENABLE
tablespace
STORAGE DISABLE storage_clause CHUNK integer integer
IN
ROW
PCTVERSION CACHE
LOGGING NOCACHE CACHE READS NOLOGGING
storage_clause: See "storage_clause" on page 7-605. varray_storage_clause::=
LOB_segname VARRAY varray_item STORE AS LOB LOB_segname ( LOB_parameters ) ( LOB_parameters )
nested_table_storage_clause::=
NESTED TABLE nested_item STORE AS storage_table
physical_properties ( ( object_properties ) )
LOCATOR RETURN AS VALUE
SQL Statements
7-125
ALTER TABLE
object_properties::=
column attribute table_constraint table_ref_constraint
DEFAULT
expr
column_ref_constraint
column_constraint
physical_properties::=
segment_attributes_clause segment_attributes_clause HEAP ORGANIZATION INDEX index_organized_table_clause , CLUSTER cluster ( column ) LOB_storage_clause varray_storage_clause nested_table_storage_clause
partition_storage_clause::=
LOB_storage_clause PARTITION partition varray_storage_clause
LOB_storage_clause ( SUBPARTITION subpartition varray_storage_clause )
modify_column_options::=
, datatype column DEFAULT expr column_constraint
7-126 SQL Reference
ALTER TABLE
move_table_clause::=
LOB_storage_clause ONLINE MOVE index_organized_table_clause segment_attributes_clause varray_storage_clause
segment_attributes_clause::=
physical_attributes_clause TABLESPACE LOGGING NOLOGGING tablespace
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
index_organized_table_clause::=
segment_attributes_clause PCTTHRESHOLD compression_clause integer
index_organized_overflow_clause
SQL Statements
7-127
ALTER TABLE
compression_clause::=
integer COMPRESS NOCOMPRESS
index_organized_overflow_clause::=
INCLUDING column_name OVERFLOW segment_attributes_clause
modify_collection_retrieval_clause::=
LOCATOR MODIFY NESTED TABLE collection_item RETURN AS VALUE
modify_storage_clauses::=
modify_LOB_storage_clause modify_varray_storage_clause
modify_LOB_storage_clause::=
MODIFY LOB ( LOB_item ) ( modify_LOB_storage_parameters )
7-128 SQL Reference
ALTER TABLE
modify_LOB_storage_parameters::=
storage_clause PCTVERSION CACHE LOGGING NOCACHE CACHE READS NOLOGGING integer
allocate_extent_clause deallocate_unused_clause
allocate_extent_clause::=
K M SIZE ( integer ' filename integer ' )
DATAFILE INSTANCE
ALLOCATE
EXTENT
deallocate_unused_clause::=
K M KEEP DEALLOCATE UNUSED integer
modify_varray_storage_clause::=
MODIFY VARRAY varray_item ( modify_LOB_storage_parameters )
SQL Statements
7-129
ALTER TABLE
drop_constraint_clause::=
PRIMARY KEY , DROP UNIQUE CONSTRAINT ( column constraint )
CASCADE
drop_column_clause::=
CASCADE COLUMN SET UNUSED ( , column ) CASCADE COLUMN DROP ( , column ) CHECKPOINT integer column INVALIDATE column INVALIDATE
CONSTRAINTS
CONSTRAINTS CHECKPOINT integer
UNUSED DROP COLUMNS
COLUMNS CONTINUE
records_per_block_clause::=
MINIMIZE RECORDS_PER_BLOCK NOMINIMIZE
7-130 SQL Reference
ALTER TABLE
alter_overflow_clause::=
PCTTHRESHOLD INCLUDING overflow_clause add_overflow_clause
integer
column
overflow_clause::=
physical_attributes_clause allocate_extent_clause OVERFLOW deallocate_unused_clause LOGGING NOLOGGING
add_overflow_clause::=
, segment_attributes_clause segment_attributes_clause ADD OVERFLOW ( PARTITION )
SQL Statements
7-131
ALTER TABLE
partitioning_clauses::=
modify_default_attributes_clause modify_partition_clause modify_subpartition_clause move_partition_clause move_subpartition_clause add_range_partition_clause add_hash_partition_clause coalesce_partition_clause drop_partition_clause rename_partition/subpartition_clause truncate_partition/subpartition_clause split_partition_clause merge_partitions_clause exchange_partition/subpartition_clause row_movement_clause
modify_default_attributes_clause::=
FOR MODIFY DEFAULT ATTRIBUTES COMPRESS PCTTHRESHOLD integer NOCOMPRESS PARTITION partition segment_attributes_clause
LOB overflow_clause VARRAY
LOB_item LOB_parameters varray
7-132 SQL Reference
ALTER TABLE
modify_partition_clause::=
partition_attributes add_subpartition_clause MODIFY PARTITION partition COALESCE REBUILD UNUSABLE LOCAL INDEXES SUBPARTITION parallel_clause
partition_attributes::=
physical_attributes_clause LOGGING NOLOGGING allocate_extent_clause deallocate_unused_clause
LOB OVERFLOW physical_attributes_clause VARRAY
LOB_item modify_LOB_storage_parameters varray
add_subpartition_clause::=
subpartition_description subpartition ADD SUBPARTITION
subpartition_description::=
LOB_storage_clause TABLESPACE tablespace varray_storage_clause parallel_clause
SQL Statements
7-133
ALTER TABLE
modify_subpartition_clause::=
allocate_extent_clause deallocate_unused_clause LOB MODIFY SUBPARTITION subpartition VARRAY REBUILD UNUSABLE LOCAL INDEXES LOB_item modify_LOB_storage_parameters varray
move_partition_clause::=
partition_description MOVE PARTITION partition parallel_clause
partition_description::=
compression_clause segment_attributes_clause LOB_storage_clause varray_storage_clause
segment_attributes_clause OVERFLOW partition_level_subpartitioning
partition_level_subpartitioning::=
, STORE SUBPARTITIONS quantity , subpartition ( SUBPARTITION hash_partitioning_storage_clause ) IN ( tablespace )
7-134 SQL Reference
ALTER TABLE
hash_partitioning_storage_clause::=
TABLESPACE tablespace
LOB VARRAY
(
LOB_item varray_item
)
STORE AS
AS LOB
( (
TABLESPACE TABLESPACE
tablespace tablespace
) )
STORE
move_subpartition_clause::=
MOVE SUBPARTITION subpartition subpartition_description
add_range_partition_clause::=
partition ADD PARTITION VALUES LESS THAN ( value_list ) partition_description
add_hash_partition_clause::=
parallel_clause partition ADD PARTITION hash_partitioning_storage_clause
coalesce_partition_clause::=
parallel_clause COALESCE PARTITION
drop_partition_clause::=
DROP PARTITION partition
SQL Statements
7-135
ALTER TABLE
rename_partition/ subpartition_clause::=
PARTITION RENAME SUBPARTITION current_name TO new_name
truncate_partition_clause/truncate_subpartition_clause::=
DROP STORAGE PARTITION TRUNCATE SUBPARTITION subpartition partition REUSE
split_partition_clause::=
SPLIT PARTITION INTO ( partition_name_old partition_description AT , ( value_list ) ) parallel_clause
partition_description
merge_partitions_clause::=
MERGE PARTITIONS partition_1 , partition_2 partition_description new_partition INTO PARTITION
7-136 SQL Reference
ALTER TABLE
exchange_partition_clause/exchange_subpartition_clause::=
PARTITION EXCHANGE SUBPARTITION INCLUDING INDEXES EXCLUDING WITHOUT subpartition WITH VALIDATION partition WITH TABLE nonpartitioned_table
schema EXCEPTIONS INTO
. table
row_movement_clause::=
ENABLE ROW DISABLE MOVEMENT
parallel_clause::=
NOPARALLEL integer PARALLEL
enable_disable_clause::=
, UNIQUE PRIMARY DISABLE CONSTRAINT constraint . table CASCADE ( KEY column )
VALIDATE ENABLE NOVALIDATE
schema using_index_clause EXCEPTIONS INTO
SQL Statements
7-137
ALTER TABLE
using_index_clause::=
LOCAL global_index_clause PCTFREE INITRANS MAXTRANS TABLESPACE storage_clause NOSORT LOGGING NOLOGGING USING INDEX integer integer integer tablespace
Purpose
To alter the definition of a nonpartitioned table, a partitioned table, a table partition, or a table subpartition.
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. For some operations you may also need the CREATE ANY INDEX privilege. In addition, if you are not the owner of the table, you need the DROP ANY TABLE privilege in order to use the drop_partition_clause or truncate_partition_clause. You must also have space quota in the tablespace in which space is to be acquired in order to use the add_partition_clause, modify_partition_clause, move_partition_clause, and split_partition_clause. To enable a UNIQUE or PRIMARY KEY constraint, you must have the privileges necessary to create an index on the table. You need these privileges because Oracle creates an index on the columns of the unique or primary key in the schema containing the table. See "CREATE INDEX" on page 7-291.
7-138 SQL Reference
ALTER TABLE
To enable or disable triggers, the triggers must be in your schema or you must have the ALTER ANY TRIGGER system privilege. To use an object type in a column definition when modifying a table, either that object must belong to the same schema as the table being altered, or you must have either the EXECUTE ANY TYPE system privilege or the EXECUTE schema object privilege for the object type.
Keywords and Parameters
The clauses described below have specialized meaning in the ALTER TABLE statement. For descriptions of the remaining keywords, see "CREATE TABLE" on page 4-381. Note: Operations performed by the ALTER TABLE statement can cause Oracle to invalidate procedures and stored functions that access the table. For information on how and when Oracle invalidates such objects, see Oracle8i Concepts. schema table is the schema containing the table. If you omit schema, Oracle assumes the table is in your own schema. is the name of the table to be altered. You can modify, or drop columns from, or rename a temporary table. However, for a temporary table, you cannot:
s s
Add columns of nested-table or varray type. You can add columns of other types. Specify referential integrity (foreign key) constraints for an added or modified column Specify the following clauses of the LOB_storage_clause for an added or modified LOB column: TABLESPACE, storage_clause, LOGGING|NOLOGGING, or the LOB_index_ clause. Specify the physical_attribute_clause, nested_table_storage_clause, parallel_clause, allocate_ extent_clause, deallocate_unused_clause, or any of the index-organized table clauses Exchange partitions between a partition and a temporary table Specify LOGGING or NOLOGGING Specify MOVE
s
s
s s s
Note: If you alter a table that is a master table for one or more materialized views, the materialized views are marked INVALID. Invalid materialized views cannot be used by query rewrite and cannot be refreshed. To revalidate a materialized view, see "ALTER MATERIALIZED VIEW / SNAPSHOT" on page 7-47. See Also: Oracle8i Data Warehousing Guide for more information on materialized views in general.
SQL Statements
7-139
ALTER TABLE
ADD add_column_ options
adds a column or integrity constraint. For a description of the keywords and parameters of this clause, see "CREATE TABLE" on page 4-381. If you add a column, the initial value of each row for the new column is null unless you specify the DEFAULT clause. In this case, Oracle updates each row in the new column with the value you specify for DEFAULT. This update operation, in turn, fires any AFTER UPDATE triggers defined on the table. You can add an overflow data segment to each partition of a partitioned index-organized table. You can add LOB columns to nonpartitioned and partitioned tables. You can specify LOB storage at the table and at the partition or subpartition level. If you previously created a view with a query that used the "SELECT *" syntax to select all columns from table, and you now add a column to table, Oracle does not automatically add the new column to the view. To add the new column to the view, re-create the view using the CREATE VIEW statement with the OR REPLACE clause. See "CREATE VIEW" on page 7-456. Restrictions:
s
You cannot add a LOB column to a partitioned index-organized table. (This restriction does not apply to nonpartitioned index-organized tables.) You cannot add a column with a NOT NULL constraint if table has any rows unless you also specify the DEFAULT clause. If you specify this clause for an index-organized table, you cannot specify any other clauses in the same statement. specifies a default 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. If you are adding a new column to the table and specify the default value, Oracle inserts the default column value into all rows of the table. 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.
s
s
DEFAULT
table_ref_ constraint column_ref_ constraint
These clauses let you further describe a column of type REF. The only difference between these clauses is that you specify table_ref from the table level, so you must identify the REF column or attribute you are defining. You specify column_ref after you have already identified the REF column or attribute. For syntax and description of these constraints, including restrictions, see the "constraint_clause" on page 7-233.
7-140 SQL Reference
ALTER TABLE
column_constraint
adds or removes a NOT NULL constraint to or from an existing column. You cannot use this clause to modify any other type of constraint using ALTER TABLE. See the "constraint_clause" on page 7-233. adds or modifies an integrity constraint on the table. See the "constraint_clause" on page 7-233.
table_constraint LOB_storage_ clause
specifies the LOB storage characteristics for the newly added LOB column. You cannot use this clause to modify an existing LOB column. Instead, you must use the modify_LOB_ storage_clause. Restrictions:
s
The only parameter of LOB_parameters you can specify for a hash partition or hash subpartition is TABLESPACE. You cannot specify the LOB_index_clause if table is partitioned. is the LOB column name or LOB object attribute for which you are explicitly defining tablespace and storage characteristics that are different from those of the table. specifies the name of the LOB data segment. You cannot use lob_ segname if more than one lob_item is specified. specifies whether the LOB value is stored in the row (inline) or outside of the row. (The LOB locator is always stored in the row regardless of where the LOB value is stored.)
s
s
lob_item
lob_segname ENABLE | DISABLE STORAGE IN ROW
ENABLE specifies that the LOB value is stored inline if its length is less than approximately 4000 bytes minus system control information. This is the default. DISABLE specifies that the LOB value is stored outside of the row regardless of the length of the LOB value.
s
Restriction: You cannot change STORAGE IN ROW once it is set. Therefore, you can specify this clause only as part of the add_column_ options clause, not as part of the modify_column_options clause. CHUNK integer specifies the number of bytes to be allocated for LOB manipulation. If integer is not a multiple of the database block size, Oracle rounds up (in bytes) to the next multiple. For example, if the database block size is 2048 and integer is 2050, Oracle allocates 4096 bytes (2 blocks).The maximum value is 32768 (32 K), which is the largest Oracle block size allowed. The default CHUNK size is one Oracle database block. You cannot change the value of CHUNK once it is set. Note: The value of CHUNK must be less than or equal to the value of NEXT (either the default value or that specified in the storage clause). If CHUNK exceeds the value of NEXT, Oracle returns an error.
SQL Statements
7-141
ALTER TABLE
PCTVERSION integer
is the maximum percentage of overall LOB storage space used for creating new versions of the LOB. The default value is 10, meaning that older versions of the LOB data are not overwritten until 10% of the overall LOB storage space is used. This clause is deprecated as of Oracle8i. Oracle generates an index for each LOB column. The LOB indexes are system named and system managed, and reside in the same tablespace as the LOB data segments. It is still possible for you to specify this clause in some cases. However, Oracle Corporation strongly recommends that you no longer do so. For information on how Oracle manages LOB indexes in tables migrated from earlier versions, see Oracle8i Migration.
LOB_index_ clause
varray_storage_ clause
lets you specify separate storage characteristics for the LOB in which a varray will be stored. In addition, if you specify this clause, Oracle will always store the varray in a LOB, even if it is small enough to be stored inline. Restriction: You cannot specify the TABLESPACE clause of LOB_parameters as part of this clause. The LOB tablespace for a varray defaults to the containing table's tablespace.
nested_table_ storage_clause
enables you to specify separate storage characteristics for a nested table, which in turn enables you to define the nested table as an index-organized table. You must include this clause when creating a table with columns or column attributes whose type is a nested table. (Clauses within this clause that function the same way they function for parent object tables are not repeated here.) Restrictions:
s s
You cannot specify the parallel_clause. You cannot specify TABLESPACE (as part of the segment_attributes_clause) for a nested table. The tablespace is always that of the parent table. is the name of a column (or a top-level attribute of the table's object type) whose type is a nested table. is the name of the table where the rows of nested_item reside. The storage table is created in the same schema and the same tablespace as the parent table.
nested_item storage_table
partition_storage_ lets you specify a separate LOB_storage_clause or varray_storage_clause for each partition. clause You must specify the partitions in the order of partition position. If you do not specify a LOB_storage_clause or varray_storage_clause for a particular partition, the storage characteristics are those specified for the LOB item at the table level. If you also did not specify any storage characteristics at the table level for the LOB item, Oracle stores the LOB data partition in the same tablespace as the table partition to which it corresponds. Restriction: You can specify only one list of partition_storage_clauses per ALTER TABLE statement, and all LOB_storage_clauses and varray_storage_clauses must precede the list of partition_storage_clauses.
7-142 SQL Reference
ALTER TABLE
MODIFY modify_column_ options
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.
s
You can change a CHAR column to VARCHAR2 (or VARCHAR) and a VARCHAR2 (or VARCHAR) to CHAR only if the column contains nulls in all rows or if you do not attempt to change the column size. You can change any column's datatype or decrease any column's size if all rows for the column contain nulls. You can always increase the size of a character or raw column or the precision of a numeric column, whether or not all the columns contain nulls.
s
s
Restrictions:
s
You cannot modify the datatype or length of a column that is part of a table or index partitioning or subpartitioning key. You cannot modify the definition of a column on which a domain index has been built. If you specify this clause for an index-organized table, you cannot specify any other clauses in the same statement. is the name of the column to be added or modified. 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, and only if the column contains no nulls. To 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.
s
s
column
datatype
specifies a new datatype for an existing column. You can omit the datatype only 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. If you change the datatype of a column in a materialized view container table, the corresponding materialized view is invalidated. To revalidate a materialized view, see "ALTER MATERIALIZED VIEW / SNAPSHOT" on page 7-47. Restrictions:
s
You cannot specify a column of datatype ROWID for an indexorganized table, but you can specify a column of type UROWID. You cannot change a column's datatype to LOB or REF.
s
SQL Statements
7-143
ALTER TABLE
MODIFY CONSTRAINT constraint
modifies the state of an existing constraint named constraint. For a description of all the keywords and parameters of constraint_state, see the "constraint_clause" on page 7-233.
move_table_clause For a heap-organized table, use the segment_attributes_clause of the syntax. The move_ table_clause lets you relocate data of a nonpartitioned table into a new segment, optionally in a different tablespace, and optionally modify any of its storage attributes. You can also move any LOB data segments associated with the table using the LOB_ storage_clause. (LOB items not specified in this clause are not moved.) For an index-organized table, use the index_organized_table_clause of the syntax. The move_ table_clause rebuilds the index-organized table's primary key index B*-tree. The overflow data segment is not rebuilt unless the OVERFLOW keyword is explicitly stated, with two exceptions:
s
If you alter the values of PCTTHRESHOLD or the INCLUDING column as part of this ALTER TABLE statement, the overflow data segment is rebuilt. If any of out-of-line columns (LOBs, varrays, nested table columns) in the indexorganized table are moved explicitly, then the overflow data segment is also rebuilt.
s
The index and data segments of LOB columns are not rebuilt unless you specify the LOB columns explicitly as part of this ALTER TABLE statement. ONLINE specifies that DML operations on the index-organized table are allowed during rebuilding of the table's primary key index B*-tree. Restrictions:
s
You can specify this clause only for a nonpartitioned indexorganized table. Parallel DML is not supported during online MOVE. If you specify ONLINE and then issue parallel DML statements, Oracle returns an error.
s
compression_clause enables and disables key compression in an index-organized table.
s
COMPRESS enables key compression, which eliminates repeated occurrence of primary key column values in index-organized tables. Use integer to specify the prefix length (number of prefix columns to compress). The valid range of prefix length values is from 1 to the number of primary key columns minus 1. The default prefix length is the number of primary key columns minus 1. Restrictions: - You can specify this clause only for an index-organized table. - You can specify compression for a partition of an indexorganized table only if compression has been specified at the table level.
7-144 SQL Reference
ALTER TABLE
s
NOCOMPRESS disables key compression in index-organized tables. This is the default.
TABLESPACE Restrictions:
s
specifies the tablespace into which the rebuilt index-organized table is stored.
If you specify MOVE, it must be the first clause. For an index-organized table, the only clauses outside this clause that are allowed are the physical_attribute_clause and the parallel_clause. For heap-organized tables, you can specify those two clauses and the LOB_storage_clauses. You cannot MOVE an entire partitioned table (either heap or index organized). You must move individual partitions or subpartitions. See "move_partition_clause" on page 7-157 and "move_subpartition_clause" on page 7-158.
s
Notes regarding LOBs: For any LOB columns you specify in this clause:
s
Oracle drops the old LOB data segment and corresponding index segment and creates new segments, even if you do not specify a new tablespace. If the LOB index in table resided in a different tablespace from the LOB data, Oracle collocates the LOB index with the LOB data in the LOB data's tablespace after the move.
s
physical_ attributes_clause
changes the value of PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters and storage characteristics. See the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters of "CREATE TABLE" on page 4-381 and the "storage_clause". Restriction: You cannot specify the PCTUSED parameter for the index segment of an index-organized table. WARNING:
s
For a nonpartitioned table, the values you specify override any values specified for the table at create time. For a range- or hash-partitioned table, the values you specify are the default values for the table and the actual values for every existing partition, overriding any values already set for the partitions. To change default table attributes without overriding existing partition values, use the modify_default_attributes_clause. For a composite-partitioned table, the values you specify are the default values for the table and all partitions of the table and the actual values for all subpartitions of the table, overriding any values already set for the subpartitions. To change default partition attributes without overriding existing subpartition values, use the modify_ default_attributes_clause with the FOR PARTITION clause.
s
s
modify_collection_ changes what is returned when a collection item is retrieved from the database. retrieval_clause
SQL Statements
7-145
ALTER TABLE
collection_item RETURN AS
is the name of a column-qualified attribute whose type is nested table or varray. specifies what Oracle returns as the result of a query.
s
LOCATOR specifies that a unique locator for the nested table is returned. VALUE specifies that a copy of the nested table itself is returned.
s
modify_storage_clauses: modify_LOB_ storage_clause modifies the physical attributes of the LOB lob_item. You can specify only one lob_item for each modify_LOB_storage_clause. Restrictions:
s
You cannot modify the value of the INITIAL parameter in the storage_clause when modifying the LOB storage attributes. You cannot specify both the allocate_extent_clause and the deallocate_unused_clause in the same statement.
s
modify_varray_ storage_clause
lets you change the storage characteristics of an existing LOB in which a varray is stored. Restriction: You cannot specify the TABLESPACE clause of LOB_parameters as part of this clause. The LOB tablespace for a varray defaults to the containing table's tablespace. drops an integrity constraint from the database. Oracle stops enforcing the constraint and removes it from the data dictionary. You can specify only one constraint for each drop_ constraint_clause, but you can specify multiple drop_constraint_clauses in one statement. PRIMARY KEY UNIQUE CONSTRAINT CASCADE Restrictions:
s
drop_constraint_ clause
drops the table's PRIMARY KEY constraint. drops the UNIQUE constraint on the specified columns. drops the integrity constraint named constraint. drops all other integrity constraints that depend on the dropped integrity constraint.
You cannot drop a UNIQUE or PRIMARY KEY constraint that is part of a referential integrity constraint without also dropping the foreign key. To drop the referenced key and the foreign key together, use the CASCADE clause. If you omit CASCADE, Oracle does not drop the PRIMARY KEY or UNIQUE constraint if any foreign key references it. You cannot drop a primary key constraint (even with the CASCADE clause) on a table that uses the primary key as its object identifier (OID). If you drop a referential integrity constraint on a REF column, the REF column remains scoped to the referenced table. You cannot drop the scope of the column.
s
s
s
7-146 SQL Reference
ALTER TABLE
drop_column_ clause
lets you free space in the database by dropping columns you no longer need, or by marking them to be dropped at a future time when the demand on system resources is less. SET UNUSED marks one or more columns as unused. Specifying this clause does not actually remove the target columns from each row in the table (that is, it does not restore the disk space used by these columns). Therefore, the response time is faster than it would be if you execute the DROP clause. You can view all tables with columns marked as unused in the data dictionary views USER_UNUSED_COL_TABS, DBA_UNUSED_COL_ TABS, and ALL_UNUSED_COL_TABS. For information on these views, see Oracle8i Reference. Unused columns are treated as if they were dropped, even though their column data remains in the table's rows. After a column has been marked as unused, you have no access to that column. A "SELECT *" query will not retrieve data from unused columns. In addition, the names and types of columns marked unused will not be displayed during a DESCRIBE, and you can add to the table a new column with the same name as an unused column. Note: Until you actually drop these columns, they continue to count toward the absolute limit of 1000 columns per table. However, as with all DDL statements, you cannot roll back the results of this clause. That is, you cannot issue SET USED counterpart to retrieve a column that you have SET UNUSED. Also, if you mark a column of datatype LONG as UNUSED, you cannot add another LONG column to the table until you actually drop the unused LONG column. See Also: "CREATE TABLE" on page 4-381 for more information on the 1000 column limit. DROP removes the column descriptor and the data associated with the target column from each row in the table. If you explicitly drop a particular column, all columns currently marked as unused in the target table are dropped at the same time.
SQL Statements
7-147
ALTER TABLE
When the column data is dropped:
s
All indexes defined on any of the target columns are also dropped. All constraints that reference a target column are removed. If any statistics types are associated with the target columns, Oracle disassociates the statistics from the column with the FORCE option and drops any statistics collected using the statistics type.
s s
See Also: "DISASSOCIATE STATISTICS" on page 7-470 for more information on disassociating statistics types. Note: If a constraint also references a nontarget column, Oracle returns an error and does not drop the column unless you have specified the CASCADE CONSTRAINTS clause. If you have specified that clause, Oracle removes all constraints that reference any of the target columns. DROP UNUSED COLUMNS removes from the table all columns currently marked as unused. Use this statement when you want to reclaim the extra disk space from unused columns in the table. If the table contains no unused columns, the statement returns with no errors. specifies one or more columns to be set as unused or dropped. Use the COLUMN keyword only if you are specifying only one column. If you specify a column list, it cannot contain duplicates. drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns, and drops all multicolumn constraints defined on the dropped columns. If any constraint is referenced by columns from other tables or remaining columns in the target table, then you must specify CASCADE CONSTRAINTS. Otherwise, the statement aborts and an error is returned. Note: Currently, Oracle executes this clause regardless of whether you specify the keyword INVALIDATE. Oracle invalidates all dependent objects, such as views, triggers, and stored program units. Object invalidation is a recursive process. Therefore, all directly dependent and indirectly dependent objects are invalidated. However, only local dependencies are invalidated, because Oracle manages remote dependencies differently from local dependencies. An object invalidated by this statement is automatically revalidated when next referenced. You must then correct any errors that exist in that object before referencing it. See Also: Oracle8i Concepts for more information on dependencies.
column
CASCADE CONSTRAINTS
INVALIDATE
7-148 SQL Reference
ALTER TABLE
CHECKPOINT
specifies that a checkpoint for the drop column operation will be applied after processing integer rows; integer is optional and must be greater than zero. If integer is greater than the number of rows in the table, Oracle applies a checkpoint after all the rows have been processed. If you do not specify integer, Oracle sets the default of 512. Checkpointing cuts down the amount of undo logs accumulated during the drop column operation to avoid running out of rollback segment space. However, if this statement is interrupted after a checkpoint has been applied, the table remains in an unusable state. While the table is unusable, the only operations allowed on it are DROP TABLE, TRUNCATE TABLE, and ALTER TABLE DROP COLUMNS CONTINUE (described below). You cannot use this clause with SET UNUSED, because that clause does not remove column data.
DROP COLUMNS CONTINUE
continues the drop column operation from the point at which it was interrupted. Submitting this statement while the table is in a valid state results in an error.
Restrictions on the drop_column_clause:
s
Each of the parts of this clause can be specified only once in the statement and cannot be mixed with any other ALTER TABLE clauses. For example, the following statements are not allowed: ALTER TABLE t1 DROP COLUMN f1 DROP (f2); ALTER TABLE t1 DROP COLUMN f1 SET UNUSED (f2); ALTER TABLE t1 DROP (f1) ADD (f2 NUMBER); ALTER TABLE t1 SET UNUSED (f3) ADD (CONSTRAINT ck1 CHECK (f2 > 0));
s
You can drop an object type column only as an entity. Dropping an attribute from an object type column is not allowed. If you drop a nested table column, its storage table is removed. If you drop a LOB column, the LOB data and its corresponding LOB index segment are removed. If you drop a BFILE column, only the locators stored in that column are removed, not the files referenced by the locators. You can drop a column from an index-organized table only if it is not a primary key column. The primary key constraint of an index-organized table can never be dropped, so you cannot drop a primary key column even if you have specified CASCADE CONSTRAINTS.
s s
s
s
SQL Statements
7-149
ALTER TABLE
s
You can export tables with dropped or unused columns. However, you can import a table only if all the columns specified in the export files are present in the table (that is, none of those columns has been dropped or marked unused). Otherwise, Oracle returns an error. You cannot drop a column on which a domain index has been built.
s
You cannot use this clause to drop:
s
A pseudocolumn, clustered column, or partitioning column. (You can drop nonpartitioning columns from a partitioned table if all the tablespaces where the partitions were created are online and in read-write mode.) A column from a nested table, an object table, or a table owned by SYS
s
allocate_extent_ clause
explicitly allocates a new extent for the table, the partition or subpartition, the overflow data segment, the LOB data segment, or the LOB index. Restriction: You cannot allocate an extent for a range- or composite-partitioned table. SIZE specifies the size of the extent in bytes. 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 STORAGE parameters of the table's overflow data segment or of the LOB index. specifies one of the datafiles in the tablespace of the table, overflow data segment, LOB data tablespace, or LOB index to contain the new extent. If you omit this parameter, Oracle chooses the datafile. makes the new extent available to the freelist group associated with the specified instance. If the instance number exceeds the maximum number of freelist groups, the former is divided by the latter, and the remainder is used to identify the freelist group to be used. An instance is identified by the value of its initialization parameter INSTANCE_ NUMBER. If you omit this parameter, the space is allocated to the table, but is not drawn from any particular freelist group. Rather, the master freelist is used, and space is allocated as needed. Use this parameter only if you are using Oracle with the Parallel Server option in parallel mode. See Also: Oracle8i Concepts 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.
DATAFILE
INSTANCE
deallocate_ unused_clause
explicitly deallocates unused space at the end of the table, partition or subpartition, overflow data segment, LOB data segment, or LOB index and makes the space available for other segments in the tablespace. You can free only unused space above the high water mark (that is, the point beyond which database blocks have not yet been formatted to receive data).
7-150 SQL Reference
ALTER TABLE
Oracle credits the amount of the released space to the user quota for the tablespace in which the deallocation occurs. Oracle deallocates unused space from the end of the object toward the high water mark at the beginning of the object. If an extent is completely contained in the deallocation, then the whole extent is freed for reuse. If an extent is partially contained in the deallocation, then the used part up to the high water mark becomes the extent, and the remaining unused space is freed for reuse. The exact amount of space freed depends on the values of the INITIAL, MINEXTENTS, and NEXT parameters (as described in "storage_clause" on page 7-605). KEEP specifies the number of bytes above the high water mark that the table, overflow data segment, LOB data segment, or LOB index will have after deallocation.
s
If you omit KEEP and the high water mark is above the size of INITIAL and MINEXTENTS, then all unused space above the high water mark is freed. When the high water mark is less than the size of INITIAL or MINEXTENTS, then all unused space above MINEXTENTS is freed. If you specify KEEP, then the specified amount of space is kept and the remaining space is freed. When the remaining number of extents is less than MINEXTENTS, then MINEXTENTS is adjusted to the new number of extents. If the initial extent becomes smaller than INITIAL, then INITIAL is adjusted to the new size. In either case, NEXT is set to the size of the last extent that was deallocated.
s
s
CACHE
for data that is accessed frequently, specifies that the blocks retrieved for this table are placed at the most recently used end of the LRU list in the buffer cache when a full table scan is performed. This attribute is useful for small lookup tables. As a parameter in the LOB_storage_clause, CACHE specifies that Oracle places LOB data values in the buffer cache for faster access. Restriction: You cannot specify CACHE for an index-organized table. However, indexorganized tables implicitly provide CACHE behavior.
NOCACHE
for data that is not accessed frequently, specifies that the blocks retrieved for this table are placed at the least recently used end of the LRU list in the buffer cache when a full table scan is performed. As a parameter in the LOB_storage_clause, NOCACHE specifies that the LOB value is either not brought into the buffer cache or brought into the buffer cache and placed at the least recently used end of the LRU list. (The latter is the default behavior.) NOCACHE is the default for LOB storage. Restriction: You cannot specify NOCACHE for index-organized tables.
SQL Statements
7-151
ALTER TABLE
CACHE READS
applies only to LOB storage. It specifies that LOB values are brought into the buffer cache only during read operations, but not during write operations.
s
When you add a new LOB column, you can specify the logging attribute with CACHE READS, as you can when defining a LOB column at create time. When you modify a LOB column from CACHE or NOCACHE to CACHE READS, or from CACHE READS to CACHE or NOCACHE, you can change the logging attribute. If you do not specify the LOGGING or NOLOGGING, this attribute defaults to the current logging attribute of the LOB column.
s
For existing LOBs, if you do not specify CACHE, NOCACHE, or CACHE READS, Oracle retains the existing values of the LOB attributes. MONITORING specifies that Oracle can collect modification statistics on table. These statistics are estimates of the number of rows affected by DML statements over a particular period of time. They are available for use by the optimizer or for analysis by the user. See Also: Oracle8i Designing and Tuning for Performance for more information on using this clause. NOMONITORING specifies that Oracle will not collect modification statistics on table. Restriction: You cannot specify MONITORING or NOMONITORING for a temporary table. LOGGING| NOLOGGING specifies whether subsequent Direct Loader (SQL*Loader) and direct-load INSERT operations against a nonpartitioned table, table partition, all partitions of a partitioned table, or all subpartitions of a partition will be logged (LOGGING) or not logged (NOLOGGING) in the redo log file. When used with the modify_default_attributes_clause, this clause affects the logging attribute of a partitioned table. LOGGING|NOLOGGING also specifies whether ALTER TABLE...MOVE and ALTER TABLE...SPLIT operations will be logged or not logged. For a table or table partition, if you omit LOGGING|NOLOGGING, the logging attribute of the table or table partition defaults to the logging attribute of the tablespace in which it resides. For LOBs, if you omit LOGGING|NOLOGGING,
s
If you specify CACHE, then LOGGING is used (because you cannot have CACHE NOLOGGING). If you specify NOCACHE or CACHE READS, the logging attribute defaults to the logging attribute of the tablespace in which it resides.
s
NOLOGGING does not apply to LOBs that are stored inline with row data. That is, if you specify NOLOGGING for LOBs with values less than 4000 bytes and you have not disabled STORAGE IN ROW, Oracle ignores the NOLOGGING specification and treats the LOB data the same as other table data.
7-152 SQL Reference
ALTER TABLE
In NOLOGGING mode, data is modified with minimal logging (to mark new extents invalid and to record dictionary changes). When applied during media recovery, the extent invalidation records mark a range of blocks as logically corrupt, because the redo data is not logged. Therefore, if you cannot afford to lose this table, it is important to take a backup after the NOLOGGING operation. If the database is run in ARCHIVELOG mode, media recovery from a backup taken before the LOGGING operation will restore the table. However, media recovery from a backup taken before the NOLOGGING operation will not restore the table. The logging attribute of the base table is independent of that of its indexes. See Also: Oracle8i Parallel Server Concepts for more information about the logging_clause and parallel DML. RENAME TO renames table to new_table_name. Note: Using this clause will invalidate any dependent materialized views. See Also: "CREATE MATERIALIZED VIEW / SNAPSHOT" on page 7-318 and Oracle8i Data Warehousing Guide for more information on materialized views. records_per_block_ determines whether Oracle restricts the number of records that can be stored in a block. clause This clause ensures that any bitmap indexes subsequently created on the table will be as small (compressed) as possible. Restrictions:
s
You cannot specify either MINIMIZE or NOMINIMIZE if a bitmap index has already been defined on table. You must first drop the bitmap index. You cannot specify this clause for an index-organized table or nested table. instructs Oracle to calculate the largest number of records in any block in the table, and limit future inserts so that no block can contain more than that number of records. Restriction: You cannot specify MINIMIZE for an empty table.
s
MINIMIZE
NOMINIMIZE alter_overflow_ clause
disables the MINIMIZE feature. This is the default.
modifies the definition of an index-organized table. Index-organized tables keep data sorted on the primary key and are therefore best suited for primary-key-based access and manipulation. Note: When you alter an index-organized table, Oracle evaluates the maximum size of each column to estimate the largest possible row. If an overflow segment is needed but you have not specified OVERFLOW, Oracle raises an error and does not execute the ALTER TABLE statement. This checking function guarantees that subsequent DML operations on the index-organized table will not fail because an overflow segment is lacking.
SQL Statements
7-153
ALTER TABLE
PCTTHRESHOLD integer
specifies the percentage of space reserved in the index block for an index-organized table row. Any portion of the row that exceeds the specified threshold is stored in the overflow area. PCTTHRESHOLD must be a value from 1 to 50. Restrictions:
s
You cannot reduce the value of PCTTHRESHOLD so much that the primary key will not fit. You cannot specify PCTTHRESHOLD for individual partitions of an index-organized table.
s
INCLUDING column_name
specifies the column at which to divide an index-organized table row into index and overflow portions. All non-primary-key columns that follow column_name are stored in the overflow data segment. The column_name is either the name of the last primary key column or any subsequent non-primary-key column. If you use the drop_column_clause to drop (or mark unused) a column defined as an INCLUDING column, the column stored immediately before this column will become the new INCLUDING column.
overflow_clause
specifies the overflow data segment physical storage and logging attributes to be modified for the index-organized table. Parameters specified in this clause are applicable only to the overflow data segment. Restriction: You cannot specify OVERFLOW for a partition of a partitioned index-organized table unless the table already has an overflow segment. See Also: "CREATE TABLE" on page 4-381.
7-154 SQL Reference
ALTER TABLE
add_overflow_ clause
adds an overflow data segment to the specified index-organized table. For a partitioned index-organized table:
s
If you do not specify PARTITION, Oracle automatically allocates an overflow segment for each partition. The physical attributes of these segments are inherited from the table level. If you wish to specify separate physical attributes for one or more partitions, you must specify such attributes for every partition in the table. You do not specify the name of the partitions, but you must specify their attributes in the order in which they were created. You can find the order of the partitions by querying the PARTITION_NAME and PARTITION_POSITION columns of the USER_IND_PARTITIONS view.
s
If you do not specify TABLESPACE for a particular partition, Oracle uses the tablespace specified for the table. If you do not specify TABLESPACE at the table level, Oracle uses the tablespace of the partition's primary key index segment. partitioning_ clauses The following clauses apply only to partitioned tables. You cannot combine partition operations with other partition operations or with operations on the base table in one ALTER TABLE statement. Note: If you drop, exchange, truncate, move, modify, or split a partition on a table that is a master table for one or more materialized views, existing bulk load information about the table will be deleted. Therefore, be sure to refresh all dependent materialized views before performing any of these operations. modify_default_ attributes_clause specifies new default values for the attributes of table. Partitions and LOB partitions you create subsequently will inherit these values unless you override them explicitly when creating the partition or LOB partition. Existing partitions and LOB partitions are not affected by this clause. Only attributes named in the statement are affected, and the default values specified are overridden by any attributes specified at the individual partition level. FOR PARTITION applies only to composite-partitioned tables. This clause specifies new default values for the attributes of partition. Subpartitions and LOB subpartitions of partition that you create subsequently will inherit these values, unless you override them explicitly when creating the subpartition or LOB subpartition. Existing subpartitions are not affected by this clause.
SQL Statements
7-155
ALTER TABLE
Restrictions:
s
The PCTTHRESHOLD, COMPRESS, physical_attributes_clause, and overflow_clause are valid only for partitioned index-organized tables. You cannot specify the PCTUSED parameter for the index segment of an indexorganized table. You can specify COMPRESS only if compression is already specified at the table level.
s
s
modify_partition_ clause
modifies the real physical attributes of the partition table partition. Optionally modifies the storage attributes of one or more LOB items for the partition. You can specify new values for any of the following physical attributes for the partition: the logging attribute; PCTFREE, PCTUSED, INITRANS, or MAXTRANS parameter; or storage parameters. If table is composite-partitioned:
s
If you specify the allocate_extent_clause, Oracle will allocate an extent for each subpartition of partition. If you specify deallocate_unused_clause, Oracle will deallocate unused storage from each subpartition of partition. Any other attributes changed in this clause will be changed in subpartitions of partition as well, overriding existing values. To avoid changing the attributes of existing subpartitions, use the FOR PARTITION clause of the modify_default_ attributes_clause.
s
s
Restriction: If table is hash partitioned, you can specify only the allocate_extent and deallocate_unused clauses. All other attributes of the partition are inherited from the tablelevel defaults except TABLESPACE, which stays the same as it was at create time. add_subpartition_ clause adds a hash subpartition to partition. Oracle populates the new subpartition with rows rehashed from the other subpartition(s) of partition as determined by the hash function. Oracle marks UNUSABLE, and you must rebuild, the local index subpartitions corresponding to the added and to the rehashed subpartitions. If you do not specify subpartition, Oracle assigns a name in the form SYS_SUBPnnn If you do not specify TABLESPACE, the new subpartition will reside in the default tablespace of partition. COALESCE SUBPARTITION specifies that Oracle should select a hash subpartition, distribute its contents into one or more remaining subpartitions (determined by the hash function), and then drop the selected subpartition. Local index subpartitions corresponding to the selected subpartition are also dropped. Oracle marks UNUSABLE, and you must rebuild, the index subpartitions corresponding to one or more absorbing subpartitions.
7-156 SQL Reference
ALTER TABLE
UNUSABLE LOCAL INDEXES clause
The next two clauses modify the attributes of local index partitions corresponding to partition. UNUSABLE LOCAL INDEXES marks UNUSABLE all the local index partitions associated with partition. REBUILD UNUSABLE LOCAL INDEXES rebuilds the unusable local index partitions associated with partition. Restrictions:
s
You cannot specify this clause with any other clauses of the modify_partition_clause. You cannot specify this clause for partitions that are subpartitioned.
s
modify_ subpartition_ clause
lets you allocate or deallocate storage for an individual subpartition of table. Restriction: The only modify_LOB_storage_parameters you can specify for subpartition are the allocate_extent_clause and deallocate_unused_clause. UNUSABLE LOCAL INDEXES marks UNUSABLE all the local index subpartitions associated with subpartition. REBUILD UNUSABLE LOCAL INDEXES rebuilds the unusable local index subpartitions associated with subpartition.
rename_partition/ subpartition_ clause move_partition_ clause
renames a table partition or subpartition current_name to new_name. For both partitions and subpartitions, new_name must be different from all existing partitions and subpartitions of the same table. moves table partition partition to another segment. You can move partition data to another tablespace, recluster data to reduce fragmentation, or change create-time physical attributes. If the table contains LOB columns, you can use the LOB_storage_clause to move the LOB data and LOB index segments associated with this partition. Only the LOBs named are affected. If you do not specify the LOB_storage_clause for a particular LOB column, its LOB data and LOB index segments are not moved. If partition is not empty, MOVE PARTITION marks UNUSABLE all corresponding local index partitions and all global nonpartitioned indexes, and all the partitions of global partitioned indexes. When you move a LOB data segment, Oracle drops the old data segment and corresponding index segment and creates new segments even if you do not specify a new tablespace.
SQL Statements
7-157
ALTER TABLE
The move operation obtains its parallel attribute from the parallel_clause, if specified. If not specified, the default parallel attributes of the table, if any, are used. If neither is specified, Oracle performs the move without using parallelism. The parallel_clause on MOVE PARTITION does not change the default parallel attributes of table. Note: For index-organized tables, Oracle uses the address of the primary key, as well as its value, to construct logical rowids. The logical rowids are stored in the secondary index of the table. If you move a partition of an index-organized table, the address portion of the rowids will change, which can hamper performance. To ensure optimal performance, rebuild the secondary index(es) on the moved partition to update the rowids. See Also: Oracle8i Concepts for more information on logical rowids. Restrictions:
s
If partition is a hash partition, the only attribute you can specify in this clause is TABLESPACE. You cannot move a partition of a composite-partitioned table. You must move each subpartition separately with the move_subpartition_clause. You cannot specify this clause for a partition containing subpartitions. However, you can move subpartitions using the move_subpartition_clause.
s
s
move_ subpartition_ clause
moves the table subpartition subpartition to another segment. If you do not specify TABLESPACE, the subpartition will remain in the same tablespace. Unless the subpartition is empty, Oracle marks UNUSABLE all local index subpartitions corresponding to the subpartition being moved, as well as global nonpartitioned indexes and partitions of global indexes. If the table contains LOB columns, you can use the LOB_storage_clause to move the LOB data and LOB index segments associated with this subpartition. Only the LOBs named are affected. If you do not specify the LOB_storage_clause for a particular LOB column, its LOB data and LOB index segments are not moved. When you move a LOB data segment, Oracle drops the old data segment and corresponding index segment and creates new segments even if you do not specify a new tablespace.
add_range_ partition_clause
adds a new range partition partition to the "high" end of a partitioned table (after the last existing partition). You can specify any create-time physical attributes for the new partition. If the table contains LOB columns, you can also specify partition-level attributes for one or more LOB items. You can specify up to 64K-1 partitions. For a discussion of factors that might impose practical limits less than this number, refer to Oracle8i Administrator's Guide.
7-158 SQL Reference
ALTER TABLE
Restrictions:
s
If the first element of the partition bound of the high partition is MAXVALUE, you cannot add a partition to the table. Instead, use the split_partition_clause to add a partition at the beginning or the middle of the table. The compression_clause, physical_attributes_clause, and OVERFLOW are valid only for a partitioned index-organized table. You cannot specify the PCTUSED parameter for the index segment of an indexorganized table. You can specify OVERFLOW only if the partitioned table already has an overflow segment. You can specify compression only if compression is enabled at the table level. specifies the upper bound for the new partition. The value_list is a comma-separated, ordered list of literal values corresponding to column_list. The value_list must collate greater than the partition bound for the highest existing partition in the table. is permitted only for a composite-partitioned table. This clause lets you specify particular hash subpartitions for partition. You specify composite partitioning in one of two ways:
s
s
s
s
s
VALUES LESS THAN (value_list)
partition_level_ subpartitioning
You can specify individual subpartitions by name, and optionally the tablespace where each should be stored, or You can specify the number of subpartitions (and optionally one or more tablespaces where they are to be stored). In this case, Oracle assigns partition names of the form SYS_SUBPnnn. The number of tablespaces does not have to equal the number of subpartitions. If the number of subpartitions is greater than the number of tablespaces, Oracle cycles through the names of the tablespaces.
s
The subpartitions inherit all their attributes from any attributes specified for new_partition, except for TABLESPACE, which you can specify at the subpartition level. Any attributes not specified at the subpartition or partition level are inherited from table-level defaults. This clause overrides any subpartitioning specified at the table level. If you do not specify this clause but you specified default subpartitioning at the table level, new_partition_name will inherit the table-level default subpartitioning (see "CREATE TABLE" on page 4-381).
SQL Statements
7-159
ALTER TABLE
add_hash_ partition_clause
adds a new hash partition to the "high" end of a partitioned table. Oracle will populate the new partition with rows rehashed from other partitions of table as determined by the hash function. You can specify a name for the partition, and optionally a tablespace where it should be stored. If you do not specify new_partition_name, Oracle assigns a partition name of the form SYS_Pnnn. If you do not specify TABLESPACE, the new partition is stored in the table's default tablespace. Other attributes are always inherited from table-level defaults. See Also: "CREATE TABLE" on page 4-381 and Oracle8i Concepts for more information on hash partitioning. parallel_clause lets you specify whether to parallelize the creation of the new partition.
coalesce_ partition_clause
applies only to hash-partitioned tables. This clause specifies that Oracle should select a hash partition, distribute its contents into one or more remaining partitions (determined by the hash function), and then drop the selected partition. Local index partitions corresponding to the selected partition are also dropped. Oracle marks UNUSABLE, and you must rebuild, the local index partitions corresponding to one or more absorbing partitions. applies only to tables partitioned using the range or composite method. This clause removes partition partition, and the data in that partition, from a partitioned table. If you want to drop a partition but keep its data in the table, you must merge the partition into one of the adjacent partitions. See the merge_partitions_clause of this statement. If the table has LOB columns, the LOB data and LOB index partitions (and their subpartitions, if any) corresponding to partition are also dropped.
s
drop_partition_ clause
Oracle drops local index partitions and subpartitions corresponding to partition, even if they are marked UNUSABLE. Oracle marks UNUSABLE all global nonpartitioned indexes defined on the table and all partitions of global partitioned indexes, unless the partition being dropped or all of its subpartitions are empty. If you drop a partition and later insert a row that would have belonged to the dropped partition, Oracle stores the row in the next higher partition. However, if that partition is the highest partition, the insert will fail because the range of values represented by the dropped partition is no longer valid for the table.
s
s
Restriction: If table contains only one partition, you cannot drop the partition. You must drop the table. truncate_ partition_clause truncate_ subpartition_ clause PARTITION removes all rows from partition or, if the table is composite-partitioned, all rows from partition's subpartitions. SUBPARTITION removes all rows from subpartition. If the table contains any LOB columns, the LOB data and LOB index segments for this partition are also truncated. If the table is composite-partitioned, the LOB data and LOB index segments for this partition's subpartitions are truncated.
7-160 SQL Reference
ALTER TABLE
If the partition or subpartition to be truncated contains data, you must first disable any referential integrity constraints on the table. Alternatively, you can delete the rows and then truncate the partition. For each partition or subpartition truncated, Oracle also truncates corresponding local index partitions and subpartitions. If those index partitions or subpartitions are marked UNUSABLE, Oracle truncates them and resets the UNUSABLE marker to VALID. In addition, if the truncated partition or subpartition, or any of the subpartitions of the truncated partition are not empty, Oracle marks as UNUSABLE all global nonpartitioned indexes and partitions of global indexes defined on the table. DROP STORAGE deallocates space from the deleted rows and makes it available for use by other schema objects in the tablespace.
REUSE STORAGE keeps space from the deleted rows allocated to the partition or subpartition. The space is subsequently available only for inserts and updates to the same partition or subpartition. split_partition_ clause from an original partition partition_name_old, creates two new partitions, each with a new segment and new physical attributes, and new initial extents. The segment associated with partition_name_old is discarded. Restriction: You cannot specify this clause for a hash-partitioned table. AT (value_ list) specifies the new noninclusive upper bound for split_partition_1. The value_list must compare less than the original partition bound for partition_name_old and greater than the partition bound for the next lowest partition (if there is one). describes the two partitions resulting from the split. specifies optional names and physical attributes of the two partitions resulting from the split. If you do not specify new partition names, Oracle assigns names of the form SYS_Pn. Any attributes you do not specify are inherited from partition_name_old. Restriction:
s
INTO partition_ description, partition_ description
You can specify the compression_clause, physical_attributes_clause, and OVERFLOW only for a partitioned index-organized table. You cannot specify the PCTUSED parameter for the index segment of an index-organized table.
s
parallel_clause
parallelizes the split operation, but does not change the default parallel attributes of the table.
If you specify subpartitioning for the new partitions, you can specify only TABLESPACE for the subpartitions. All other attributes will be inherited from the containing new partition. If partition_name_old is subpartitioned, and you do not specify any subpartitioning for the new partitions, the new partitions will inherit the number and tablespaces of the subpartitions in partition_name_old.
SQL Statements
7-161
ALTER TABLE
Oracle also splits corresponding local index partitions, even if they are marked UNUSABLE. The resulting local index partitions inherit all their partition-level default attributes from the local index partition being split. If partition_name_old was not empty, Oracle marks UNUSABLE all global nonpartitioned indexes and all partitions of global indexes on the table. (This action on global indexes does not apply to index-organized tables.) In addition, if any partitions or subpartitions resulting from the split are not empty, Oracle marks as UNUSABLE all corresponding local index partitions and subpartitions. If table contains LOB columns, you can use the LOB_storage_clause to specify separate LOB storage attributes for the LOB data segments resulting from the split. Oracle drops the LOB data and LOB index segments of partition_name_old and creates new segments for each LOB column, for each partition, even if you do not specify a new tablespace. merge_partitions_ clause merges the contents of two adjacent partitions of table into one new partition, and then drops the original two partitions. The new partition inherits the partition-bound of the higher of the two original partitions. Any attributes not specified in the segment_attributes_clause are inherited from table-level defaults. If you do not specify new_partition_name, Oracle assigns a name of the form SYS_Pnnn. If the new partition has subpartitions, Oracle assigns subpartition names of the form SYS_ SUBPnnn. If either or both of the original partitions was not empty, Oracle marks UNUSABLE all global nonpartitioned global indexes and all partitions of global indexes on the table. In addition, if the partition or any of its subpartitions resulting from the merge is not empty, Oracle marks UNUSABLE all corresponding local index partitions and subpartitions. Restriction: You cannot specify this clause for an index-organized table or for a table partitioned using the hash method. partition_level_ partitioning specifies hash subpartitioning attributes for the new partition. Any attributes not specified in this clause are inherited from table-level defaults. If you do not specify this clause, the new merged partition inherits subpartitioning attributes from table-level defaults. parallel_clause exchange_ partition_clause exchange_ subpartition_ clause specifies that the merging operation is to be parallelized.
lets you exchange the data and index segments of
s s
a hash or range partition (or subpartition) with a nonpartitioned table a hash-partitioned table with a range partition of a composite-partitioned table
The default behavior is EXCLUDING INDEXES WITH VALIDATION. You must have ALTER TABLE privileges on both tables to perform this operation. This clause facilitates high-speed data loading when used with transportable tablespaces. For information on this topic, see Oracle8i Administrator's Guide.
7-162 SQL Reference
ALTER TABLE
If table contains LOB columns, for each LOB column Oracle exchanges LOB data and LOB index partition or subpartition segments with corresponding LOB data and LOB index segments of table. All statistics of the table and partition are exchanged, including table, column, index statistics, and histograms. The aggregate statistics of the table receiving the new partition are recalculated. The logging attribute of the table and partition is also exchanged. Restriction: Both tables involved in the exchange must have the same primary key, and no validated foreign keys can be referencing either of the tables unless the referenced table is empty. WITH TABLE table specifies the table with which the partition will be exchanged. INCLUDING INDEXES EXCLUDING INDEXES WITH VALIDATION WITHOUT VALIDATION EXCEPTIONS INTO specifies that the local index partitions or subpartitions should be exchanged with the corresponding table index (for a nonpartitioned table) or local indexes (for a hashpartitioned table). specifies that all index partitions or subpartitions corresponding to the partition and all the regular indexes and index partitions on the exchanged table are marked UNUSABLE. specifies that if any rows in the exchanged table do not map into partitions or subpartitions being exchanged, Oracle should return an error. specifies that the proper mapping of rows in the exchanged table is not checked. specifies a table into which Oracle places the rowids of all rows violating the constraint. If you omit schema, Oracle assumes the exceptions table is in your own schema. If you omit this clause altogether, Oracle assumes that the table is named EXCEPTIONS. The exceptions table must be on your local database. You can create the EXCEPTIONS table using one of these scripts:
s
UTLEXCPT.SQL uses physical rowids. Therefore it can accommodate rows from conventional tables but not from index-organized tables. (See the Note that follows.) UTLEXPT1.SQL uses universal rowids, so it can accommodate rows from both conventional and index-organized tables.
s
If you create your own exceptions table, it must follow the format prescribed by one of these two scripts. See Oracle8i Migration for compatibility issues related to the use of these scripts. Note: If you are collecting exceptions from index-organized tables based on primary keys (rather than universal rowids), you must create a separate exceptions table for each indexorganized table to accommodate its primary-key storage. You create multiple exceptions tables with different names by modifying and resubmitting the script. For information on the SQL scripts, see the DBMS_IOT package in Oracle8i Supplied PL/ SQL Packages Reference. For information on eliminating migrated and chained rows, see Oracle8i Designing and Tuning for Performance.
SQL Statements
7-163
ALTER TABLE
Restrictions on EXCEPTIONS INTO clause:
s s
This clause is not valid with subpartitions. The partitioned table must have been defined with a UNIQUE constraint, and that constraint must be in DISABLE VALIDATE state.
If these conditions are not true, Oracle ignores this clause. See Also: The "constraint_clause" on page 7-233 for more information on constraint checking. Restrictions on exchanging partitions: When exchanging between a hash-partitioned table and the range partition of a composite-partitioned table, the following restrictions apply:
s
The partitioning key of the hash-partitioned table must be identical to the subpartitioning key of the composite-partitioned table. The number of partitions in the hash-partitioned table must be identical to the number of subpartitions in the range partition of the composite-partitioned table. Oracle marks UNUSABLE all global indexes on both tables.
s
s
For partitioned index-organized tables, the following additional restrictions apply:
s
The source and target table/partition must have their primary key set on the same columns, in the same order. If compression is enabled, it must be enabled for both the source and the target, and with the same prefix length. An index-organized table partition cannot be exchanged with a regular table or vice versa. Both the source and target must have overflow segments, or neither can have overflow segments. determines whether a row can be moved to a different partition or subpartition because of a change to one or more of its key values. Restriction: You can specify this clause only for a partitioned table. ENABLE allows Oracle to move a row to a different partition or subpartition as the result of an update to the partitioning or subpartitioning key. Restriction: You cannot specify this clause if a domain index has been built on any column of the table. WARNING: Moving a row in the course of an UPDATE operation changes that row's rowid. DISABLE returns an error if an update to a partitioning or subpartitioning key would result in a row moving to a different partition or subpartition. This is the default.
s
s s
row_movement_ clause
parallel_clause
changes the default degree of parallelism for queries and DML on the table. For additional information, see the Notes to the parallel_clause of "CREATE TABLE" on page 4-381.
7-164 SQL Reference
ALTER TABLE
NOPARALLEL PARALLEL
specifies serial execution. This is the default. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances times the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution processes. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer. Restriction: If table contains any columns of LOB or user-defined object type, subsequent INSERT, UPDATE, and DELETE operations on table are executed serially without notification. Subsequent queries, however, will be executed in parallel. Note: If you specify the parallel_clause in conjunction with the move_table_clause, the parallelism applies only to the move, not to subsequent DML and query operations on the table. enable_disable_ clause ENABLE TABLE LOCK lets you specify whether Oracle should apply an integrity constraint. For a complete description of this clause, including notes and restrictions that relate to this statement, see the enable_disable_clause of "CREATE TABLE" on page 4-381. enables DML and DDL locks on a table in a parallel server environment. See Also: Oracle8i Parallel Server Concepts. Note: DML table locks are not acquired on temporary tables. DISABLE TABLE LOCK disables DML and DDL locks on a table to improve performance in a parallel server environment. See Also: Oracle8i Parallel Server Concepts. ENABLE ALL TRIGGERS enables all triggers associated with the table. Oracle fires the triggers whenever their triggering condition is satisfied. See "CREATE TRIGGER" on page 7-426. To enable a single trigger, use the enable_clause of ALTER TRIGGER. See "ALTER TRIGGER" on page 7-183. DISABLE ALL TRIGGERS disables all triggers associated with the table. Oracle will not fire a disabled trigger even if the triggering condition is satisfied.
Examples
Nested Table Example The following statement modifies the storage characteristics of a nested table column PROJECTS in table EMP so that when queried it returns actual values instead of locators:
ALTER TABLE emp MODIFY NESTED TABLE projects RETURN AS VALUE;
SQL Statements
7-165
ALTER TABLE
The following statement specifies parallel processing for queries to the EMP table:
PARALLEL Example
ALTER TABLE emp PARALLEL;
ENABLE VALIDATE Example The following statement places in ENABLE VALIDATE state an integrity constraint named FK_DEPTNO in the EMP table:
ALTER TABLE emp ENABLE VALIDATE 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 also identify the exceptions in the EMP table with the following statement:
SELECT emp.* FROM emp e, except_table ex WHERE e.row_id = ex.row_id AND ex.table_name = 'EMP' AND ex.constraint = 'FK_DEPTNO';
The following statement tries to place in ENABLE NOVALIDATE state two constraints on the EMP table:
ENABLE NOVALIDATE Example
ALTER TABLE emp ENABLE NOVALIDATE UNIQUE (ename) ENABLE NOVALIDATE CONSTRAINT nn_ename;
This statement has two ENABLE clauses:
s
The first places a unique constraint on the ENAME column in ENABLE NOVALIDATE state. The second places the constraint named NN_ENAME in ENABLE NOVALIDATE state.
s
In this case, Oracle enables the constraints only if both are satisfied by each row in the table. If any row violates either constraint, Oracle returns an error and both constraints remain disabled. 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
DISABLE Example
7-166 SQL Reference
ALTER TABLE
and PHONENO columns of the CUSTOMERS table. The following statement disables the unique key on the combination of the AREACO and PHONENO columns of the CUSTOMERS table:
ALTER TABLE customers DISABLE UNIQUE (areaco, phoneno) CASCADE;
The unique key in the CUSTOMERS table is referenced by the foreign key in the PHONE_CALLS table, so you must use the CASCADE clause to disable the unique key. This clause disables the foreign key as well.
CHECK Example
The following 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. The constraint is disabled, so you can increase an employee's compensation above this limit.
Triggers Example The following statement enables all triggers associated with the
EMP table:
ALTER TABLE emp ENABLE ALL TRIGGERS;
DEALLOCATE UNUSED Example The following statement frees all unused space for reuse in table EMP, where the high water mark is above MINEXTENTS:
ALTER TABLE emp DEALLOCATE UNUSED;
This statement illustrates the drop_column_clause with CASCADE CONSTRAINTS. Assume table T1 is created as follows:
DROP COLUMN Example
CREATE TABLE t1 ( pk NUMBER PRIMARY KEY, fk NUMBER, c1 NUMBER, c2 NUMBER, CONSTRAINT ri FOREIGN KEY (fk) REFERENCES t1, CONSTRAINT ck1 CHECK (pk > 0 and c1 > 0), CONSTRAINT ck2 CHECK (c2 > 0)
SQL Statements
7-167
ALTER TABLE
);
An error will be returned for the following statements:
ALTER TABLE t1 DROP (pk); -- pk is a parent key ALTER TABLE t1 DROP (c1); -- c1 is referenced by multicolumn constraint ck1
Submitting the following statement drops column PK, the primary key constraint, the foreign key constraint, RI, and the check constraint, CK1:
ALTER TABLE t1 DROP (pk) CASCADE CONSTRAINTS;
If all columns referenced by the constraints defined on the dropped columns are also dropped, then CASCADE CONSTRAINTS is not required. For example, assuming that no other referential constraints from other tables refer to column PK, then it is valid to submit the following statement without the CASCADE CONSTRAINTS clause:
ALTER TABLE t1 DROP (pk, fk, c1);
Index-Organized Table Examples
This statement modifies the INITRANS parameter for the index segment of index-organized table DOCINDEX:
ALTER TABLE docindex INITRANS 4;
The following statement adds an overflow data segment to index-organized table DOCINDEX:
ALTER TABLE docindex ADD OVERFLOW;
This statement modifies the INITRANS parameter for the overflow data segment of index-organized table DOCINDEX:
ALTER TABLE docindex OVERFLOW INITRANS 4;
ADD PARTITION Example The following statement adds a partition P3 and specifies storage characteristics for three of the table's LOB columns (B, C, and D):
ALTER TABLE pt ADD PARTITION p3 VALUES LESS THAN (30) LOB (b, d) STORE AS (TABLESPACE tsz) LOB (c) STORE AS mylobseg;
The LOB data and LOB index segments for columns B and D in partition P3 will reside in tablespace TSZ. The remaining attributes for these LOB columns will be inherited first from the table-level defaults, and then from the tablespace defaults.
7-168 SQL Reference
ALTER TABLE
The LOB data segments for column C will reside in the MYLOBSEG segment, and will inherit all other attributes from the table-level defaults and then from the tablespace defaults.
SPLIT PARTITION Example The following statement splits partition P3 into
partitions P3_1 and P3_2:
ALTER TABLE pt SPLIT PARTITION p3 AT (25) INTO (PARTITION p3_1 TABLESPACE ts4 LOB (b,d) STORE AS (TABLESPACE tsz), PARTITION p3_2 (TABLESPACE ts5) LOB (c) STORE AS (TABLESPACE ts5);
In partition P3_1, Oracle creates the LOB segments for columns B and D in tablespace TSZ. In partition P3_2, Oracle creates the LOB segments for column C in tablespace TS5. The LOB segments for columns B and D in partition P3_2 and those for column C in partition P3_1 remain in original tablespace for the original partition P3. However, Oracle creates new segments for all the LOB data and LOB index segments, even though they are not moved to a new tablespace. The following statements create an object type, a corresponding object table with a primary-key-based object identifier, and a table having a user-defined REF column:
User-Defined Object Identifier Example
CREATE TYPE emp_t AS OBJECT (empno NUMBER, address CHAR(30)); CREATE TABLE emp OF emp_t ( empno PRIMARY KEY) OBJECT IDENTIFIER IS PRIMARY KEY; CREATE TABLE dept (dno NUMBER, mgr_ref REF emp_t SCOPE is emp);
The next statements add a constraint and a user-defined REF column, both of which reference table EMP:
ALTER TABLE dept ADD CONSTRAINT mgr_cons FOREIGN KEY (mgr_ref) REFERENCES emp; ALTER TABLE dept ADD sr_mgr REF emp_t REFERENCES emp;
Add Column Example The following 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
SQL Statements
7-169
ALTER TABLE
ADD (thriftplan NUMBER(7,2), loancode CHAR(1) NOT NULL);
Modify Column Examples
The following 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. The following 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;
The following statement allocates an extent of 5 kilobytes for the EMP table and makes it available to instance 4:
ALLOCATE EXTENT Example
ALTER TABLE emp ALLOCATE EXTENT (SIZE 5K INSTANCE 4);
Because this statement omits the DATAFILE parameter, Oracle allocates the extent in one of the datafiles belonging to the tablespace containing the table.
DEFAULT Examples This statement 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 ------ ------- ---
7-170 SQL Reference
ALTER TABLE
815234
LEWIS
0
To discontinue previously specified default values, so that they are no longer automatically inserted into newly added rows, replace the values with nulls, as shown in this statement:
ALTER TABLE accounts MODIFY (bal DEFAULT NULL);
The MODIFY clause need only specify the column name and the modified part of the definition, rather than the entire column definition. This statement has no effect on any existing values in existing rows.
Drop Constraint Examples The following 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 the following statement:
ALTER TABLE dept DROP CONSTRAINT pk_dept CASCADE;
The CASCADE clause drops any foreign keys that reference the primary key. The following statement drops the unique key on the DNAME column of the DEPT table:
ALTER TABLE dept DROP UNIQUE (dname);
The DROP clause in this statement omits the CASCADE clause. Because of this omission, Oracle does not drop the unique key if any foreign key references it.
LOB Examples The following statement adds CLOB column RESUME to the
EMPLOYEE table and specifies LOB storage characteristics for the new column:
ALTER TABLE employee ADD (resume CLOB) LOB (resume) STORE AS resume_seg (TABLESPACE resume_ts);
To modify the LOB column RESUME to use caching, enter the following statement:
ALTER TABLE employee MODIFY LOB (resume) (CACHE);
SQL Statements
7-171
ALTER TABLE
Nested Table Examples The following statement adds the nested table column SKILLS to the EMPLOYEE table:
ALTER TABLE employee ADD (skills skill_table_type) NESTED TABLE skills STORE AS nested_skill_table;
You can also modify a nested table's storage characteristics. Use the name of the storage table specified in the nested_table_storage_clause to make the modification. You cannot query or perform DML statements on the storage table. Use the storage table only to modify the nested table column storage characteristics. The following statement creates table VETSERVICE with nested table column CLIENT and storage table CLIENT_TAB. Nested table VETSERVICE is modified to specify constraints:
CREATE TYPE pet_table AS OBJECT (pet_name VARCHAR2(10), pet_dob DATE); CREATE TABLE vetservice (vet_name VARCHAR2(30), client pet_table) NESTED TABLE client STORE AS client_tab; ALTER TABLE client_tab ADD UNIQUE (ssn);
The following statement adds a UNIQUE constraint to nested table NESTED_SKILL_ TABLE:
ALTER TABLE nested_skill_table ADD UNIQUE (a);
The following statement alters the storage table for a nested table of REF values to specify that the REF is scoped:
CREATE TYPE emp_t AS OBJECT (eno number, ename char(31)); CREATE TYPE emps_t AS TABLE OF REF emp_t; CREATE TABLE emptab OF emp_t; CREATE TABLE dept (dno NUMBER, employees emps_t) NESTED TABLE employees STORE AS deptemps; ALTER TABLE deptemps ADD (SCOPE FOR (column_value) IS emptab);
Similarly, to specify storing the REF with rowid:
ALTER TABLE deptemps ADD (REF(column_value) WITH ROWID);
In order to execute these ALTER TABLE statements successfully, the storage table DEPTEMPS must be empty. Also, because the nested table is defined as a table of
7-172 SQL Reference
ALTER TABLE
scalars (REFs), Oracle implicitly provides the column name COLUMN_VALUE for the storage table.
See Also:
s
"CREATE TABLE" on page 4-381 for more information about nested table storage. Oracle8i Application Developer's Guide - Fundamentals for more information about nested tables.
s
REF Examples
In the following statement an object type DEPT_T has been previously defined. Now, create table EMP as follows:
CREATE TABLE emp (name VARCHAR(100), salary NUMBER, dept REF dept_t);
An object table DEPARTMENTS is created as:
CREATE TABLE departments OF dept_t;
The DEPT column can store references to objects of DEPT_T stored in any table. If you would like to restrict the references to point only to objects stored in the DEPARTMENTS table, you could do so by adding a scope constraint on the DEPT column as follows:
ALTER TABLE emp ADD (SCOPE FOR (dept) IS departments);
The above ALTER TABLE statement will succeed only if the EMP table is empty. If you want the REF values in the DEPT column of EMP to also store the rowids, issue the following statement:
ALTER TABLE emp ADD (REF(dept) WITH ROWID);
Add Partition Example
The following statement adds partition JAN99 to
tablespace TSX:
ALTER TABLE sales ADD PARTITION jan99 VALUES LESS THAN( '970201' ) TABLESPACE tsx;
Drop Partition Example
The following statement drops partition DEC98:
SQL Statements
7-173
ALTER TABLE
ALTER TABLE sales DROP PARTITION dec98;
Exchange Partition Example The following statement converts partition FEB97 to
table SALES_FEB97 without exchanging local index partitions with corresponding indexes on SALES_FEB97 and without verifying that data in SALES_FEB97 falls within the bounds of partition FEB97:
ALTER TABLE sales EXCHANGE PARTITION feb97 WITH TABLE sales_feb97 WITHOUT VALIDATION;
Modify Partition Examples The following statement marks all the local index
partitions corresponding to the NOV96 partition of the SALES table UNUSABLE:
ALTER TABLE sales MODIFY PARTITION nov96 UNUSABLE LOCAL INDEXES;
The following statement rebuilds all the local index partitions that were marked UNUSABLE:
ALTER TABLE sales MODIFY PARTITION jan97 REBUILD UNUSABLE LOCAL INDEXES;
The following statement changes MAXEXTENTS and logging attribute for partition BRANCH_NY:
ALTER TABLE branch MODIFY PARTITION branch_ny STORAGE (MAXEXTENTS 75) LOGGING;
Move Partition Example
The following statement moves partition DEPOT2 to
tablespace TS094:
ALTER TABLE parts MOVE PARTITION depot2 TABLESPACE ts094 NOLOGGING;
Rename Partition Examples
The following statement renames a table:
ALTER TABLE emp RENAME TO employee;
In the following statement, partition EMP3 is renamed:
ALTER TABLE employee RENAME PARTITION emp3 TO employee3;
Split Partition Example
The following statement splits the old partition DEPOT4, creating two new partitions, naming one DEPOT9 and reusing the name of the old partition for the other:
7-174 SQL Reference
ALTER TABLE
ALTER TABLE parts SPLIT PARTITION depot4 AT ( '40-001' ) INTO ( PARTITION depot4 TABLESPACE ts009 STORAGE (MINEXTENTS 2), PARTITION depot9 TABLESPACE ts010 ) PARALLEL (10);
Truncate Partition Example The following statement deletes all the data in the
SYS_P017 partition and deallocates the freed space:
ALTER TABLE deliveries TRUNCATE PARTITION sys_p017 DROP STORAGE;
Additional Examples
For examples of defining integrity constraints with the ALTER TABLE statement, see the "constraint_clause" on page 7-233. For examples of changing the value of a table's storage parameters, see the "storage_clause" on page 7-605.
SQL Statements
7-175
ALTER TABLESPACE
ALTER TABLESPACE
Syntax
ALTER TABLESPACE tablespace
datafile/tempfile_clauses DEFAULT storage_clause K M MINIMUM ONLINE NORMAL TEMPORARY IMMEDIATE FOR OFFLINE BEGIN BACKUP END ONLY READ WRITE PERMANENT TEMPORARY COALESCE LOGGING NOLOGGING RECOVER ; EXTENT integer
7-176 SQL Reference
ALTER TABLESPACE
datafile/tempfile_clauses::=
, DATAFILE ADD TEMPFILE , RENAME DATAFILE ' filename ' TO ' , filename ' ' filespec ' autoextend_clause
filespec: See "filespec" on page 7-516. autoextend_clause::=
OFF K AUTOEXTEND NEXT ON integer M maxsize_clause
maxsize_clause::=
UNLIMITED MAXSIZE integer K M
storage_clause: See "storage_clause" on page 7-605.
Purpose
To alter an existing tablespace or one or more of its datafiles or tempfiles. For information on creating a tablespace, see "CREATE TABLESPACE" on page 4-419.
SQL Statements
7-177
ALTER TABLESPACE
Prerequisites
If you have ALTER TABLESPACE system privilege, you can perform any of this statement's operations. If you have MANAGE TABLESPACE system privilege, you can only perform the following operations:
s
take the tablespace online or offline begin or end a backup make the tablespace read-only or read-write
s
s
Before you can make a tablespace read-only, the following conditions must be met:
s
The tablespace must be online. The tablespace must not contain any active rollback segments. For this reason, the SYSTEM tablespace can never be made read-only, because it contains the SYSTEM rollback segment. Additionally, because the rollback segments of a read-only tablespace are not accessible, Oracle recommends that you drop the rollback segments before you make a tablespace read-only. The tablespace must not be involved in an open backup, because the end of a backup updates the header file of all datafiles in the tablespace.
s
s
Performing this function in restricted mode may help you meet these restrictions, because only users with RESTRICTED SESSION system privilege can be logged on.
Keywords and Parameters
tablespace is the name of the tablespace to be altered. Note: For locally managed temporary tablespaces, the only clause you can specify in this statement in the ADD clause. LOGGING | NOLOGGING specifies the default logging attribute of all tables, indexes, and partitions within the tablespace. The tablespace-level logging attribute can be overridden by logging specifications at the table, index, and partition levels. When an existing tablespace logging attribute is changed by an ALTER TABLESPACE statement, all tables, indexes, and partitions created after the statement will have the new default logging attribute (which you can still subsequently override). The logging attributes of existing objects are not changed. Only the following operations support NOLOGGING mode:
s
DML: direct-load INSERT (serial or parallel); Direct Loader (SQL*Loader)
7-178 SQL Reference
ALTER TABLESPACE
s
DDL: CREATE TABLE ... AS SELECT, CREATE INDEX, ALTER INDEX ... REBUILD, ALTER INDEX ... REBUILD PARTITION, ALTER INDEX ... SPLIT PARTITION, ALTER TABLE ... SPLIT PARTITION, ALTER TABLE ... MOVE PARTITION.
In NOLOGGING mode, data is modified with minimal logging (to mark new extents invalid and to record dictionary changes). When applied during media recovery, the extent invalidation records mark a range of blocks as logically corrupt, because the redo data is not logged. Therefore, if you cannot afford to lose the object, it is important to take a backup after the NOLOGGING operation. datafile/tempfile_ adds or modifies a datafile or tempfile. clauses ADD DATAFILE | TEMPFILE Adds to the tablespace a datafile or tempfile specified by filespec (see "filespec" on page 7-516). You can add a datafile or tempfile to a locally managed tablespace that is online or to a dictionary managed tablespace that is online or offline. Be sure the file is not in use by another database. Note: For locally managed temporary tablespaces, this is the only clause you can specify at any time. RENAME DATAFILE renames one or more of the tablespace's datafiles. Take the tablespace offline before renaming the datafile. Each 'filename' must fully specify a datafile using the conventions for filenames on your operating system. This clause merely 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. autoextend_ clause enables or disables the autoextending of the size of the datafile in the tablespace. OFF disables autoextend if it is turned on. NEXT and MAXSIZE are set to zero. Values for NEXT and MAXSIZE must be respecified in further ALTER TABLESPACE AUTOEXTEND statements. enables autoextend. specifies the size in bytes of the next increment of disk space to be allocated automatically to the datafile when more extents are required. Use K or M to specify this size in kilobytes or megabytes. The default is one data block. specifies maximum disk space allowed for automatic extension of the datafile. UNLIMITED sets no limit on allocating disk space to the datafile.
ON NEXT
maxsize_clause
SQL Statements
7-179
ALTER TABLESPACE
DEFAULT storage_clause
specifies the new default storage parameters for objects subsequently created in the tablespace. For a dictionary-managed temporary table, Oracle considers only the NEXT parameter of the storage_clause. See the "storage_clause" on page 7-605. Restriction: You cannot specify this clause for a locally managed tablespace.
MINIMUM EXTENT integer
controls free space fragmentation in the tablespace by ensuring that every used or free extent size in a tablespace is at least as large as, and is a multiple of, integer. This clause is not relevant for a dictionary-managed temporary tablespace. Restriction: You cannot specify this clause for a locally managed tablespace. See Also: Oracle8i Administrator's Guide for more information about using MINIMUM EXTENT to control space fragmentation.
ONLINE OFFLINE
brings the tablespace online. takes the tablespace offline and prevents further access to its segments. NORMAL flushes all blocks in all datafiles in the tablespace out of the SGA. You need not perform media recovery on this tablespace before bringing it back online. This is the default. performs a checkpoint for all online datafiles 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. 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. takes the production database tablespaces in the recovery set offline for tablespace point-in-time recovery. For additional information see Oracle8i Backup and Recovery Guide.
TEMPORARY
IMMEDIATE
FOR RECOVER
Suggestion: Before taking a tablespace offline for a long time, you may want to alter the tablespace allocation of 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. See Also: "ALTER USER" on page 7-193. BEGIN BACKUP signifies that an open backup is to be performed on the datafiles that make up this tablespace. This clause does not prevent users from accessing the tablespace. You must use this clause before beginning an open backup. You cannot use this clause on a read-only tablespace. Note: While the backup is in progress, you cannot take the tablespace offline normally, shut down the instance, or begin another backup of the tablespace. END BACKUP signifies that an open backup of the tablespace is complete. Use this clause as soon as possible after completing an open backup. You cannot use this clause on a read-only tablespace.
7-180 SQL Reference
ALTER TABLESPACE
If you forget to indicate the end of an online tablespace backup, and an instance failure or SHUTDOWN ABORT occurs, Oracle assumes that media recovery (possibly requiring archived redo log) is necessary at the next instance start up. To restart the database without media recovery, see Oracle8i Administrator's Guide. READ ONLY places the tablespace in transition read-only mode. In this state, existing transactions can complete (commit or roll back), but no further write operations (DML) are allowed to the tablespace except for rollback of existing transactions that previously modified blocks in the tablespace. Once a tablespace is read only, you can copy its files to read-only media. You must then rename the datafiles in the control file to point to the new location by using the SQL statement ALTER DATABASE ... RENAME. See "ALTER DATABASE" on page 7-6. See Also: Oracle8i Concepts for more information on read-only tablespaces. READ WRITE PERMANENT signifies that write operations are allowed on a previously read-only tablespace. specifies that the tablespace is to be converted from a temporary to a permanent one. A permanent tablespace is one in which permanent database objects can be stored. This is the default when a tablespace is created. specifies that the tablespace is to be converted from a permanent to a temporary one. A temporary tablespace is one in which no permanent database objects can be stored. Objects in a temporary tablespace persist only for the duration of the session. for each datafile in the tablespace, coalesces all contiguous free extents into larger contiguous extents.
TEMPORARY
COALESCE
Examples
Backup Examples The following statement signals to the database that a backup
is about to begin:
ALTER TABLESPACE accounting BEGIN BACKUP;
The following statement signals to the database that the backup is finished:
ALTER TABLESPACE accounting END BACKUP;
Moving and Renaming Example This example moves and renames a datafile
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 clause:
SQL Statements
7-181
ALTER TABLESPACE
ALTER TABLESPACE accounting OFFLINE NORMAL; 2. 3.
Copy the file from 'DISKA:PAY1.DAT' to 'DISKB:RECEIVE1.DAT' using your operating system's commands. Rename the datafile using the ALTER TABLESPACE statement with the RENAME DATAFILE clause:
ALTER TABLESPACE accounting RENAME DATAFILE 'diska:pay1.dbf' TO 'diskb:receive1.dbf';
4.
Bring the tablespace back online using an ALTER TABLESPACE statement with the ONLINE clause:
ALTER TABLESPACE accounting ONLINE;
Adding a Datafile Example The following statement adds a datafile to the tablespace and changes the default logging attribute to NOLOGGING. When more space is needed, new extents of size 10 kilobytes will be added up to a maximum of 100 kilobytes:
ALTER TABLESPACE accounting NOLOGGING ADD DATAFILE 'disk3:pay3.dbf' SIZE 50K AUTOEXTEND ON NEXT 10K MAXSIZE 100K;
Altering a tablespace logging attribute has no affect on the logging attributes of the existing schema objects within the tablespace. The tablespace-level logging attribute can be overridden by logging specifications at the table, index, and partition levels. The following statement changes the allocation of every extent of TABSPACE_ST to a multiple of 128K:
Changing Extent Allocation Example
ALTER TABLESPACE tabspace_st MINIMUM EXTENT 128K;
7-182 SQL Reference
ALTER TRIGGER
ALTER TRIGGER
Syntax
ENABLE schema. ALTER TRIGGER trigger DISABLE DEBUG COMPILE ;
Purpose
To enable, disable, or compile a database trigger. For information on creating a trigger, see "CREATE TRIGGER" on page 7-426. For information on dropping a trigger, see "DROP TRIGGER" on page 7-505.
Note: This statement does not change the declaration or definition
of an existing trigger. To redeclare or redefine a trigger, use the CREATE TRIGGER statement with OR REPLACE.
Prerequisites
The trigger must be in your own schema or you must have ALTER ANY TRIGGER system privilege. In addition, to alter a trigger on DATABASE, you must have the ADMINISTER DATABASE TRIGGER system privilege.
See Also: "CREATE TRIGGER" on page 7-426 for more information on triggers based on DATABASE.
Keywords and Parameters
schema trigger is the schema containing the trigger. If you omit schema, Oracle assumes the trigger is in your own schema. is the name of the trigger to be altered.
SQL Statements
7-183
ALTER TRIGGER
ENABLE DISABLE COMPILE
enables the trigger. You can also use the ENABLE ALL TRIGGERS clause of ALTER TABLE to enable all triggers associated with a table. See "ALTER TABLE" on page 7-123. disables the trigger. You can also use the DISABLE ALL TRIGGERS clause of ALTER TABLE to disable all triggers associated with a table. See "ALTER TABLE" on page 7-123. explicitly compiles the trigger, whether it is valid or invalid. Explicit recompilation eliminates the need for implicit run-time recompilation and prevents associated run-time compilation errors and performance overhead. Oracle first recompiles objects upon which the trigger depends, if any of these objects are invalid. If Oracle recompiles the trigger successfully, the trigger becomes valid. If recompiling the trigger results in compilation errors, then Oracle returns an error and the trigger remains invalid. You can see the associated compiler error messages with the SQL*Plus command SHOW ERRORS. For information on debugging procedures, see Oracle8i Application Developer's Guide - Fundamentals. For information on how Oracle maintains dependencies among schema objects, including remote objects, see Oracle8i Concepts. DEBUG instructs the PL/SQL compiler to generate and store the code for use by the PL/SQL debugger. This clause can be used for normal triggers and for instead-of triggers.
Examples
Consider a trigger named REORDER created on the INVENTORY table. The trigger 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 the following 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 the following 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. It is possible that a part's inventory falls below its reorder point while the trigger was disabled. In that
7-184 SQL Reference
ALTER TRIGGER
case, when you reenable the trigger, Oracle does not automatically fire the trigger for this part until another transaction further reduces the inventory.
SQL Statements
7-185
ALTER TYPE
ALTER TYPE
Syntax
schema ALTER TYPE . type SPECIFICATION DEBUG COMPILE invoker_rights_clause REPLACE AS OBJECT ( element_list ) ; BODY
element_list::=
, MEMBER attribute datatype , STATIC MAP , ORDER MEMBER function_spec function_spec procedure_spec
,
pragma_clause
invoker_rights_clause::=
CURRENT_USER AUTHID DEFINER
7-186 SQL Reference
ALTER TYPE
pragma_clause::=
, RNDS WNDS method_name PRAGMA RESTRICT_REFERENCES ( DEFAULT WNPS TRUST , RNPS )
Purpose
To recompile the specification and/or body, or to change the specification of an object type by adding new object member subprogram specifications. You cannot change the existing properties (attributes, member subprograms, map or order functions) of an object type, but you can add new member subprogram specifications.
Prerequisites
The object type must be in your own schema and you must have CREATE TYPE or CREATE ANY TYPE system privilege, or you must have ALTER ANY TYPE system privileges.
Keywords and Parameters
schema type COMPILE is the schema that contains the type. If you omit schema, Oracle assumes the type is in your current schema. is the name of an object type, a nested table type, or a rowid type. compiles the object type specification and body. This is the default if neither SPECIFICATION nor BODY is specified. If recompiling the type results in compilation errors, then Oracle returns an error and the type remains invalid. You can see the associated compiler error messages with the SQL*Plus command SHOW ERRORS. SPECIFICATION compiles only the object type specification. BODY compiles only the object type body.
SQL Statements
7-187
ALTER TYPE
DEBUG REPLACE AS OBJECT invoker_rights_ clause
instructs the PL/SQL compiler to generate and store the code for use by the PL/SQL debugger. adds new member subprogram specifications. This clause is valid only for object types, not for nested table or varray types. specifies whether the member functions and procedures of the object type execute with the privileges and in the schema of the user who owns the object type or with the privileges and in the schema of CURRENT_USER. This specification applies to the corresponding type body as well. (For information on how CURRENT_USER is determined, see Oracle8i Concepts and Oracle8i Application Developer's Guide - Fundamentals.) This clause also determines how Oracle resolves external names in queries, DML operations, and dynamic SQL statements in the member functions and procedures of the type. Restriction: You can specify this clause only for an object type, not for a nested table or varray type. See Also: PL/SQL User's Guide and Reference. AUTHID CURRENT_USER specifies that the member functions and procedures of the object type execute with the privileges of CURRENT_USER. This clause creates an "invoker-rights type." This clause also specifies that external names in queries, DML operations, and dynamic SQL statements resolve in the schema of CURRENT_USER. External names in all other statements resolve in the schema in which the type resides. Note: You must specify this clause to maintain invoker-rights status for the type if you created it with this status. Otherise the status will revert to definer rights. AUTHID DEFINER specifies that the member functions and procedures of the object type execute with the privileges of the owner of the schema in which the functions and procedures reside, and that external names resolve in the schema where the member functions and procedures reside. This is the default.
attribute MEMBER | STATIC
is an object attribute name. Attributes are data items with a name and a type specifier that form the structure of the object. specifies a function or procedure subprogram associated with the object type which is referenced as an attribute. For a description of the difference between member and static methods, and for examples, see "CREATE TYPE" on page 7-437. For information about overloading subprogram names within a package, see the PL/SQL User's Guide and Reference. You must specify a corresponding method body in the object type body for each procedure or function specification. See "CREATE TYPE BODY" on page 7-447. procedure_spec is the specification of a procedure subprogram.
7-188 SQL Reference
ALTER TYPE
function_spec pragma_clause
is the specification of a function subprogram.
is a complier directive that denies member functions read/write access to database tables, packaged variables, or both, and thereby helps to avoid side effects. See Also: Oracle8i Application Developer's Guide - Fundamentals. method DEFAULT WNDS WNPS RNDS RNPS TRUST is the name of the MEMBER function or procedure to which the pragma is being applied. specifies that the pragma should be applied to all methods in the type for which a pragma has not been explicitly specified. specifies the constraint writes no database state (does not modify database tables). specifies the constraint writes no package state (does not modify packaged variables). specifies the constraint reads no database state (does not query database tables). specifies the constraint reads no package state (does not reference package variables). specifies that the restrictions listed in the pragma are not actually to be enforced, but are simply trusted to be true.
MAP|ORDER MEMBER function_spec MAP specifies a member function (MAP method) that returns the relative position of a given instance in the ordering of all instances of the object. A map method is called implicitly and induces an ordering of object instances by mapping them to values of a predefined scalar type. Oracle uses the ordering for comparison operators and ORDER BY clauses. If the argument to the map method is null, the map method returns null and the method is not invoked. An object specification can contain only one map method, which must be a function. The result type must be a predefined SQL scalar type, and the map function can have no arguments other than the implicit SELF argument. Note: If type_name will be referenced in queries involving sorts (through ORDER BY, GROUP BY, DISTINCT, or UNION clauses) or joins, and you want those queries to be parallelized, you must specify a MAP member function.
SQL Statements
7-189
ALTER TYPE
ORDER
specifies a member function (ORDER method) that takes an instance of an object as an explicit argument and the implicit SELF argument and returns either a negative, zero, or positive integer. The negative, zero, or positive indicates that the implicit SELF argument is less than, equal to, or greater than the explicit argument. If either argument to the order method is null, the order method returns null and the method is not invoked. When instances of the same object type definition are compared in an ORDER BY clause, the order method function is invoked. An object specification can contain only one ORDER method, which must be a function having the return type NUMBER.
You can declare either a MAP method or an ORDER method, but not both. If you declare either method, you can compare object instances in SQL. If you do not declare either method, you can compare object instances only for equality or inequality. Instances of the same type definition are equal only if each pair of their corresponding attributes is equal. No comparison method needs to be specified to determine the equality of two object types. See Also: "Object Values" on page 2-35 for more information about object value comparisons.
Examples
Adding a Member Function
In the following example, member function QTR is added to the type definition of DATA_T.
CREATE TYPE data_t AS OBJECT ( year NUMBER, MEMBER FUNCTION prod(invent NUMBER) RETURN NUMBER ); CREATE TYPE BODY data_t IS MEMBER FUNCTION prod (invent NUMBER) RETURN NUMBER IS BEGIN RETURN (year + invent); END; END; ALTER TYPE data_t REPLACE AS OBJECT ( year NUMBER, MEMBER FUNCTION prod(invent NUMBER) RETURN NUMBER, MEMBER FUNCTION qtr(der_qtr DATE) RETURN CHAR );
7-190 SQL Reference
ALTER TYPE
CREATE OR REPLACE TYPE BODY data_t IS MEMBER FUNCTION prod (invent NUMBER) RETURN NUMBER IS MEMBER FUNCTION qtr(der_qtr DATE) RETURN CHAR IS BEGIN RETURN (year + invent); END; BEGIN RETURN 'FIRST'; END; END;
Recompiling a Type The following example creates and then recompiles type
LOAN_T:
CREATE TYPE loan_t AS OBJECT ( loan_num NUMBER, interest_rate FLOAT, amount FLOAT, start_date DATE, end_date DATE ); ALTER TYPE loan_t COMPILE;
Recompiling a Type Body The following example compiles the type body of
LINK2.
CREATE TYPE link1 AS OBJECT (a NUMBER); CREATE TYPE link2 AS OBJECT (a NUMBER, b link1, MEMBER FUNCTION p(c1 NUMBER) RETURN NUMBER); CREATE TYPE BODY link2 AS MEMBER FUNCTION p(c1 NUMBER) RETURN NUMBER IS t13 link1; BEGIN t13 := link1(13); dbms_output.put_line(t13.a); RETURN 5; END; END; CREATE TYPE link3 AS OBJECT (a link2); CREATE TYPE link4 AS OBJECT (a link3);
SQL Statements
7-191
ALTER TYPE
CREATE TYPE link5 AS OBJECT (a link4); ALTER TYPE link2 COMPILE BODY;
Recompiling a Type Specification The following example compiles the type
specification of LINK2.
CREATE TYPE link1 AS OBJECT (a NUMBER); CREATE TYPE link2 AS OBJECT (a NUMBER, b link1, MEMBER FUNCTION p(c1 NUMBER) RETURN NUMBER); CREATE TYPE BODY link2 AS MEMBER FUNCTION p(c1 NUMBER) RETURN NUMBER IS t14 link1; BEGIN t14 := link1(14); dbms_output.put_line(t14.a); RETURN 5; END; END; CREATE TYPE link3 AS OBJECT (a link2); CREATE TYPE link4 AS OBJECT (a link3); CREATE TYPE link5 AS OBJECT (a link4); ALTER TYPE link2 COMPILE SPECIFICATION;
7-192 SQL Reference
ALTER USER
ALTER USER
Syntax
BY IDENTIFIED password
EXTERNALLY GLOBALLY AS ' external_name '
DEFAULT TEMPORARY
TABLESPACE TABLESPACE
tablespace tablespace K M
integer QUOTA UNLIMITED user PROFILE profile , role , DEFAULT ROLE ALL ALTER USER PASSWORD EXPIRE LOCK ACCOUNT UNLOCK , user proxy_clause NONE ; EXCEPT role ON tablespace
SQL Statements
7-193
ALTER USER
proxy_clause::=
, role_name ROLE WITH GRANT CONNECT REVOKE THROUGH proxy NONE ALL EXCEPT , role_name
Purpose
To change the authentication or database resource characteristics of a database user. To permit a proxy server to connect as a client without authentication.
Note: ALTER USER syntax does not accept the old password. Therefore it neither authenticates using the old password nor checks the new password against the old before setting the new password. If these checks against the old password are important, use the OCIPasswordChange() call instead of ALTER USER. For more information, see Oracle Call Interface Programmer's Guide.
Prerequisites
You must have the ALTER USER system privilege. However, you can change your own password without this privilege.
Keywords and Parameters
The keywords and parameters shown below are unique to ALTER USER or have different functionality than they have in CREATE USER. All the remaining keywords and parameters in the ALTER USER statement have the same meaning as in the CREATE USER statement. For information on these keywords and parameters, see "CREATE USER" on page 7-451. To assign limits on database resources to a user, see "CREATE PROFILE" on page 7-359.
7-194 SQL Reference
ALTER USER
IDENTIFIED BY password
Note: Oracle expects a different timestamp for each resetting of a particular password. If you reset one password multiple times within one second (for example, by cycling through a set of passwords using a script), Oracle may return an error message that the password cannot be reused. For this reason, Oracle Corporation recommends that you avoid using scripts to reset passwords. indicates that a user must be authenticated by way of an LDAP V3 compliant directory service such as Oracle Internet Directory. (See also "CREATE USER" on page 7-451.) You can change a user's access verification method to IDENTIFIED GLOBALLY AS 'external_name' only if all external roles granted directly to the user are revoked. You can change a user created as IDENTIFIED GLOBALLY AS 'external_name' to IDENTIFIED BY password or IDENTIFIED EXTERNALLY.
IDENTIFIED GLOBALLY AS
DEFAULT ROLE
can contain only roles that have been granted directly to the user with a GRANT statement. You cannot use the DEFAULT ROLE clause to enable:
s s s
roles not granted to the user roles granted through other roles roles managed by an external service (such as the operating system), or by the Oracle Internet Directory
Oracle enables default roles at logon without requiring the user to specify their passwords. See Also: "CREATE ROLE" on page 4-365. proxy_clause controls the ability of a proxy (an application or application server) to connect as the specified user and to activate all, some, or none of the user's roles. See Also: Oracle8i Concepts for more information on proxies and their use of the database. GRANT REVOKE proxy WITH ROLE allows the connection. prohibits the connection. identifies the proxy connecting to Oracle. specifies the roles that the application is permitted to activate after it connects as the user. If you do not include this clause, Oracle activates all roles granted to the specified user automatically. permits the proxy to connect as the specified user and to activate only the roles that are specified by role_name. permits the proxy to connect as the specified user and to activate all roles associated with that user except those specified by role_name. permits the proxy to connect as the specified user, but prohibits the proxy from activating any of that user's roles after connecting.
role_name ALL EXCEPT role_name NONE
SQL Statements
7-195
ALTER USER
Examples
General Examples The following 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;
The following statement assigns the CLERK profile to SCOTT:
ALTER USER scott PROFILE clerk;
In subsequent sessions, SCOTT is restricted by limits in the CLERK profile. The following 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.
Authentication Examples The following statement changes user TOM's
authentication mechanism:
ALTER USER tom IDENTIFIED GLOBALLY AS 'CN=tom,O=oracle,C=US';
The following statement causes user FRED's password to expire:
ALTER USER fred PASSWORD EXPIRE;
If you cause a database user's password to expire with PASSWORD EXPIRE, the user (or the DBA) must change the password before attempting to log in to the database following the expiration. However, tools such as SQL*Plus allow you to change the password on the first attempted login following the expiration.
Proxy Examples The following statement permits the proxy user APPSERVER1 to
connect as the user JANE. It also allows APPSERVER1 to activate the role INVENTORY:
ALTER USER jane GRANT CONNECT THROUGH appserver1 WITH ROLE inventory;
7-196 SQL Reference
ALTER USER
The following statement takes away the right of proxy user APPSERVER1 to connect as the user JANE:
ALTER USER jane REVOKE CONNECT THROUGH appserver1;
SQL Statements
7-197
ALTER VIEW
ALTER VIEW
Syntax
schema. ALTER VIEW view COMPILE ;
Purpose
To explicitly recompile a view that is invalid. Explicit recompilation allows you to locate recompilation errors before run time. You may want to recompile a view explicitly 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.
Notes:
s
This statement does not change the definition of an existing view. To redefine a view, you must use CREATE VIEW with OR REPLACE. See "CREATE VIEW" on page 7-456. If you alter a view that is referenced by one or more materialized views, those materialized views are invalidated. Invalid materialized views cannot be used by query rewrite and cannot be refreshed. To revalidate an invalid materialized view, see "ALTER MATERIALIZED VIEW / SNAPSHOT" on page 7-47. For information on materialized views in general, see Oracle8i Data Warehousing Guide.
s
See Also: Oracle8i Concepts for more about dependencies among schema objects.
Prerequisites
The view must be in your own schema or you must have ALTER ANY TABLE system privilege.
7-198 SQL Reference
ALTER VIEW
Keywords and Parameters
schema view COMPILE is the schema containing the view. If you omit schema, Oracle assumes the view is in your own schema. is the name of the view to be recompiled. causes Oracle to recompile the view. The COMPILE keyword is required.
Example
To recompile the view CUSTOMER_VIEW, issue the following 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 run time.
SQL Statements
7-199
ANALYZE
ANALYZE
Syntax
PARTITION TABLE ANALYZE INDEX CLUSTER for_clause COMPUTE STATISTICS ROWS SAMPLE for_clause ESTIMATE DELETE STATISTICS STATISTICS SET VALIDATE REF UPDATE schema CASCADE VALIDATE STRUCTURE schema INT0 LIST CHAINED ROWS . table INT0 . table DANGLING TO NULL ; integer PERCENT table schema . index cluster SUBPARTITION ( ( partition ) )
subpartition
7-200 SQL Reference
ANALYZE
for_clause::=
TABLE INDEXED ALL FOR COLUMNS attribute LOCAL ALL INDEXES SIZE COLUMNS integer column SIZE integer SIZE integer
Purpose
This statement lets you
s
Collect or delete statistics about an index or index partition, table or table partition, index-organized table, cluster, or scalar object attribute. Validate the structure of an index or index partition, table or table partition, index-organized table, cluster, or object reference (REF). Identify migrated and chained rows of a table or cluster.
s
s
For most statistics collection purposes, Oracle Corporation recommends that you use the DBMS_STATS package. That package lets you collect statistics in parallel, collect global statistics for partitioned objects, and fine tune your statistics collection in other ways. See Oracle8i Supplied PL/SQL Packages Reference for more information on this package. However, you can use this statement for any of the purposes described in this section, and you must use this statement (rather than the DBMS_STATS package) for the following purposes:
s
To use the VALIDATE or LIST CHAINED ROWS clauses To sample a number (rather than a percentage) of rows To collect statistics not used by the optimizer (such as information on freelist blocks)
s
s
SQL Statements
7-201
ANALYZE
Prerequisites
The schema object to be analyzed must be local, and it must be in your own schema or you must have the ANALYZE ANY system privilege. 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 want to validate a partitioned table, you must have INSERT privilege on the table into which you list analyzed rowids, or you must have INSERT ANY TABLE system privilege.
Keywords and Parameters
schema INDEX index is the schema containing the index, table, or cluster. If you omit schema, Oracle assumes the index, table, or cluster is in your own schema. identifies an index to be analyzed (if no for_clause is used). Oracle collects the following statistics for an index (statistics marked with an asterisk are always computed exactly):
s s s s s s
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 the rows are about the indexed values)
Index statistics appear in the data dictionary views USER_INDEXES, ALL_INDEXES, and DBA_INDEXES. For a domain index, this statement invokes the user-defined statistics collection function specified in the statistics type associated with the index (see "ASSOCIATE STATISTICS" on page 7-210). If no statistics type is associated with the domain index, the statistics type associated with its indextype is used. If no statistics type exists for either the index or its indextype, no user-defined statistics are collected. User-defined index statistics appear in the data dictionary views USER_USTATS, ALL_USTATS, and DBA_USTATS. Restriction: You cannot analyze a domain index that is marked LOADING or FAILED. See Also: "CREATE INDEX" on page 7-291 for more information on domain indexes.
7-202 SQL Reference
ANALYZE
TABLE table
identifies a table to be analyzed. When you collect statistics for a table, Oracle also automatically collects the statistics for each of the table's indexes and domain indexes, provided that no for_clauses are used. When you analyze a table, Oracle collects statistics about expressions occurring in any function-based indexes as well. Therefore, be sure to create function-based indexes on the table before analyzing the table. See Also: "CREATE INDEX" on page 7-291 for more information about function-based indexes. When analyzing a table, Oracle skips all domain indexes marked LOADING or FAILED. Table statistics, including the status of domain indexes, appear in the data dictionary views USER_TABLES, ALL_TABLES, and DBA_TABLES. Oracle collects the following statistics for a table (statistics marked with an asterisk are always computed exactly):
s s
Number of rows * Number of data blocks below the high water mark (that is, the number of data blocks that have been formatted to receive data, regardless whether they currently contain data or are empty) * 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
s s s s
Restrictions:
s s
You cannot use ANALYZE to collect statistics on data dictionary tables. You cannot use ANALYZE to collect default statistics on a temporary table. However, if you have created an association between one or more columns of a temporary table and a user-defined statistics type, you can use ANALYZE to collect the user-defined statistics on the temporary table. (The association must already exist.) You cannot compute or estimate statistics for the following column types: REFs, varrays, nested tables, LOBs (LOBs are not analyzed, they are skipped), LONGs, or object types. However, if a statistics type is associated with such a column, user-defined statistics are collected.
s
See Also: "ASSOCIATE STATISTICS" on page 7-210. PARTITION | SUBPARTITION specifies that statistics will be gathered for partition or subpartition. You cannot use this clause when analyzing clusters. If you specify PARTITION and table is composite-partitioned, Oracle analyzes all the subpartitions within the specified partition.
SQL Statements
7-203
ANALYZE
CLUSTER cluster
identifies a cluster to be analyzed. 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.
s
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 cluster, Oracle collects the average number of data blocks taken up by a single hash key value and all of its rows.
s
These statistics appear in the data dictionary views USER_CLUSTERS and DBA_CLUSTERS. COMPUTE STATISTICS ESTIMATE STATISTICS computes exact statistics about the analyzed object and stores them in the data dictionary. When you analyze a table, both table and column statistics are collected. estimates statistics about the analyzed object and stores them in the data dictionary.
Both computed and estimated 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 Oracle8i Designing and Tuning for Performance. SAMPLE integer specifies the amount of data from the analyzed object Oracle samples to estimate statistics. If you omit this parameter, Oracle samples 1064 rows. The default sample value is adequate for tables up to a few thousand rows. If your tables are larger, specify a higher value for SAMPLE. If you specify more than half of the data, Oracle reads all the data and computes the statistics. ROWS PERCENT causes Oracle to sample integer rows of the table or cluster or integer entries from the index. The integer must be at least 1. 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.
for_clause
specifies whether an entire table or index, or just particular columns, will be analyzed. The following clauses apply only to the ANALYZE TABLE version of this statement: FOR TABLE FOR COLUMNS restricts the statistics collected to only table statistics rather than table and column statistics. restricts the statistics collected to only column statistics for the specified columns and scalar object attributes, rather than for all columns and attributes; attribute specifies the qualified column name of an item in an object. collects column statistics for all columns and scalar object attributes.
FOR ALL COLUMNS
7-204 SQL Reference
ANALYZE
FOR ALL INDEXED COLUMNS
collects column statistics for all indexed columns in the table.
Column statistics can be based on the entire column or can use a histogram by specifying SIZE (see below). Oracle collects the following column statistics:
s s
Number of distinct values in the column as a whole Maximum and minimum values in each band
See Also: Oracle8i Designing and Tuning for Performance and "Histogram Examples" on page 7-208 for more information on histograms. Column statistics appear in the data dictionary views USER_TAB_COLUMNS, ALL_TAB_ COLUMNS, and DBA_TAB_COLUMNS. Histograms appear in the data dictionary views USER_ TAB_HISTOGRAMS, DBA_TAB_HISTOGRAMS, and ALL_TAB_HISTOGRAMS; USER_PART_ HISTOGRAMS, DBA_PART_HISTOGRAMS, and ALL_PART_HISTOGRAMS; and USER_ SUBPART_HISTOGRAMS, DBA_SUBPART_HISTOGRAMS, and ALL_SUBPART_HISTOGRAMS. Note: The MAXVALUE and MINVALUE columns of USER_, DBA_, and ALL_TAB_COLUMNS have a length of 32 bytes. If you analyze columns with a length >32 bytes, and if the columns are padded with leading blanks, Oracle may take into account only the leading blanks and return unexpected statistics. If a user-defined statistics type has been associated with any columns, the for_clause collects user-defined statistics using that statistics type. If no statistics type is associated with a column, Oracle checks to see if any statistics type has been associated with the type of the column, and uses that statistics type. If no statistics type has been associated with either the column or its user-defined type, no user-defined statistics are collected. User-defined column statistics appear in the data dictionary views USER_USTATS, ALL_USTATS, and DBA_USTATS. If you want to collect statistics on both the table as a whole and on one or more columns, be sure to generate the statistics for the table first, and then for the columns. Otherwise, the table-only ANALYZE will overwrite the histograms generated by the column ANALYZE. For example, issue the following statements: ANALYZE TABLE emp ESTIMATE STATISTICS; ANALYZE TABLE emp ESTIMATE STATISTICS FOR ALL COLUMNS; FOR ALL INDEXES FOR ALL LOCAL INDEXES SIZE specifies that all indexes associated with the table will be analyzed. specifies that all local index partitions are analyzed. You must specify the keyword LOCAL if the PARTITION clause and INDEX are specified. specifies the maximum number of partitions in the histogram. The default value is 75, minimum value is 1, and maximum value is 254.
SQL Statements
7-205
ANALYZE
DELETE STATISTICS
deletes any statistics about the analyzed object that are currently stored in the data dictionary. Use this statement when you no longer want Oracle to use the statistics. When you use this clause on a table, Oracle also automatically removes statistics for all the table's indexes. When you use this clause on a cluster, Oracle also automatically removes statistics for all the cluster's tables and all their indexes, including the cluster index. If user-defined column or index statistics were collected for an object, Oracle also removes the user-defined statistics by invoking the statistics deletion function specified in the statistics type that was used to collect the statistics.
VALIDATE REF UPDATE
validates the REFs in the specified table, checks the rowid portion in each REF, compares it with the true rowid, and corrects, if necessary. You can use this clause only when analyzing a table. SET DANGLING TO NULL sets to NULL any REFs (whether or not scoped) in the specified table that are found to point to an invalid or nonexistent object. Note: If the owner of the table does not have SELECT object privilege on the referenced objects, Oracle will consider them invalid and set them to NULL. Subsequently these REFs will not be available in a query, even if it is issued by user with appropriate privileges on the objects.
VALIDATE STRUCTURE
validates the structure of the analyzed object. The statistics collected by this clause are not used by the Oracle optimizer, as are statistics collected by the COMPUTE STATISTICS and ESTIMATE STATISTICS clauses.
s s s
For a table, Oracle verifies the integrity of each of the table's data blocks and rows. For a cluster, Oracle automatically validates the structure of the cluster's tables. For a partitioned table, Oracle also verifies that the row belongs to the correct partition. If the row does not collate correctly, the rowid is inserted into the INVALID_ROWS table. For a temporary table, Oracle validates the structure of the table and its indexes during the current session. For an index, Oracle verifies the integrity of each data block in the index and checks for block corruption. This clause 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 with the CASCADE clause. Oracle stores statistics about the index in the data dictionary views INDEX_STATS and INDEX_HISTOGRAM, which are described in Oracle8i Reference.
s
s
Validating the structure of an object prevents SELECT, INSERT, UPDATE, and DELETE statements from concurrently accessing the object. Therefore, do not use this clause on the tables, clusters, and indexes of your production applications during periods of high database activity. If Oracle encounters corruption in the structure of the object, an error message is returned to you. In this case, drop and re-create the object.
7-206 SQL Reference
ANALYZE
INTO
specifies a table into which Oracle lists the rowids of the partitions whose rows do not collate correctly. If you omit schema, Oracle assumes the list is in your own schema. If you omit this clause altogether, Oracle assumes that the table is named INVALID_ROWS. The SQL script used to create this table is UTLVALID.SQL. validates the structure of the indexes associated with the table or cluster. If you use this clause when validating a table, Oracle also validates the table's indexes. If you use this clause when validating a cluster, Oracle also validates all the clustered tables' indexes, including the cluster index. If you use this clause to validate an enabled (but previously disabled) function-based index, validation errors may result. In this case, you must rebuild the index.
CASCADE
LIST CHAINED ROWS
identifies migrated and chained rows of the analyzed table or cluster. You cannot use this clause 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. You can create the CHAINED_ROWS table using one of these scripts:
s
UTLCHAIN.SQL uses physical rowids. Therefore it can accommodate rows from conventional tables but not from indexorganized tables. (See the Note that follows.) UTLCHN1.SQL uses universal rowids, so it can accommodate rows from both conventional and index-organized tables.
s
If you create your own chained-rows table, it must follow the format prescribed by one of these two scripts. See Oracle8i Migration for compatibility issues related to the use of these scripts. Note: If you are analyzing index-organized tables based on primary keys (rather than universal rowids), you must create a separate chained-rows table for each index-organized table to accommodate its primary-key storage. Use the SQL scripts DBMSIOTC.SQL and PRVTIOTC.PLB to define the BUILD_CHAIN_ROWS_TABLE procedure, and then execute this procedure to create an IOT_CHAINED_ROWS table for each such index-organized table. For information on the SQL scripts, see the DBMS_IOT package in Oracle8i Supplied PL/SQL Packages Reference. For information on eliminating migrated and chained rows, see Oracle8i Designing and Tuning for Performance.
Examples
The following statement estimates statistics for the CUST_ HISTORY table and all of its indexes:
Analyzing a Cluster
SQL Statements
7-207
ANALYZE
ANALYZE TABLE cust_history ESTIMATE STATISTICS;
Deleting Statistics The following statement deletes statistics about the CUST_
HISTORY table and all its indexes from the data dictionary:
ANALYZE TABLE cust_history DELETE STATISTICS;
Histogram Examples The following statement creates a 10-band histogram on the
SAL column of the EMP table:
ANALYZE TABLE emp COMPUTE STATISTICS FOR COLUMNS sal SIZE 10;
You can also collect histograms for a single partition of a table. The following statement analyzes the EMP table partition P1:
ANALYZE TABLE emp PARTITION (p1) COMPUTE STATISTICS;
Index Example
The following statement validates the structure the of index
PARTS_INDEX:
ANALYZE INDEX parts_index VALIDATE STRUCTURE;
Table Examples The following statement analyzes the EMP table and all of its
indexes:
ANALYZE TABLE emp VALIDATE STRUCTURE CASCADE;
For a table, the VALIDATE REF UPDATE clause verifies the REFs in the specified table, checks the rowid portion of each REF, and then compares it with the true rowid. If the result is an incorrect rowid, the REF is updated so that the rowid portion is correct. The following statement validates the REFs in the EMP table:
ANALYZE TABLE emp VALIDATE REF UPDATE;
Cluster Example The following 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;
7-208 SQL Reference
ANALYZE
Chained Rows Example The following statement collects information about all the chained rows of the table ORDER_HIST:
ANALYZE TABLE order_hist LIST CHAINED ROWS INTO cr;
The preceding statement places the information into the table CR. You can then examine the rows with this query:
SELECT * FROM cr; OWNER_NAME ---------SCOTT TABLE_NAME ---------ORDER_HIST CLUSTER_NAME -----------HEAD_ROWID TIMESTAMP ------------------ --------AAAAZzAABAAABrXAAA 15-MAR-96
COMPUTE Example The following statement calculates statistics for a scalar object
attribute:
ANALYZE TABLE emp COMPUTE STATISTICS FOR COLUMNS addr.street;
SQL Statements
7-209
ASSOCIATE STATISTICS
ASSOCIATE STATISTICS
Syntax
column_association ASSOCIATE STATISTICS WITH function_association ;
column_association::=
, schema COLUMNS . table . column using_clause
function_association::=
, schema FUNCTIONS , schema PACKAGES , using_clause schema TYPES , , schema INDEXES , schema INDEXTYPES . indextype . index default_selectivity_clause default_cost_clause . type default_cost_clause , default_selectivity_clause . package . function
7-210 SQL Reference
ASSOCIATE STATISTICS
using_clause::=
schema USING . statistics_type
default_cost_clause::=
DEFAULT COST ( cpu_cost , io_cost , network_cost )
default_selectivity_clause::=
DEFAULT SELECTIVITY default_selectivity
Purpose
To associate a statistics type (or default statistics) containing functions relevant to statistics collection, selectivity, or cost with one or more columns, standalone functions, packages, types, domain indexes, or indextypes. For a listing of all current statistics type associations, refer to the USER_ ASSOCIATIONS table. If you analyze the object with which you are associating statistics, you can also view the associations in the USER_USTATS table. For information on the order of precedence with which ANALYZE uses associations, see "ANALYZE" on page 7-200.
Prerequisites
To issue this statement, you must have the appropriate privileges to alter the base object (table, function, package, type, domain index, or indextype). In addition, unless you are associating only default statistics, you must have execute privilege on the statistics type. The statistics type must already have been defined. For information on defining types, see "CREATE TYPE" on page 7-437.
Keywords and Parameters
column_ association specifies a list of one or more table columns. If you do not specify schema, Oracle assumes the table is in your own schema.
SQL Statements
7-211
ASSOCIATE STATISTICS
function_ association
specifies a list of one or more standalone functions, packages, user-defined datatypes, domain indexes, or indextypes. If you do not specify schema, Oracle assumes the object is in your own schema.
s
FUNCTIONS refers only to standalone functions, not to method types or to built-in functions. TYPES refers only to user-defined types, not to internal SQL datatypes.
s
Restriction: You cannot specify an object for which you have already defined an association. You must first disassociate the statistics from this object. See "DISASSOCIATE STATISTICS" on page 7-470. using_clause default_cost_ clause specifies the statistics type being associated with columns, functions, packages, types, domain indexes, or indextypes. The statistics_type must already have been created. specifies default costs for standalone functions, packages, types, domain indexes, or indextypes. If you specify this clause, you must include one number each for CPU cost, I/O cost, and network cost, in that order. Each cost is for a single execution of the function or method or for a single domain index access. Accepted values are integers of zero or greater.
default_ specifies as a percent the default selectivity for predicates with standalone functions, types, selectivity_clause packages, or user-defined operators. The default_selectivity must be a whole number between 0 and 100. Values outside this range are ignored. Restriction: You cannot specify DEFAULT SELECTIVITY for domain indexes or indextypes.
Examples
Standalone Function Example
This statement creates an association for a standalone function FN and causes the optimizer to call the appropriate cost function (if present) in the statistics type STAT_FN.
ASSOCIATE STATISTICS WITH FUNCTIONS fn USING stat_fn;
Default Cost Example This statement specifies that using the domain index T_A to implement a given predicate always has a CPU cost of 100, I/O of 5, and network cost of 0.
ASSOCIATE STATISTICS WITH INDEXES t_a DEFAULT COST (100,5,0);
The optimizer will simply use these default costs instead of calling a cost function.
7-212 SQL Reference
AUDIT sql_statements
AUDIT sql_statements
Syntax
, user , proxy , statement_opt AUDIT , system_priv SESSION BY ACCESS WHENEVER BY , user ON BEHALF OF ANY
NOT SUCCESSFUL ;
Purpose
To track the occurrence of specific SQL statements in subsequent user sessions. Auditing options specified by the AUDIT sql_statements statement apply only to subsequent sessions, not to current sessions. To choose particular schema objects for auditing, see "AUDIT schema_objects" on page 7-221. For information on disabling auditing of SQL statements, see "NOAUDIT sql_statements" on page 7-550.
Prerequisites
You must have AUDIT SYSTEM system privilege. You must enable auditing by setting the initialization parameter AUDIT_TRAIL to DB. You can specify auditing options regardless of whether auditing is enabled. However, Oracle does not generate audit records until you enable auditing.
SQL Statements
7-213
AUDIT sql_statements
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 71 and Table 72. For each audited operation, Oracle produces an audit record containing this information:
s s s s
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, which is a database table containing audit records. You can review database activity by examining the audit trail through data dictionary views. For information on these views, see the Oracle8i Reference. 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 75. Rather than specifying many individual system privileges, you can specify the roles CONNECT, RESOURCE, and DBA. Doing so is equivalent to auditing all of the system privileges granted to those roles. See "GRANT system_privileges_and_roles" on page 7-519 for more information on these roles. Oracle also provides two shortcuts for specifying groups of system privileges and statement options at once:
s
ALL is equivalent to specifying all statements options shown in Table 71 but not the additional statement options shown in Table 72. ALL PRIVILEGES is equivalent to specifying all system privileges.
s
Note: Oracle Corporation recommends that you specify individual system privileges and statement options for auditing rather than roles or shortcuts. The specific system privileges and statement options encompassed by roles and shortcuts change from one release to the next and may not be supported in future versions of Oracle. BY user BY proxy chooses only SQL statements issued by specified users for auditing. If you omit this clause, Oracle audits all users' statements. chooses for auditing only SQL statements issued by the specified proxy. See Also: Oracle8i Concepts for more information on proxies and their use of the database. ON BEHALF OF specifies the user or users on whose behalf the proxy executes the specified statement.
s s
user specifies auditing of statements executed on behalf of a particular user. ANY specifies auditing of statements executed on behalf of any user.
BY SESSION
causes Oracle to write a single record for all SQL statements of the same type issued in the same session.
7-214 SQL Reference
AUDIT sql_statements
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 (DDL) statements, Oracle automatically audits by access regardless of whether you specify the BY SESSION clause or BY ACCESS clause. For statement options and system privileges that audit SQL statements other than DDL, you can specify either BY SESSION or BY ACCESS. BY SESSION is the default.
WHENEVER SUCCESSFUL
chooses auditing only for statements that succeed. NOT chooses auditing only for statements that fail or result in errors. If you omit the WHENEVER SUCCESSFUL clause, Oracle audits SQL statements regardless of success or failure.
Table 71
Statement Auditing Options for Database Objects
SQL Statements and Operations CREATE CLUSTER AUDIT CLUSTER DROP CLUSTER TRUNCATE CLUSTER
Statement Option CLUSTER
CONTEXT
CREATE CONTEXT DROP CONTEXT
DATABASE LINK
CREATE DATABASE LINK DROP DATABASE LINK
DIMENSION
CREATE DIMENSION ALTER DIMENSION DROP DIMENSION
DIRECTORY
CREATE DIRECTORY DROP DIRECTORY
INDEX
CREATE INDEX ALTER INDEX DROP INDEX
NOT EXISTS
All SQL statements that fail because a specified object does not exist.
SQL Statements
7-215
AUDIT sql_statements
Table 71 (Cont.) Statement Auditing Options for Database Objects
Statement Option PROCEDUREa SQL Statements and Operations CREATE FUNCTION CREATE LIBRARY CREATE PACKAGE CREATE PACKAGE BODY CREATE PROCEDURE DROP FUNCTION DROP LIBRARY DROP PACKAGE DROP PROCEDURE PROFILE CREATE PROFILE ALTER PROFILE DROP PROFILE PUBLIC DATABASE LINK PUBLIC SYNONYM CREATE PUBLIC DATABASE LINK DROP PUBLIC DATABASE LINK 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 SYNONYM Logons CREATE SYNONYM DROP SYNONYM
7-216 SQL Reference
AUDIT sql_statements
Table 71 (Cont.) Statement Auditing Options for Database Objects
Statement Option SYSTEM AUDIT SQL Statements and Operations AUDIT sql_statements NOAUDIT sql_statements SYSTEM GRANT GRANT system_privileges_and_roles REVOKE system_privileges_and_roles TABLE CREATE TABLE DROP TABLE TRUNCATE TABLE COMMENT ON TABLE DELETE [FROM] table TABLESPACE CREATE TABLESPACE ALTER TABLESPACE DROP TABLESPACE TRIGGER CREATE TRIGGER ALTER TRIGGER with ENABLE and DISABLE clauses DROP TRIGGER ALTER TABLE with ENABLE ALL TRIGGERS clause and DISABLE ALL TRIGGERS clause TYPE CREATE TYPE CREATE TYPE BODY ALTER TYPE DROP TYPE DROP TYPE BODY USER CREATE USER ALTER USER DROP USER VIEW CREATE VIEW DROP VIEW
SQL Statements
7-217
AUDIT sql_statements
Table 71 (Cont.) Statement Auditing Options for Database Objects
Statement Option
a
SQL Statements and Operations
Java schema objects (sources, classes, and resources) are considered the same as procedures for purposes of auditing SQL statements.
Table 72
Additional Statement Auditing Options for SQL Statements
SQL Statements and Operations ALTER SEQUENCE ALTER TABLE COMMENT ON TABLE table, view, materialized view COMMENT ON COLUMN table.column, view.column, materialized view.column
Statement Option ALTER SEQUENCE ALTER TABLE COMMENT TABLE
DELETE TABLE EXECUTE PROCEDURE
DELETE FROM table, view CALL Execution of any procedure or function or access to any variable, library, or cursor inside a package.
GRANT DIRECTORY
GRANT privilege ON directory REVOKE privilege ON directory
GRANT PROCEDURE
GRANT privilege ON procedure, function, package REVOKE privilege ON procedure, function, package
GRANT SEQUENCE
GRANT privilege ON sequence REVOKE privilege ON sequence
GRANT TABLE
GRANT privilege ON table, view, materialized view. REVOKE privilege ON table, view, materialized view
GRANT TYPE
GRANT privilege ON TYPE REVOKE privilege ON TYPE
INSERT TABLE LOCK TABLE
INSERT INTO table, view LOCK TABLE table, view
7-218 SQL Reference
AUDIT sql_statements
Table 72 (Cont.) Additional Statement Auditing Options for SQL Statements
Statement Option SELECT SEQUENCE SELECT TABLE UPDATE TABLE SQL Statements and Operations Any statement containing sequence.CURRVAL or sequence.NEXTVAL SELECT FROM table, view, materialized view UPDATE table, view
Examples
Role Examples To choose auditing for every SQL statement that creates, alters,
drops, or sets a role, regardless of whether the statement completes successfully, issue the following statement:
AUDIT ROLE;
To choose auditing for every statement that successfully creates, alters, drops, or sets a role, issue the following 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 the following statement:
AUDIT ROLE WHENEVER NOT SUCCESSFUL;
Query/Update Examples To choose auditing for any statement that queries or
updates any table, issue the following 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 the following statement:
AUDIT SELECT TABLE, UPDATE TABLE BY scott, blake;
Delete Example To choose auditing for statements issued using the DELETE ANY
TABLE system privilege, issue the following statement:
AUDIT DELETE ANY TABLE;
SQL Statements
7-219
AUDIT sql_statements
Directory Examples
To choose auditing for statements issued using the CREATE ANY DIRECTORY system privilege, issue the following statement:
AUDIT CREATE ANY DIRECTORY;
To choose auditing for CREATE DIRECTORY (and DROP DIRECTORY) statements that do not use the CREATE ANY DIRECTORY system privilege, issue the following statement:
AUDIT DIRECTORY;
7-220 SQL Reference
AUDIT schema_objects
AUDIT schema_objects
Syntax
, object_opt AUDIT ALL DEFAULT SESSION BY ACCESS WHENEVER ON DIRECTORY directory_name schema . object
NOT SUCCESSFUL ;
Purpose
To track operations on a specific schema object. To choose particular SQL statements for auditing, see "AUDIT sql_statements" on page 7-213. Auditing keeps track of operations performed by database users. Auditing options established by the AUDIT schema_objects statement apply to current sessions as well as to subsequent sessions. For information on discontinuing auditing operations, see "NOAUDIT schema_objects" on page 7-552.
Prerequisites
The object you choose for auditing must be in your own schema or you must have AUDIT ANY system privilege. In addition, if the object you choose for auditing is a directory object, even if you created it, you must have AUDIT ANY system privilege.
Keywords and Parameters
object_opt specifies a particular operation for auditing. Table 73 shows each object option and the types of objects to which it applies. The name of each object option specifies a SQL statement 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.
SQL Statements
7-221
AUDIT schema_objects
ALL schema object
is a shortcut equivalent to specifying all object options applicable for the type of object. You can use this shortcut rather than explicitly specifying all options for an object. is the schema containing the object chosen for auditing. If you omit schema, Oracle assumes the object is in your own schema. identifies the object chosen for auditing. The object must be a table, view, sequence, stored procedure, function, package, materialized view, or library. You can also specify a synonym for a table, view, sequence, procedure, stored function, package, or materialized view.
ON DEFAULT
establishes the specified object options as default object options for subsequently created objects. Once you have established these default auditing options, any subsequently created object is automatically audited with those options. The default auditing options for a view are always the union of the auditing options for the view's base tables. You can see the current default auditing options by querying the ALL_DEF_AUDIT_OPTS data dictionary view. If you change the default auditing options, the auditing options for previously created objects remain the same. You can change the auditing options for an existing object only by specifying the object in the ON clause of the AUDIT statement.
ON DIRECTORY directory_name BY SESSION BY ACCESS WHENEVER SUCCESSFUL
identifies the name of the directory chosen for auditing. causes Oracle to write a single record for all operations of the same type on the same object issued in the same session. This is the default. causes Oracle to write one record for each audited operation. 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 SUCCESSFUL clause entirely, Oracle audits all SQL statements, regardless of success or failure.
7-222 SQL Reference
AUDIT schema_objects
Table 73 Object Auditing Options
Procedure MaterialFunction ized View / Snapshot Directory Sequence Packagea X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X
Object Option ALTER AUDIT COMMENT DELETE EXECUTE GRANT INDEX INSERT LOCK READ RENAME SELECT UPDATE
a
Object Library Type X X X Context
Table X X X X
View
Java schema objects (sources, classes, and resources) are considered the same as procedures, functions, and packages for purposes of auditing options.
Examples
To choose auditing for every SQL statement that queries the EMP table in the schema SCOTT, issue the following statement:
Query Examples
AUDIT SELECT ON scott.emp;
To choose auditing for every statement that successfully queries the EMP table in the schema SCOTT, issue the following statement:
AUDIT SELECT ON scott.emp WHENEVER SUCCESSFUL;
SQL Statements
7-223
AUDIT schema_objects
To choose auditing for every statement that queries the EMP table in the schema SCOTT and results in an Oracle error, issue the following statement:
AUDIT SELECT ON scott.emp WHENEVER NOT SUCCESSFUL;
Insert/Update Example To choose auditing for every statement that inserts or
updates a row in the DEPT table in the schema BLAKE, issue the following statement:
AUDIT INSERT, UPDATE ON blake.dept;
ALL Example To choose auditing for every statement that performs any operation
on the ORDER sequence in the schema ADAMS, issue the following statement:
AUDIT ALL ON adams.order;
The above statement uses the ALL shortcut to choose auditing for the following statements that operate on the sequence:
s
ALTER SEQUENCE AUDIT GRANT any statement that accesses the sequence's values using the pseudocolumns CURRVAL or NEXTVAL
s
s
s
To choose auditing for every statement that reads files from the BFILE_DIR1 directory, issue the following statement:
READ Example
AUDIT READ ON DIRECTORY bfile_dir1;
DEFAULT Example The following 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:
7-224 SQL Reference
AUDIT schema_objects
s
If you create a table, Oracle automatically audits any ALTER, GRANT, INSERT, UPDATE, or DELETE statements issued against the table. If you create a view, Oracle automatically audits any GRANT, INSERT, UPDATE, or DELETE statements issued against the view. If you create a sequence, Oracle automatically audits any ALTER or GRANT statements issued against the sequence. If you create a procedure, package, or function, Oracle automatically audits any ALTER or GRANT statements issued against it.
s
s
s
SQL Statements
7-225
CALL
7SQL Statements
CALL
Syntax
type schema CALL . package . . function procedure method INDICATOR , ( expr ) : INTO : host_variable ; indicator_variable @ dblink_name
Purpose
Enables you to execute a routine (a standalone procedure or function, or a procedure or function defined within a type or package) from within SQL. For information on creating such routine, refer to PL/SQL User's Guide and Reference.
Prerequisites
You must have EXECUTE privilege on the standalone routine or on the type or package in which the routine is defined.
Keywords and Parameters
schema specifies the schema in which the standalone routine (or the package or type containing the routine) resides. If you do not specify schema, Oracle assumes the routine is in your own schema. specifies the type or package in which the routine is defined. specifies the name of the function or procedure being called, or a synonym that translates to a function or procedure. When you call a type's member function or procedure, if the first argument (SELF) is a null IN OUT argument, Oracle returns an error. If SELF is a null IN argument, Oracle returns null. In both cases, the function or procedure is not invoked. Restriction: If the routine is a function, the INTO clause is mandatory.
type or package function | procedure | method
7-226 SQL Reference
CALL
@dblink
in a distributed database system, specifies the name of the database containing the standalone routine (or the package or functioning containing the routine). If you omit dblink, Oracle looks in your local database. specifies one or more arguments to the routine. Restrictions:
s
expr
An expr cannot be a pseudocolumn or either of the object reference functions VALUE or REF. Any expr that is an IN OUT or OUT argument of the routine must correspond to a host variable expression.
s
INTO :host_ variable :indicator_variable
applies only to calls to functions. This parameter specifies which host variable will store the return value of the function. indicates the value or condition of the host variable. See Also: Pro*C/C++ Precompiler Programmer's Guide for more information on host variables and indicator variables.
Example
The following statement creates a procedure UPDATESALARY, and then calls the procedure, which updates the specified employee ID with a new salary.
CREATE OR REPLACE PROCEDURE updateSalary (id NUMBER, newsalary NUMBER) IS BEGIN UPDATE emp SET sal=newsalary WHERE empno=id; END; CALL updateSalary(1404, 50000);
SQL Statements
7-227
COMMENT
COMMENT
Syntax
schema TABLE . table view snapshot COMMENT ON schema COLUMN . table . view snapshot . column IS ' text ' ;
Purpose
To add a comment about a table, view, snapshot, or column into the data dictionary. See also "Comments" on page 2-62. You can view the comments on a particular table or column by querying the data dictionary views USER_TAB_COMMENTS, DBA_TAB_COMMENTS, or ALL_TAB_ COMMENTS or USER_COL_COMMENTS, DBA_COL_COMMENTS, or ALL_COL_ COMMENTS. For information on these views, see Oracle8i Reference. To drop a comment from the database, set it to the empty string ' '.
Prerequisites
The table, view, or snapshot must be in your own schema or you must have COMMENT ANY TABLE system privilege.
Keywords and Parameters
TABLE COLUMN IS 'text' specifies the schema and name of the table, view, or materialized view to be commented. If you omit schema, Oracle assumes the table, view, or snapshot is in your own schema. 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 the text of the comment. See the syntax description of 'text' in "Text" on page 2-2.
7-228 SQL Reference
COMMENT
Example
To insert an explanatory remark on the NOTES column of the SHIPPING table, you might issue the following statement:
COMMENT ON COLUMN shipping.notes IS 'Special packing or shipping instructions';
To drop this comment from the database, issue the following statement:
COMMENT ON COLUMN shipping.notes IS ' ';
SQL Statements
7-229
COMMIT
COMMIT
Syntax
COMMENT ' text ' , WORK COMMIT FORCE ' text ' ; integer
Purpose
To end your current transaction and make permanent all changes performed in the transaction. A transaction is a sequence of SQL statements that Oracle treats as a single unit. This statement also erases all savepoints in the transaction and releases the transaction's locks.
Note: Oracle issues an implicit COMMIT before and after any data definition language (DDL) statement.
You can also use this statement to
s
Commit an in-doubt distributed transaction manually Terminate a read-only transaction begun by a SET TRANSACTION statement.
s
Oracle Corporation recommends that you explicitly end every transaction in 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 roll back the current transaction.
7-230 SQL Reference
COMMIT
See Also:
s
Oracle8i Concepts for more information on transactions. "SET TRANSACTION" on page 7-602 for more information on specifying characteristics of a transaction.
s
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.
Keywords and Parameters
WORK COMMENT is supported for compliance with standard SQL. The statements COMMIT and COMMIT WORK are equivalent. 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. See Also: "COMMENT" on page 7-228 for more information on adding comments to SQL statements. FORCE in a distributed database system, 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 use integer to specifically assign the transaction a system change number (SCN). If you omit integer, the transaction is committed using the current SCN. Note: A COMMIT statement with a FORCE clause commits only the specified transaction. Such a statement does not affect your current transaction. Restriction: COMMIT statements using the FORCE clause are not supported in PL/SQL. See Also: Oracle8i Distributed Database Systems for more information on these topics.
Examples
INSERT Example This statement inserts a row into the DEPT table and commits
this change:
INSERT INTO dept VALUES (50, 'MARKETING', 'TAMPA');
SQL Statements
7-231
COMMIT
COMMIT WORK;
COMMENT Example The following statement commits the current transaction and
associates a comment with it:
COMMIT 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.
In-Doubt Transaction Example
The following statement manually commits an in-
doubt distributed transaction:
COMMIT FORCE '22.57.53';
7-232 SQL Reference
constraint_clause
constraint_clause
Syntax
table_constraint::=
CONSTRAINT constraint , UNIQUE ( PRIMARY KEY constraint_state ) column )
foreign_key_clause CHECK ( condition
column_constraint::=
CONSTRAINT NOT NULL UNIQUE PRIMARY KEY CASCADE ON schema REFERENCES CHECK ( condition ) . table ( column ) DELETE SET NULL constraint
constraint_state
SQL Statements
7-233
constraint_clause
table_ref_constraint::=
schema ) ref_attribute ref_column REF ( ref_attribute CONSTRAINT constraint_name FOREIGN KEY ( ref_attribute ref_column ) references_clause ) WITH ROWID IS . scope_table_name
ref_column SCOPE FOR (
column_ref_constraint::=
schema SCOPE WITH IS ROWID constraint_name references_clause . scope_table_name
CONSTRAINT
references_clause::=
schema REFERENCES CASCADE ON DELETE SET NULL constraint_state . object_table
7-234 SQL Reference
constraint_clause
constraint_state::=
IMMEDIATE INITIALLY DEFERRABLE IMMEDIATE INITIALLY DEFERRED DEFERRED
NOT
NOT DEFERRABLE
RELY NORELY ENABLE DISABLE using_index_clause VALIDATE NOVALIDATE EXCEPTIONS INTO
schema
. table
using_index_clause::=
LOCAL global_index_clause PCTFREE INITRANS MAXTRANS TABLESPACE storage_clause NOSORT LOGGING NOLOGGING USING INDEX integer integer integer tablespace
SQL Statements
7-235
constraint_clause
global_index_clause::=
, GLOBAL PARTITION BY RANGE ( column_list ) ( global_partition_clause )
global_partition_clause::=
partition PARTITION physical_attributes_clause TABLESPACE LOGGING NOLOGGING VALUES LESS THAN ( value_list ) tablespace
foreign_key_clause::=
, FOREIGN KEY ( , ON ( table column ) DELETE SET NULL column ) REFERENCES CASCADE
schema
.
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
7-236 SQL Reference
constraint_clause
storage_clause: See the "storage_clause" on page 7-605.
Purpose
To define an integrity constraint. An integrity constraint is a rule that restricts the values for one or more columns in a table or an index-organized table.
Note: Oracle does not support constraints on columns or
attributes whose type is an object, nested table, varray, REF, or LOB. The only exception is that NOT NULL constraints are supported for columns or attributes whose type is object, VARRAY, REF, or LOB.
Prerequisites
Constraint clauses can appear in either CREATE TABLE or ALTER TABLE statements. To define an integrity constraint, you must have the privileges necessary to issue one of these statements. See "CREATE TABLE" on page 4-381 and "ALTER TABLE" on page 7-123. To create a referential integrity constraint, the parent table must be in your own schema, or you must have the REFERENCES privilege on the columns of the referenced key in the parent table.
Keywords and Parameters
table_constraint 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_ constraint The column_constraint syntax is part of a column definition. Usually, an integrity constraint defined with this syntax can impose rules only on the column in which it is defined.
s
The column_constraint syntax that appears in a CREATE TABLE or ALTER TABLE ADD statement can define any type of integrity constraint. Column_constraint syntax that appears in an ALTER TABLE MODIFY column_options statement can only define or remove a NOT NULL constraint.
s
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 the form SYS_Cn. If you do not specify NULL or NOT NULL in a column definition, NULL is the default.
SQL Statements
7-237
constraint_clause
Restriction: You cannot create a constraint on columns or attributes whose type is userdefined object, LOB, or REF, with the following exceptions:
s
You can specify a NOT NULL constraint on columns or attributes of user-defined object type, varray, and LOB. You can specify NOT NULL and referential integrity constraints on a column of type REF.
s
UNIQUE
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 composite unique key is made up of a combination of columns. To define a composite unique key, you must use table_constraint syntax rather than column_constraint syntax. 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. Restrictions:
s
For a composite unique key, no two rows in the table can have the same combination of values in the key columns. A composite unique key cannot have more than 32 columns. The overall size of the key (in bytes) should not exceed approximately the width of all indexed columns plus the number of indexed columns. 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.
s
s s
7-238 SQL Reference
constraint_clause
PRIMARY KEY
designates a column or combination of columns as the table's primary key. A composite primary key is made up of a combination of columns. To define a composite primary key, you must use the table_constraint syntax rather than the column_constraint syntax. Restrictions:
s s
A table can have only one primary key. None of the columns in the primary key can have datatype LONG, LONG RAW, VARRAY, NESTED TABLE, OBJECT, LOB, BFILE, or REF. 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. The size of the PRIMARY KEY of an index-organized table cannot exceed one-half of the database block size or 3800 bytes, whichever is less. (PRIMARY KEY is required for an index-organized table.) A composite primary key cannot have more than 32 columns. The overall size of the key (in bytes) should not exceed approximately the width of all indexed columns plus the number of indexed columns. You cannot designate the same column or combination of columns as both a primary key and a unique key.
s s s
s
s
NULL | NOT NULL
determines whether a column can contain nulls. You must specify NULL and NOT NULL with column_constraint syntax, not with table_constraint syntax. NULL specifies that a column can contain null values. The NULL keyword does not actually define an integrity constraint. If you do not specify either NOT NULL or NULL, the column can contain nulls by default. specifies that a column cannot contain null values. To satisfy this constraint, every row in the table must contain a value for the column.
NOT NULL
Restriction: You cannot specify NULL or NOT NULL for an attribute of an object. Instead, use a CHECK constraint with the IS [NOT] NULL condition. See the "Attribute-Level Constraints Example" on page 7-248. Referential integrity constraints Referential integrity constraints designate a column or combination of columns as the foreign key and establish a relationship between that foreign key and a specified primary or unique key, called the referenced key. The table containing the foreign key is called the child table, and the table containing the referenced key is called the parent table. The foreign key and the referenced key can be in the same table. In this case, the parent and child tables are the same.
SQL Statements
7-239
constraint_clause
From the table level, specify referential integrity using the foreign_key_clause with the table_ constraint syntax. This syntax allows you to specify a composite foreign key, which is made up of a combination of columns. From the column level, use the REFERENCES clause of the column_constraint syntax to specify a referential integrity constraint in which the foreign key is made up of a single column. 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. Restrictions:
s s
A foreign key cannot be of type LONG or LONG RAW. The referenced UNIQUE or PRIMARY KEY constraint on the parent table must already be defined. The child and parent tables must be on the same database. To enable referential integrity constraints across nodes of a distributed database, you must use database triggers. You cannot define a referential integrity constraint in a CREATE TABLE statement that contains an AS subquery clause. Instead, you must create the table without the constraint and then add it later with an ALTER TABLE statement.
s
s
See Also: Oracle8i Application Developer's Guide - Fundamentals. foreign_key_ clause designates a column or combination of columns as the foreign key from the table level. You must use this syntax to define a composite foreign key. To satisfy a referential integrity constraint involving composite keys, either the values of the foreign key columns must match the values of the referenced key columns in a row in the parent table, or the value of at least one of the columns of the foreign key must be null. Restrictions:
s
A composite foreign key cannot have more than 32 columns. The overall size of the key (in bytes) should not exceed approximately the width of all indexed columns plus the number of indexed columns. A composite foreign key must refer to a composite unique key or a composite primary key.
s
7-240 SQL Reference
constraint_clause
REFERENCES
designates the current column or attribute as the foreign key and identifies the parent table and the column or combination of columns that make up the referenced key. If you identify only 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. determines how Oracle automatically maintains referential integrity if you remove a referenced primary or unique key value. If you omit this clause, Oracle does not allow you to delete referenced key values in the parent table that have dependent rows in the child table.
s
ON DELETE
CASCADE specifies that Oracle removes dependent foreign key values. SET NULL specifies that Oracle converts dependent foreign key values to NULL.
s
CHECK
specifies a condition that each row in the table must satisfy. To satisfy the constraint, each row in the table must make the condition either TRUE or unknown (due to a null). For information and syntax, see "Conditions" on page 5-14. When 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, and do not assume any particular order of evaluation of the conditions. Oracle does not verify that CHECK conditions are not mutually exclusive. Restrictions: 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 the following constructs:
s s s s
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
SQL Statements
7-241
constraint_clause
table_ref_ constraint and column_ref_ constraint
further describe a column of type REF. The only difference between these clauses is that you specify table_ref_constraint from the table level, so you must identify the REF column or attribute you are defining. You specify column_ref_constraint after you have already identified the REF column or attribute. Both types of constraint let you specify a SCOPE constraint, a WITH ROWID constraint, or a referential integrity constraint. As is the case for regular table and column constraints, you use FOREIGN KEY syntax for a referential integrity constraint at the table level, and REFERENCES syntax for a referential integrity constraint at the column level. See "Referential integrity constraints" on page 7-239. If the REF column's scope table or reference table has a primary-key-based object identifier, then it is a user-defined REF column. See Also: Oracle8i Concepts for more information on REFs. ref_column ref_attribute SCOPE is the name of a REF column of an object or relational table. is an embedded REF attribute within an object column of a relational table. In a table with a REF column, each REF value in the column can conceivably reference a row in a different object table. The SCOPE clause restricts the scope of references to a single table, scope_table_name. The values in the REF column or attribute point to objects in scope_table_ name, in which object instances (of the same type as the REF column) are stored. You can only specify one scope table per REF column. Restrictions:
s
You can add a SCOPE constraint to an existing column only if the table is empty. You cannot specify SCOPE for the REF elements of a varray column. You must specify this clause if you specify AS subquery and the subquery returns user-defined REFs. The scope_table_name must be in your own schema or you must have SELECT privileges on scope_table_name or SELECT ANY TABLE system privileges. You cannot drop a SCOPE table constraint from a REF column.
s s
s
s
WITH ROWID
stores the rowid along with the REF value in ref_column or ref_attribute. Storing a REF value with a rowid can improve the performance of dereferencing operations, but will also use more space. Default storage of REF values is without rowids.
7-242 SQL Reference
constraint_clause
Restrictions:
s
You cannot specify a WITH ROWID constraint for the REF elements of a varray column. You cannot drop a WITH ROWID constraint from a REF column. If the REF column or attribute is scoped, then this clause is ignored and the rowid is not stored with the REF value.
s s
references_clause
specifies a referential integrity constraint on the REF column.This clause also implicitly restricts the scope of the REF column or attribute to the reference table. If you do not specify CONSTRAINT, Oracle generates a system name for the constraint. Restrictions:
s
If you add a referential integrity constraint to an existing REF column that is scoped, then the referenced table must be the same as the scope table of the REF column. The system adds a scope constraint when you add a referential integrity constraint to an existing unscoped REF column. Therefore, all the restrictions that apply for the SCOPE constraint also apply in this case. If you later drop the referential integrity constraint, the REF column will remain scoped to the referenced table.
s
s
DEFERRABLE
indicates that constraint checking can be deferred until the end of the transaction by using the SET CONSTRAINT(S) statement. For information on checking constraints after each DML statement, see "SET CONSTRAINT(S)" on page 7-598. See Oracle8i Administrator's Guideand Oracle8i Concepts for more information about deferred constraints. indicates that this constraint is checked at the end of each DML statement. If you do not specify either word, then NOT DEFERRABLE is the default. indicates that at the start of every transaction, the default is to check this constraint at the end of every DML statement. If you do not specify INITIALLY, INITIALLY IMMEDIATE is the default. implies that this constraint is DEFERRABLE and specifies that, by default, the constraint is checked only at the end of each transaction.
NOT DEFERRABLE INITIALLY IMMEDIATE INITIALLY DEFERRED Restrictions:
s s
You cannot defer a NOT DEFERRABLE constraint with the SET CONSTRAINT(S) statement. You cannot specify either DEFERRABLE or NOT DEFERRABLE if you are modifying an existing constraint directly (that is, by specifying the ALTER TABLE ... MODIFY constraint statement). You cannot alter a constraint's deferrability status. You must drop the constraint and re-create it.
s
SQL Statements
7-243
constraint_clause
RELY | NORELY
specifies whether an enabled constraint is to be enforced. Specify RELY to enable an existing constraint without enforcement. Specify NORELY to enable and enforce an existing constraint. The default is NORELY. Unenforced constraints are generally useful only with materialized views and query rewrite. Depending on the QUERY_REWRITE_INTEGRITY mode (see "ALTER SESSION" on page 7-83), query rewrite can use constraints that are enabled with or without enforcement to determine join information. See Also: Oracle8i Data Warehousing Guide for more information on materialized views and query rewrite. Restrictions:
s
RELY and NORELY are relevant only if you are modifying an existing constraint (that is, you have issued the ALTER TABLE ... MODIFY constraint statement). You cannot set a NOT NULL constraint to RELY.
s
using_index_clause specifies parameters for the index Oracle uses to enable a UNIQUE or PRIMARY KEY constraint. The name of the index is the same as the name of 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 "CREATE TABLE" on page 4-381. If table is partitioned, you can specify a locally or globally partitioned index for the unique or primary key constraint. For a description of LOCAL and global_index_clause, and for a description of NOSORT and LOGGING|NOLOGGING in relation to indexes, see "CREATE INDEX" on page 7-291. Restriction: Use this clause only when enabling UNIQUE and PRIMARY KEY constraints. NOSORT ENABLE indicates 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. specifies that the constraint will be applied to all new data in the table. Before you can enable a referential integrity constraint, its referenced constraint must be enabled.
s
ENABLE VALIDATE additionally specifies that all old data also complies with the constraint. An enabled validated constraint guarantees that all data is and will continue to be valid. If you place a primary key constraint in ENABLE VALIDATE mode, the validation process will verify that the primary key columns contain no nulls. To avoid this overhead, mark each column in the primary key NOT NULL before enabling the table's primary key constraint. (For optimal results, do this before inserting data into the column.)
s
ENABLE NOVALIDATE ensures that all new DML operations on the constrained data comply with the constraint, but does not ensure that existing data in the table complies with the constraint.
7-244 SQL Reference
constraint_clause
Enabling a primary key or unique key constraint automatically creates a unique index to enforce the constraint. This index is dropped if the constraint is subsequently disabled, causing Oracle to rebuild the index every time the constraint is enabled. To avoid this behavior, create new primary key and unique key constraints initially disabled. Then create nonunique indexes or use existing nonunique indexes to enforce the constraints. For additional notes and restrictions, see the enable_disable_clause of "CREATE TABLE" on page 4-405. DISABLE disables the integrity constraint. If you do not specify this clause when creating a constraint, Oracle automatically enables the constraint.
s
DISABLE VALIDATE disables the constraint and drops the index on the constraint, but keeps the constraint valid. This feature is most useful in data warehousing situations, where the need arises to load into a range-partitioned table a quantity of data with a distinct range of values in the unique key. In such situations, the disable validate state enables you to save space by not having an index. You can then load data from a nonpartitioned table into a partitioned table using the exchange_partition_clause of the ALTER TABLE statement or using SQL*Loader. All other modifications to the table (inserts, updates, and deletes) by other SQL statements are disallowed. If the unique key coincides with the partitioning key of the partitioned table, disabling the constraint saves overhead and has no detrimental effects. If the unique key does not coincide with the partitioning key, Oracle performs automatic table scans during the exchange to validate the constraint, which might offset the benefit of loading without an index.
s
DISABLE NOVALIDATE signifies that Oracle makes no effort to maintain the constraint (because it is disabled) and cannot guarantee that the constraint is true (because it is not being validated). For information on when to use this setting, see Oracle8i Designing and Tuning for Performance. You cannot drop a table whose primary key is being referenced by a foreign key even if the foreign key constraint is in DISABLE NOVALIDATE state. Further, the optimizer can use constraints in DISABLE NOVALIDATE state.
s s
If you specify neither VALIDATE nor NOVALIDATE, the default is NOVALIDATE. If you disable a unique or primary key constraint that is using a unique index, Oracle drops the unique index.
EXCEPTIONS INTO
specifies a table into which Oracle places the rowids of all rows violating the constraint. If you omit schema, Oracle assumes the exceptions table is in your own schema. If you omit this clause altogether, Oracle assumes that the table is named EXCEPTIONS. The exceptions table must be on your local database.
SQL Statements
7-245
constraint_clause
You can create the EXCEPTIONS table using one of these scripts:
s
UTLEXCPT.SQL uses physical rowids. Therefore it can accommodate rows from conventional tables but not from index-organized tables. (See the Note that follows.) UTLEXPT1.SQL uses universal rowids, so it can accommodate rows from both conventional and index-organized tables.
s
If you create your own exceptions table, it must follow the format prescribed by one of these two scripts. See Oracle8i Migration for compatibility issues related to the use of these scripts. Note: If you are collecting exceptions from index-organized tables based on primary keys (rather than universal rowids), you must create a separate exceptions table for each indexorganized table to accommodate its primary-key storage. You create multiple exceptions tables with different names by modifying and resubmitting the script. For information on the SQL scripts, see the DBMS_IOT package in Oracle8i Supplied PL/SQL Packages Reference. For information on eliminating migrated and chained rows, see Oracle8i Designing and Tuning for Performance. This clause is valid only when validating a constraint.
Examples
Unique Key Example The following 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
7-246 SQL Reference
constraint_clause
STORAGE (INITIAL 8K
NEXT 6K) );
The above statement also uses the USING INDEX clause to specify storage characteristics for the index that Oracle creates to enable the constraint.
Composite Unique Key Example The following 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 ADD CONSTRAINT clause also specifies other properties of the constraint:
s
The USING INDEX clause specifies storage characteristics for the index Oracle creates to enable the constraint. The EXCEPTIONS INTO clause causes Oracle to write information to the BAD_ KEYS_IN_SHIP_CONT table about any rows currently in the CENSUS table that violate the constraint.
s
Primary Key Example
CREATE TABLE (deptno dname loc
The following statement creates the DEPT table and defines and enables a primary key on the DEPTNO column:
dept NUMBER(2) CONSTRAINT pk_dept PRIMARY KEY, VARCHAR2(9), VARCHAR2(10) );
The PK_DEPT constraint identifies the DEPTNO column as the primary key of the DEPT 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),
SQL Statements
7-247
constraint_clause
CONSTRAINT pk_dept PRIMARY KEY (deptno) );
Composite Primary Key Example The following 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_CONT table. 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 the following properties of the constraint:
s
The constraint definition does not include a constraint name, so Oracle generates a name for the constraint. The DISABLE clause causes Oracle to define the constraint but not enable it.
s
The following statement alters the EMP table and defines and enables a NOT NULL constraint on the SAL column:
NOT NULL Example
ALTER TABLE emp MODIFY (sal NUMBER CONSTRAINT nn_sal NOT NULL);
NN_SAL ensures that no employee in the table has a null salary. The following example guarantees that a value exists for both the FIRST_NAME and LAST_NAME attributes of the NAME column in the STUDENTS table:
Attribute-Level Constraints Example
CREATE TYPE person_name AS OBJECT (first_name VARCHAR2(30), last_name VARCHAR2(30)); CREATE TABLE students (name person_name, age INTEGER, CHECK (name.first_name IS NOT NULL AND name.last_name IS NOT NULL));
The following 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:
Referential Integrity Constraint Example
CREATE TABLE emp (empno NUMBER(4),
7-248 SQL Reference
constraint_clause
ename job mgr hiredate sal comm deptno
VARCHAR2(10), VARCHAR2(9), NUMBER(4), DATE, NUMBER(7,2), NUMBER(7,2), CONSTRAINT fk_deptno REFERENCES dept(deptno) );
The constraint FK_DEPTNO ensures that all departments given for employees in the EMP table are present in the DEPT table. However, employees can have null department numbers, meaning they are not assigned to any department. To ensure that all employees are assigned to a department, you could create a NOT NULL constraint on the DEPTNO column in the EMP table, in addition to the REFERENCES constraint. 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. 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. 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. The above 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)
SQL Statements
7-249
constraint_clause
REFERENCES
dept(deptno) );
The foreign key definitions in both statements of this statement omit the ON DELETE clause, causing Oracle to forbid the deletion of a department if any employee works in that department.
ON DELETE Example This statement creates the EMP table, defines and enables
two referential integrity constraints, and uses the ON DELETE clause:
CREATE TABLE emp (empno NUMBER(4) PRIMARY KEY, ename VARCHAR2(10), job VARCHAR2(9), mgr NUMBER(4) CONSTRAINT fk_mgr REFERENCES emp ON DELETE SET NULL, 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 first ON DELETE clause, if manager number 2332 is deleted from the EMP table, Oracle sets to null the value of MGR for all employees in the EMP table who previously had manager 2332. Because of the second ON DELETE clause, 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.
Composite Referential Integrity Constraint Example The following 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
7-250 SQL Reference
constraint_clause
designates the combination of the AREACO and PHONENO columns of the CUSTOMERS table as a primary or unique key. The EXCEPTIONS INTO clause causes Oracle to write information to the WRONG_ NUMBERS table about any rows in the PHONE_CALLS table that violate the constraint. The following statement creates the DEPT table and defines a CHECK constraint in each of the table's columns:
CHECK Constraint Examples
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:
s
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.
s
s
Because each CONSTRAINT clause contains the DISABLE clause, Oracle only defines the constraints and does not enable them. The following statement creates the EMP table and uses a table_constraint_clause to define and enable a CHECK constraint:
CREATE TABLE emp (empno ename job mgr hiredate sal comm deptno NUMBER(4), VARCHAR2(10), VARCHAR2(9), NUMBER(4), DATE, NUMBER(7,2), NUMBER(7,2), NUMBER(2),
SQL Statements
7-251
constraint_clause
CHECK (sal + comm <= 5000) );
This constraint uses an inequality condition to limit an employee's total compensation, the sum of salary and commission, to $5000:
s
If an employee has non-null values for both salary and commission, the sum of these values must not exceed $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.
s
Because the CONSTRAINT clause in this example does not supply a constraint name, Oracle generates a name for the constraint. The following 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 enable the following rules on table data:
s
PK_OD identifies the combination of the ORDER_ID and PART_NO columns as the primary key of the table. To satisfy this constraint, no two rows in the table can contain the same combination of values in the ORDER_ID and the PART_NO columns, and 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.
s
s
7-252 SQL Reference
constraint_clause
s
NN_QTY forbids nulls in the QUANTITY column. CHECK_QTY ensures that values in the QUANTITY column are always greater than zero. CHECK_COST ensures the values in the COST column are always greater than zero.
s
s
This example also illustrates the following points about constraint clauses and column definitions:
s
Table_constraint syntax and column definitions can appear in any order. In this example, the table_constraint syntax that defines the PK_OD constraint precedes 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 identifying the constraint. Such an error more precisely identifies the violated business rule if the identified constraint enables a single business rule.
s
s
DEFERRABLE Constraint Examples The following statement creates table GAMES
with a NOT DEFERRABLE INITIALLY IMMEDIATE constraint check on the SCORES column:
CREATE TABLE games (scores NUMBER CHECK (scores >= 0));
To define a unique constraint on a column as INITIALLY DEFERRED DEFERRABLE, issue the following statement:
CREATE TABLE orders (ord_num NUMBER CONSTRAINT unq_num UNIQUE (ord_num) INITIALLY DEFERRED DEFERRABLE);
SQL Statements
7-253
CREATE CLUSTER
CREATE CLUSTER
Syntax
schema CREATE CLUSTER . cluster ( column , datatype )
physical_attributes_clause K M SIZE integer tablespace
TABLESPACE INDEX SINGLE
TABLE HASHKEYS CACHE integer
HASH
IS
expr
parallel_clause
N0CACHE ;
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
storage_clause: See the "storage_clause" on page 7-605.
7-254 SQL Reference
CREATE CLUSTER
parallel_clause::=
NOPARALLEL integer PARALLEL
Purpose
To create a cluster. A cluster is a schema object that contains data from one or more tables, all of which have one or more columns in common. Oracle stores together all the rows (from all the tables) that share the same cluster key. For general information on clusters, see Oracle8i Concepts. For information on performance considerations of clusters, see Oracle8i Application Developer's Guide Fundamentals. For suggestions on when to use clusters, see Oracle8i Designing and Tuning for Performance.
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. Oracle does not automatically create an index for a cluster when the cluster is initially created. Data manipulation language (DML) statements cannot be issued against clustered tables until a cluster index has been created.
Keywords and Parameters
schema cluster is the schema to contain the cluster. If you omit schema, Oracle creates the cluster in your current schema. is the name of the cluster to be created. After you create a cluster, you add tables to it. A cluster can contain a maximum of 32 tables. 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 nonclustered tables. For information on adding tables to a cluster, see "CREATE TABLE" on page 4-381.
SQL Statements
7-255
CREATE CLUSTER
column
is the name of a column in the cluster key. You can specify up to 16 cluster key columns. These 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.
datatype
is the datatype of a cluster key column. For information on datatypes, see the section "Datatypes" on page 2-9. Restrictions:
s
You cannot specify a cluster key column of datatype LONG, LONG RAW, REF, nested table, varray, BLOB, CLOB, BFILE, or user-defined object type. You cannot use the HASH IS clause if any column datatype is not INTEGER or NUMBER with scale 0. You can specify a column of type ROWID, but Oracle does not guarantee that the values in such columns are valid rowids.
s
s
physical_ specifies the storage characteristics of the cluster. Each table in the cluster uses these storage attributes_clause characteristics as well. 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. 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. 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 2 or the INITRANS value for the cluster's tablespace, whichever is greater. 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 "CREATE TABLE" on page 4-381. storage_clause SIZE specifies how data blocks are allocated to the cluster. See the "storage_clause" on page 7-605. specifies the amount of space in bytes to store all rows with the same cluster key value or the same hash value. Use K or M to specify this space in kilobytes or megabytes. This space determines the maximum number of cluster or hash values stored in a data block. If SIZE is not a divisor of the data block size, Oracle uses the next largest divisor. If SIZE 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.
PCTFREE INITRANS
MAXTRANS
7-256 SQL Reference
CREATE CLUSTER
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.) If you omit this parameter, Oracle reserves one data block for each cluster key value or hash value. TABLESPACE INDEX specifies the tablespace in which the cluster is created. creates an indexed cluster. In an indexed cluster, Oracle stores together rows having the same cluster key value. 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. After you create an indexed cluster, you must create an index on the cluster key before you can issue any data manipulation language (DML) statements against a table in the cluster. This index is called the cluster index. For information on creating a cluster index, see "CREATE INDEX" on page 7-291. Note: You cannot create a cluster index for a hash cluster, and you need not create an index on a hash cluster key. If you specify neither INDEX nor HASHKEYS, Oracle creates an indexed cluster by default. See Also: Oracle8i Concepts for more information in indexed clusters. HASHKEYS creates a hash cluster and specifies the number of hash values for a hash cluster. 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. Oracle rounds up the HASHKEYS value 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 clause and the HASHKEYS parameter, Oracle creates an indexed cluster by default. When you create a hash cluster, Oracle immediately allocates space for the cluster based on the values of the SIZE and HASHKEYS parameters. See Also: Oracle8i Concepts for more information on how Oracle allocates space for clusters. SINGLE TABLE specifies that the cluster is a type of hash cluster containing only one table. This clause can provide faster access to rows than would result if the table were not part of a cluster. Restriction: Only one table can be present in the cluster at a time. However, you can drop the table and create a different table in the same cluster. HASH IS specifies an expression to be used as the hash function for the hash cluster. The expression:
SQL Statements
7-257
CREATE CLUSTER
s s
Must evaluate to a positive value Must contain at least one column with referenced columns of any datatype as long as the entire expression evaluates to a number of scale 0. For example: NUM_COLUMN * length(VARCHAR2_ COLUMN) Cannot reference user-defined PL/SQL functions Cannot reference SYSDATE, USERENV, TO_DATE, UID, USER, LEVEL, or ROWNUM Cannot evaluate to a constant Cannot contain a subquery Cannot contain columns qualified with a schema or object name (other than the cluster name)
s
s
s s s
If you omit the HASH IS clause, 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 noninteger columns must use the internal hash function. parallel_clause causes creation of the cluster to be parallelized. See also the Notes to the parallel_clause of "CREATE TABLE" on page 4-381. NOPARALLEL PARALLEL specifies serial execution. This is the default. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances times the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution servers. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer. Restriction: If the tables in cluster contain any columns of LOB or user-defined object type, this statement as well as subsequent INSERT, UPDATE, or DELETE operations on cluster are executed serially without notification. CACHE specifies that the blocks retrieved for this table are placed at the most recently used end of the LRU list in the buffer cache when a full table scan is performed. This clause is useful for small lookup tables. specifies that the blocks retrieved for this table are placed at the least recently used end of the LRU list in the buffer cache when a full table scan is performed. This is the default behavior.
NOCACHE
7-258 SQL Reference
CREATE CLUSTER
Examples
Creating a Cluster The following 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);
Adding Tables to a Cluster The following statements add the EMP and DEPT tables
to the cluster:
CREATE TABLE emp (empno NUMBER ename VARCHAR2(10) PRIMARY KEY, NOT NULL CHECK (ename = UPPER(ename)),
job VARCHAR2(9), mgr NUMBER REFERENCES scott.emp(empno), hiredate DATE CHECK (hiredate < TO_DATE ('08-14-1998', 'MM-DD-YYYY')), sal NUMBER(10,2) CHECK (sal > 500), comm NUMBER(9,0) DEFAULT NULL, deptno NUMBER(2) NOT NULL ) CLUSTER personnel (deptno); CREATE TABLE (deptno dname loc CLUSTER dept NUMBER(2), VARCHAR2(9), VARCHAR2(9)) personnel (deptno);
Cluster Key Example The following 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.
Hash Cluster Examples The following statement creates a hash cluster named PERSONNEL with the cluster key column DEPARTMENT_NUMBER, a maximum of 503 hash key values, each of which is allocated 512 bytes, and storage parameter values:
SQL Statements
7-259
CREATE CLUSTER
CREATE CLUSTER personnel ( department_number NUMBER ) SIZE 512 HASHKEYS 500 STORAGE (INITIAL 100K NEXT 50K);
Because the above statement omits the HASH IS clause, Oracle uses the internal hash function for the cluster. The following statement creates a hash cluster named PERSONNEL with the cluster key made up of the columns HOME_AREA_CODE and HOME_PREFIX, and uses a SQL expression containing these columns for the hash function:
CREATE CLUSTER personnel ( home_area_code NUMBER, home_prefix NUMBER ) HASHKEYS 20 HASH IS MOD(home_area_code + home_prefix, 101);
Single-Table Hash Cluster Example The following statement creates a single-table
hash cluster named PERSONNEL with the cluster key DEPTNO and a maximum of 503 hash key values, each of which is allocated 512 bytes:
CREATE CLUSTER personnel (deptno NUMBER) SIZE 512 SINGLE TABLE HASHKEYS 500;
7-260 SQL Reference
CREATE CONTEXT
7SQL Statements
CREATE CONTEXT
Syntax
OR CREATE REPLACE CONTEXT namespace USING schema . package ;
Purpose
To create a namespace for a context (a set of application-defined attributes that validates and secures an application) and to associate the namespace with the externally created package that sets the context.
See Also: Oracle8i Concepts for a definition and discussion of
contexts.
Prerequisites
To create a context namespace, you must have CREATE ANY CONTEXT system privilege.
Keywords and Parameters
OR REPLACE namespace schema package redefines an existing context namespace using a different package. is the name of the context namespace to create or modify. Context namespaces are always stored in the schema SYS. is the schema owning package. If you omit schema, Oracle uses the current schema. is the PL/SQL package that sets or resets the context attributes under the namespace for a user session. See Also: Oracle8i Supplied PL/SQL Packages Reference for more information on setting the package. Note: To provide some design flexibility, Oracle does not verify the existence of the schema or the validity of the package at the time you create the context.
SQL Statements
7-261
CREATE CONTEXT
Examples
Suppose you have a human resources (HR) application and a PL/SQL package (HR_SECURE_CONTEXT), which validates and secures the HR application. The following statement creates the context namespace HR_CONTEXT and associates it with the package HR_SECURE_CONTEXT:
CREATE CONTEXT hr_context USING hr_secure_context;
You can control data access based on this context using the SYS_CONTEXT function. For example, suppose your HR_SECURE_CONTEXT package has defined an attribute ORG_ID as a particular organization identifier. You can secure a base table HR_ORG_ UNIT by creating a view that restricts access based on the value of ORG_ID, as follows:
CREATE VIEW hr_org_secure_view AS SELECT * FROM hr_org_unit WHERE organization_id = SYS_CONTEXT('hr_context', 'org_id');
See Also: "SYS_CONTEXT" on page 4-93 for more information on the SYS_CONTEXT function.
7-262 SQL Reference
CREATE CONTROLFILE
CREATE CONTROLFILE
Syntax
WARNING: Oracle recommends that you perform a full backup of all files in the database before using this statement. For more information, see Oracle8i Backup and Recovery Guide.
REUSE CREATE CONTROLFILE , GROUP LOGFILE integer filespec
SET DATABASE database
RESETLOGS NORESETLOGS MAXLOGFILES MAXLOGMEMBERS MAXLOGHISTORY MAXDATAFILES MAXINSTANCES ARCHIVELOG integer integer integer integer integer
, DATAFILE CHARACTER filespec SET character_set
NOARCHIVELOG
;
filespec: See "filespec" on page 7-516.
Purpose
To re-create a control file in one of the following cases:
SQL Statements
7-263
CREATE CONTROLFILE
s
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, datafiles, or instances that can concurrently have the database mounted and open.
s
s
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 clauses, Oracle uses the default values rather than the values for the previous control file. After successfully creating the control file, Oracle mounts the database in the mode specified by the initialization parameter PARALLEL_SERVER. You then must perform media recovery before opening the database. It is recommended that you then shut down the instance and take a full backup of all files in the database.
See Also: Oracle8i Backup and Recovery Guide for more information
about using this statement.
Prerequisites
You must have the OSDBA role enabled. The database must not be mounted by any instance. If the REMOTE_LOGIN_PASSWORDFILE initialization parameter is set to EXCLUSIVE, Oracle returns an error when you attempt to re-create the control file. To avoid this message, either set the parameter to SHARED, or re-create your password file before re-creating the control file.
See Also: Oracle8i Reference for more information about the
REMOTE_LOGIN_PASSWORDFILE parameter.
Keywords and Parameters
REUSE specifies that existing control files identified by the initialization parameter CONTROL_ FILES can be reused, thus ignoring and overwriting any information they may currently contain. If you omit this clause and any of these control files already exists, Oracle returns an error. 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. changes the name of the database. The name of a database can be as long as eight bytes.
DATABASE database
SET DATABASE database
7-264 SQL Reference
CREATE CONTROLFILE
LOGFILE
specifies the redo log files for your database. You must list all members of all redo log file groups. See Also: "filespec" on page 7-516 for the syntax of filespec. GROUP integer specifies logfile group. If you specify GROUP values, Oracle verifies these values with the GROUP values when the database was last open.
RESETLOGS
ignores the contents of the files listed in the LOGFILE clause. These files do not have to exist. Each filespec in the LOGFILE clause must specify the SIZE parameter. Oracle assigns all online redo log file groups to thread 1 and enables this thread for public use by any instance. After using this clause, you must open the database using the RESETLOGS clause of the ALTER DATABASE statement. specifies that all files in the LOGFILE clause should be used as they were when the database was last open. These files must exist and must be the current online redo log files rather than restored backups. Oracle reassigns the redo log file groups to the threads to which they were previously assigned and reenables the threads as they were previously enabled. specifies the datafiles of the database. You must list all datafiles. These files must all exist, although they may be restored backups that require media recovery. See the syntax description of filespec in "filespec" on page 7-516. specifies the maximum number of online 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. specifies the maximum number of members, or identical 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. 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 depends on your operating system. The maximum value is limited only by the maximum size of the control file. This parameter is useful only if you are using Oracle with the Parallel Server option in both parallel mode and archivelog mode. specifies the initial sizing of the datafiles section of the control file at CREATE DATABASE or CREATE CONTROLFILE time. An attempt to add a file whose number is greater than MAXDATAFILES, but less than or equal to DB_FILES, causes the Oracle control file to expand automatically so that the datafiles section can accommodate more files. The number of datafiles accessible to your instance is also limited by the initialization parameter DB_FILES.
NORESETLOGS
DATAFILE
MAXLOGFILES integer
MAXLOGMEMBERS integer
MAXLOGHISTORY integer
MAXDATAFILES integer
SQL Statements
7-265
CREATE CONTROLFILE
MAXINSTANCES integer
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. establishes the mode of archiving the contents of redo log files before reusing them. This clause prepares for the possibility of media recovery as well as instance or crash recovery. If you omit both the ARCHIVELOG clause and NOARCHIVELOG clause, Oracle chooses NOARCHIVELOG mode by default. After creating the control file, you can change between ARCHIVELOG mode and NOARCHIVELOG mode with the ALTER DATABASE statement. optionally reconstructs character set information in the control file. In case media recovery of the database is required, this information will be available before the database is open, so that tablespace names can be correctly interpreted during recovery. This clause is useful only if you are using a character set other than the default US7ASCII. If you are re-creating your control file and you are using Recovery Manager for tablespace recovery, and if you specify a different character set from the one stored in the data dictionary, then tablespace recovery will not succeed. (However, at database open, the control file character set will be updated with the correct character set from the data dictionary.) See Also: Oracle8i Recovery Manager User's Guide and Reference for more information on tablespace recovery. Note: You cannot modify the character set of the database with this clause.
ARCHIVELOG
NOARCHIVELOG
CHARACTER SET character_set
Example
This statement re-creates a control file. In this statement, database ORDERS_2 was created with the F7DEC character set.
CREATE CONTROLFILE REUSE 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 CHARACTER SET F7DEC;
7-266 SQL Reference
CREATE DATABASE
CREATE DATABASE
Syntax
WARNING: This statement prepares a database for initial use and erases any data currently in the specified files. Use this statement only when you understand its ramifications.
CONTROLFILE
REUSE , GROUP integer filespec integer integer integer integer ; integer
LOGFILE MAXLOGFILES MAXLOGMEMBERS MAXLOGHISTORY database CREATE DATABASE MAXINSTANCES ARCHIVELOG NOARCHIVELOG CHARACTER NATIONAL SET charset SET , MAXDATAFILES
CHARACTER
charset
autoextend_clause DATAFILE filespec
SQL Statements
7-267
CREATE DATABASE
autoextend_clause::=
OFF K AUTOEXTEND NEXT ON integer M maxsize_clause
maxsize_clause::=
UNLIMITED MAXSIZE integer K M
filespec: See "filespec" on page 7-516.
Purpose
To create a database, making it available for general use. This statement erases all data in any specified datafiles that already exist in order to prepare them for initial database use. If you use the statement on an existing database, all data in the datafiles is lost. After creating the database, this statement mounts it in either exclusive or parallel mode (depending on the value of the PARALLEL_SERVER initialization parameter) and opens it, making it available for normal use. You can then create tablespaces and rollback segments for the database. For information on these tasks, see "CREATE ROLLBACK SEGMENT" on page 4-367 and "CREATE TABLESPACE" on page 4-419.
See Also:
s
"ALTER DATABASE" on page 7-6 for information on modifying a database. Oracle8i Java Developer's Guide for information on creating an Oracle8i Java virtual machine.
s
7-268 SQL Reference
CREATE DATABASE
Prerequisites
You must have the OSDBA role enabled. If the REMOTE_LOGIN_PASSWORDFILE initialization parameter is set to EXCLUSIVE, Oracle returns an error when you attempt to re-create the database. To avoid this message, either set the parameter to SHARED, or re-create your password file before re-creating the database.
See Also: Oracle8i Reference for more information about the REMOTE_LOGIN_PASSWORDFILE parameter.
Keyword and Parameters
database is the name of the database to be created and can be up to 8 bytes long. The database name can contain only ASCII characters. Oracle writes this name into the control file. If you subsequently issue an ALTER DATABASE statement that explicitly specifies a database name, Oracle verifies that name with the name in the control file. Database names should also adhere to the rules described in "Schema Object Naming Rules" on page 2-72. Note: You cannot use special characters from European or Asian character sets in a database name. For example, characters with umlauts are not allowed. If you omit the database name from a CREATE DATABASE statement, Oracle uses the name specified by the initialization parameter DB_NAME. If the DB_NAME initialization parameter has been set, and you specify a different name from the value of that parameter, Oracle returns an error. CONTROLFILE REUSE reuses existing control files identified by the initialization parameter CONTROL_FILES, thus ignoring and overwriting any information they currently contain. Normally you use this clause only when you are re-creating a database, rather than creating one for the first time. You cannot use this clause 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 clause and any of the files specified by CONTROL_FILES already exist, Oracle returns an error. 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 (copies). For the syntax of filespec, see "filespec" on page 7-516. All redo log files specified in a CREATE DATABASE statement are added to redo log thread number 1.
SQL Statements
7-269
CREATE DATABASE
GROUP integer
uniquely identifies a redo log file group and can range from 1 to the value of the MAXLOGFILES parameter. A database must have at least two redo log file groups. 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 depend on your operating system. MAXLOGFILES integer 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 depend on your operating system. MAXLOGMEMBERS integer 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. specifies the maximum number of archived redo log files for automatic media recovery with 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 depends on your operating system. The maximum value is limited only by the maximum size of the control file. Note: This parameter is useful only if you are using Oracle with the Parallel Server option in parallel mode, and archivelog mode enabled. MAXDATAFILES integer specifies the initial sizing of the datafiles section of the control file at CREATE DATABASE or CREATE CONTROLFILE time. An attempt to add a file whose number is greater than MAXDATAFILES, but less than or equal to DB_FILES, causes the Oracle control file to expand automatically so that the datafiles section can accommodate more files. The number of datafiles accessible to your instance is also limited by the initialization parameter DB_FILES. MAXINSTANCES integer specifies the maximum number of instances that can simultaneously have this database mounted and open. This value takes precedence over the value of initialization parameter INSTANCES. The minimum value is 1. The maximum and default values depend on your operating system. specifies that the contents of a redo log file group must be archived before the group can be reused. This clause prepares for the possibility of media recovery. specifies that the contents of a redo log file group need not be archived before the group can be reused. This clause does not allow for the possibility of media recovery.
MAXLOGHISTORY integer
ARCHIVELOG NOARCHIVELOG
7-270 SQL Reference
CREATE DATABASE
The default is NOARCHIVELOG mode. After creating the database, you can change between ARCHIVELOG mode and NOARCHIVELOG mode with the ALTER DATABASE statement. CHARACTER SET specifies the character set the database uses to store data. The supported character sets and default value of this parameter depend on your operating system. Restriction: You cannot specify any fixed-width multibyte character sets as the database character set. See Also: Oracle8i National Language Support Guide for more information about character sets. NATIONAL CHARACTER SET specifies the national character set used to store data in columns specifically defined as NCHAR, NCLOB, or NVARCHAR2. If not specified, the national character set defaults to the database character set. See Oracle8i National Language Support Guide for valid character set names. specifies one or more files to be used as datafiles. See the syntax description of filespec in "filespec" on page 7-516. All these files become part of the SYSTEM tablespace. If you omit this clause, Oracle creates one datafile by default. The name and size of this default file depend on your operating system. Note: Oracle recommends that the total initial space allocated for the SYSTEM tablespace be a minimum of 5 megabytes. autoextend_clause enables or disables the automatic extension of a datafile. If you do not specify this clause, datafiles are not automatically extended. OFF disables autoextend if it is turned on. NEXT and MAXSIZE are set to zero. Values for NEXT and MAXSIZE must be respecified in ALTER DATABASE AUTOEXTEND or ALTER TABLESPACE AUTOEXTEND statements. enables autoextend. specifies the size in bytes of the next increment of disk space to be allocated to the datafile automatically when more extents are required. Use K or M to specify this size in kilobytes or megabytes. The default is the size of one data block. specifies the maximum disk space allowed for automatic extension of the datafile. sets no limit on the allocation of disk space to the datafile.
DATAFILE
ON NEXT
MAXSIZE UNLIMITED
Examples
The following statement creates a small database using defaults for all arguments:
CREATE DATABASE;
SQL Statements
7-271
CREATE DATABASE
The following 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 CHARACTER SET US7ASCII NATIONAL CHARACTER SET JA16SJISFIXED DATAFILE 'disk1:df1.dbf' AUTOEXTEND ON 'disk2:df2.dbf' AUTOEXTEND ON NEXT 10M MAXSIZE UNLIMITED;
7-272 SQL Reference
CREATE DATABASE LINK
CREATE DATABASE LINK
Syntax
SHARED CREATE CURRENT_USER CONNECT TO user authenticated_clause USING ' connect_string ' ; IDENTIFIED BY password authenticated_clause PUBLIC DATABASE LINK dblink
authenticated_clause::=
AUTHENTICATED BY user IDENTIFIED BY password
Purpose
To create a database link. A database link is a schema object in the local database that allows you to access objects on a remote database. The remote database need not be an Oracle system. 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 statement. If you are using Oracle with the distributed option, you can also access remote tables and views using any of the following statements:
s
"DELETE" on page 7-464 "INSERT" on page 7-539 "LOCK TABLE" on page 7-547 "UPDATE" on page 7-615
s
s
s
SQL Statements
7-273
CREATE DATABASE LINK
For information about accessing remote tables or views with PL/SQL functions, procedures, packages, and datatypes, see Oracle8i Application Developer's Guide Fundamentals. For information on distributed database systems, see Oracle8i Distributed Database Systems.
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. You must have CREATE SESSION privilege on the remote Oracle database. Net8 must be installed on both the local and remote Oracle databases. To access non-Oracle systems you must use the Oracle Heterogeneous Services.
Keyword and Parameters
SHARED uses a single network connection to create a public database link that can be shared between multiple users. This clause is available only with the multi-threaded server configuration. See Also: Oracle8i Distributed Database Systems for more information about shared database links. PUBLIC dblink creates a public database link available to all users. If you omit this clause, the database link is private and is available only to you. is the complete or partial name of the database link. For guidelines for naming database links, see "Referring to Objects in Remote Databases" on page 2-79. Restrictions:
s
You cannot create a database link in another user's schema, and you cannot qualify dblink with the name of a schema. (Periods are permitted in names of database links, so 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.) The number of different database links that can appear in a single statement is limited to the value of the initialization parameter OPEN_LINKS.
s
CONNECT TO CURRENT_USER
enables a connection to the remote database. creates a current user database link. The current user must be a global user with a valid account on the remote database for the link to succeed. If the database link is used directly, that is, not from within a stored object, then the current user is the same as the connected user.
7-274 SQL Reference
CREATE DATABASE LINK
When executing a stored object (such as a procedure, view, or trigger) that initiates a database link, CURRENT_USER is the username that owns the stored object, and not the username that called the object. For example, if the database link appears inside procedure SCOTT.P (created by SCOTT), and user JANE calls procedure SCOTT.P, the current user is SCOTT. However, if the stored object is an invoker-rights function, procedure, or package, the invoker's authorization ID is used to connect as a remote user. For example, if the privileged database link appears inside procedure SCOTT.P (an invoker-rights procedure created by SCOTT), and user JANE calls procedure SCOTT.P, then CURRENT_USER is JANE and the procedure executes with JANE's privileges. See Also: "CREATE FUNCTION" on page 7-284 for more information on invokerrights functions. user IDENTIFIED BY password authenticated_ clause is the username and password used to connect to the remote database (fixed user database link). If you omit this clause, the database link uses the username and password of each user who is connected to the database (connected user database link). specifies the username and password on the target instance. This clause authenticates the user to the remote server and is required for security. The specified username and password must be a valid username and password on the remote instance. The username and password are used only for authentication. No other operations are performed on behalf of this user. You must specify this clause when using the SHARED clause. USING 'connect string' specifies the service name of a remote database. For information on specifying remote databases, see Net8 Administrator's Guide.
Examples
CURRENT_USER Example The following statement defines a current-user
database link:
CREATE DATABASE LINK sales.hq.acme.com CONNECT TO CURRENT_USER USING 'sales';
Fixed User Example The following statement defines a fixed-user database link
named SALES.HQ.ACME.COM:
CREATE DATABASE LINK sales.hq.acme.com CONNECT TO scott IDENTIFIED BY tiger USING 'sales';
Once this database link is created, you can query tables in the schema SCOTT on the remote database in this manner:
SQL Statements
7-275
CREATE DATABASE LINK
SELECT * FROM emp@sales.hq.acme.com;
You can also use DML statements 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 statement 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. The following 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;
PUBLIC Example The following statement defines a shared public fixed user
database link named SALES.HQ.ACME.COM that refers to user SCOTT with password TIGER on the database specified by the string service name 'SALES':
CREATE SHARED PUBLIC DATABASE LINK sales.hq.acme.com CONNECT TO scott IDENTIFIED BY tiger AUTHENTICATED BY anupam IDENTIFIED BY bhide USING 'sales';
7-276 SQL Reference
CREATE DIMENSION
CREATE DIMENSION
Syntax
schema CREATE DIMENSION hierarchy_clause level_clause attribute_clause ; . dimension
level_clause::=
level_table LEVEL level IS ( level_table . . level_column , level_column )
hierarchy_clause::=
join_clause HIERARCHY hierarchy ( child_level CHILD OF parent_level )
join_clause::=
child_key_column JOIN KEY ( , child_key_column ) REFERENCES parent_level
SQL Statements
7-277
CREATE DIMENSION
attribute_clause::=
dependent_column ATTRIBUTE level DETERMINES ( , dependent_column )
Purpose
To create a dimension. A dimension defines a parent-child relationship between pairs of column sets, where all the columns of a column set must come from the same table. However, columns in one column set (or "level") can come from a different table than columns in another set. The optimizer uses these relationships with materialized views to perform query rewrite. The Summary Advisor uses these relationships to recommend creation of specific materialized views.
Note: Oracle does not automatically validate the relationships you
declare when creating a dimension. To validate the relationships specified in the hierarchy_clause and the join_clause, you must run the DBMS_OLAP.VALIDATE_DIMENSION procedure. For information on this procedure, see Oracle8i Supplied PL/SQL Packages Reference.
See Also:
s
"CREATE MATERIALIZED VIEW / SNAPSHOT" on page 7-318 for more information on materialized views. Oracle8i Data Warehousing Guide for more information on query rewrite, the optimizer and the Summary Advisor.
s
Prerequisites
To create a dimension in your own schema, you must have the CREATE DIMENSION system privilege. To create a dimension in another user's schema, you must have the CREATE ANY DIMENSION system privilege. In either case, you must have the SELECT object privilege on any objects referenced in the dimension.
7-278 SQL Reference
CREATE DIMENSION
Keywords and Parameters
schema dimension level_clause is the schema in which the dimension will be created. If you do not specify schema, Oracle creates the dimension in your own schema. is the name of the dimension. The name must be unique within its schema. defines a level in the dimension. A level defines dimension hierarchies and attributes. level level_table . level_ column is the name of the level specifies from the columns in the level. You can specify up to 32 columns. The tables you specify in this clause must already exist. Restrictions:
s s
All of the columns in a level must come from the same table. If columns in different levels come from different tables, then you must specify the join_clause. The set of columns you specify must be unique to this level. The columns you specify cannot be specified in any other dimension. Each level_column must be non-null. (However, these columns need not have NOT NULL constraints.)
s s s
hierarchy_clause
defines a linear hierarchy of levels in the dimension. Each hierarchy forms a chain of parentchild relationships among the levels in the dimension. Hierarchies in a dimension are independent of each other. They may (but need not) have columns in common. Each level in the dimension should be specified at most once in this clause, and each level must already have been named in the level_clause. hierarchy child_level is the name of the hierarchy. This name must be unique in the dimension. is the name of a level that has an n:1 relationship with a parent level: the level_columns of child_level cannot be null, and each child_level value uniquely determines the value of the next named parent_level. If the child level_table is different from the parent level_table, you must specify a join relationship between them in the join_clause. parent_level is the name of a level.
SQL Statements
7-279
CREATE DIMENSION
join_clause
specifies an inner equijoin relationship for a dimension whose columns are contained in multiple tables. This clause is required and permitted only when the columns specified in the hierarchy are not all in the same table. Restrictions:
s
The child_key_columns must be non-null and the parent key must be unique and nonnull. You need not define constraints to enforce these conditions, but queries may return incorrect results if these conditions are not true. Each child key must join with a key in the parent_level table. Self-joins are not permitted (that is, the child_key_columns cannot be in the same table as parent_level). specifies one or more columns that are join-compatible with columns in the parent level. If you do not specify the schema and table of each child_column, the schema and table are inferred from the CHILD OF relationship in the hierarchy_clause. If you do specify the schema and column of a child_key_ column, the schema and table must match the schema and table of columns that comprise the child of parent_level in the hierarchy_clause. Restrictions:
s s
s s
child_key_column
All of the child-key columns must come from the same table. The number of child-key columns must match the number of columns in parent_level, and the columns must be joinable. Do not specify multiple child key columns unless the parent level consists of multiple columns.
s
You can specify only one join_clause for a given pair of levels in the same hierarchy. parent_level attribute_clause is the name of a level.
specifies the columns that are uniquely determined by a hierarchy level. The columns in level must all come from the same table as the dependent_columns. The dependent_columns need not have been specified in the level_clause. For example, if the hierarchy levels are city, state, and country, then city might determine mayor, state might determine governor, and country might determine president.
Examples
This statement creates a TIME dimension on table TIME_TAB, and creates a GEOG dimension on tables CITY, STATE, and COUNTRY.
CREATE DIMENSION time LEVEL curDate LEVEL month IS time_tab.curDate IS time_tab.month
7-280 SQL Reference
CREATE DIMENSION
LEVEL qtr IS time_tab.qtr LEVEL year IS time_tab.year LEVEL fiscal_week IS time_tab.fiscal_week LEVEL fiscal_qtr IS time_tab.fiscal_qtr LEVEL fiscal_year IS time_tab.fiscal_year HIERARCHY month_rollup ( curDate CHILD OF month CHILD OF qtr CHILD OF year) HIERARCHY fiscal_year_rollup ( curDate CHILD OF fiscal_week CHILD OF fiscal_qtr CHILD OF fiscal_year ) ATTRIBUTE curDate DETERMINES (holiday, dayOfWeek) ATTRIBUTE month DETERMINES (yr_ago_month, qtr_ago_month) ATTRIBUTE fiscal_qtr DETERMINES yr_ago_qtr ATTRIBUTE year DETERMINES yr_ago ; CREATE DIMENSION geog LEVEL cityID IS (city.city, city.state) LEVEL stateID IS state.state LEVEL countryID IS country.country HIERARCHY political_rollup ( cityID CHILD OF stateID CHILD OF countryID JOIN KEY city.state REFERENCES stateID JOIN KEY state.country REFERENCES countryID);
SQL Statements
7-281
CREATE DIRECTORY
CREATE DIRECTORY
Syntax
OR CREATE REPLACE DIRECTORY directory AS ' path_name ' ;
Purpose
To create a directory object. A directory object specifies an alias for a directory on the server's file system where external binary file LOBs (BFILEs) are located. You can use directory names when referring to BFILEs in your PL/SQL code and OCI calls, rather than hard-coding the operating system pathname, thereby allowing greater file management flexibility. All directories are created in a single namespace and are not owned by an individual's schema. You can secure access to the BFILEs stored within the directory structure by granting object privileges on the directories to specific users. When you create a directory, you are automatically granted the READ object privilege and can grant READ privileges to other users and roles. The DBA can also grant this privilege to other users and roles.
See Also:
s
"Large Object (LOB) Datatypes" on page 2-23 for more information on BFILE objects. "GRANT object_privileges" on page 7-532 for more information on granting object privileges.
s
Prerequisites
You must have CREATE ANY DIRECTORY system privileges to create directories. You must also create a corresponding operating system directory for file storage. Your system or database administrator must ensure that the operating system directory has the correct read permissions for Oracle processes. Privileges granted for the directory are created independently of the permissions defined for the operating system directory. Therefore, the two may or may not correspond exactly. For example, an error occurs if user SCOTT is granted READ
7-282 SQL Reference
CREATE DIRECTORY
privilege on the directory schema object, but the corresponding operating system directory does not have READ permission defined for Oracle processes.
Keywords and Parameters
OR REPLACE re-creates the directory database object if it already exists. You can use this clause to change the definition of an existing directory without dropping, re-creating, and regranting database object privileges previously granted on the directory. Users who had previously been granted privileges on a redefined directory can still access the directory without being regranted the privileges For information on removing a directory from the database, see "DROP DIRECTORY" on page 7-477. directory is the name of the directory object to be created. The maximum length of directory is 30 bytes. You cannot qualify a directory object with a schema name. Note: Oracle does not verify that the directory you specify actually exists. Therefore, take care that you specify a valid directory in your operating system. In addition, if your operating system uses case-sensitive pathnames, be sure you specify the directory in the correct format. (However, you need not include a trailing slash at the end of the pathname.) 'path_name' is the full pathname of the operating system directory on the server where the files are located. The single quotes are required, with the result that the path name is case sensitive.
Example
The following statement redefines directory database object BFILE_DIR to enable access to BFILEs stored in the operating system directory /PRIVATE1/LOB/ FILES:
CREATE OR REPLACE DIRECTORY bfile_dir AS '/private1/LOB/files';
SQL Statements
7-283
CREATE FUNCTION
CREATE FUNCTION
Syntax
OR CREATE REPLACE FUNCTION , IN OUT IN ( argument OUT NOCOPY datatype ) schema . function
invoker_rights_clause DETERMINISTIC PARALLEL_ENABLE RETURN datatype AS call_spec IS pl/sql_function_body ;
invoker_rights_clause::=
CURRENT_USER AUTHID DEFINER
call_spec::=
Java_declaration LANGUAGE C_declaration
Java_declaration::=
JAVA NAME ' string '
7-284 SQL Reference
CREATE FUNCTION
C_declaration::=
NAME C PARAMETERS ( name LIBRARY parameters ) lib_name WITH CONTEXT
Purpose
To create a stored function or a call specification. A stored function (also called a user function) is a set of 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. User functions can be used as part of a SQL expression. For a general discussion of procedures and functions, see "CREATE PROCEDURE" on page 7-353. For examples of creating functions, see "Examples" on page 7-289. A call specification declares a Java method or a third-generation language (3GL) routine so that it can be called from SQL and PL/SQL. The call specification tells Oracle which Java method, or which named function in which shared library, to invoke when a call is made. It also tells Oracle what type conversions to make for the arguments and return value. The CREATE FUNCTION statement creates a function as a standalone schema object. You can also create a function as part of a package. For information on creating packages, see "CREATE PACKAGE" on page 7-344. For information on modifying a function, see "ALTER FUNCTION" on page 7-28. For information on shared libraries, see "CREATE LIBRARY" on page 7-316. For information on dropping a standalone function, see "DROP FUNCTION" on page 7-478.
See Also: Oracle8i Application Developer's Guide - Fundamentals for more information about registering external functions.
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 depend on your operating system. To create a function in your own schema, you must have the CREATE PROCEDURE system privilege. To create a function in another user's schema, you must have the
SQL Statements
7-285
CREATE FUNCTION
CREATE ANY PROCEDURE system privilege. To replace a function in another user's schema, you must have the ALTER ANY PROCEDURE system privilege. To invoke a call specification, you may need additional privileges (for example, EXECUTE privileges on C library for a C call specification). 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.
See Also: PL/SQL User's Guide and Reference or Oracle8i Java Stored
Procedures Developer's Guide for more information on such prerequisites.
Keywords and Parameters
OR REPLACE re-creates the function if it already exists. Use this clause to change the definition of an existing function without dropping, re-creating, and regranting object privileges previously granted on the function. If you redefine a function, Oracle recompiles it. For information on recompiling functions, see "ALTER FUNCTION" on page 7-28. Users who had previously been granted privileges on a redefined function can still access the function without being regranted the privileges. If any function-based indexes depend on the function, Oracle marks the indexes DISABLED. schema function is the schema to contain the function. If you omit schema, Oracle creates the function in your current schema. is the name of the function to be created. If creating the function results in compilation errors, Oracle returns an error. You can see the associated compiler error messages with the SHOW ERRORS command. Restrictions on User-Defined Functions User-defined functions cannot be used in situations that require an unchanging definition. Thus, you cannot use user-defined functions:
s s
In a CHECK constraint clause of a CREATE TABLE or ALTER TABLE statement In a DEFAULT clause of a CREATE TABLE or ALTER TABLE statement
7-286 SQL Reference
CREATE FUNCTION
In addition, when a function is called from within a query or DML statement, the function cannot:
s s
Have OUT or IN OUT parameters Commit or roll back the current transaction, create or roll back to a savepoint, or alter the session or the system. DDL statements implicitly commit the current transaction, so a user-defined function cannot execute any DDL statements. Write to the database, if the function is being called from a SELECT statement. However, a function called from a subquery in a DML statement can write to the database. Write to the same table that is being modified by the statement from which the function is called, if the function is called from a DML statement.
s
s
Except for the restriction on OUT and IN OUT parameters, Oracle enforces these restrictions not only for the function called directly from the SQL statement, but also for any functions that function calls, and on any functions called from the SQL statements executed by that function or any function it calls. argument IN OUT IN OUT NOCOPY 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. specifies that you must supply a value for the argument when calling the function. This is the default. specifies the function will set the value of the argument. specifies that a value for the argument can be supplied by you and may be set by the function. instructs Oracle to pass this argument as fast as possible. This clause can significantly enhance performance when passing a large value like a record, an index-by table, or a varray to an OUT or IN OUT parameter. (IN parameter values are always passed NOCOPY.)
s
When you specify NOCOPY, assignments made to a package variable may show immediately in this parameter (or assignments made to this parameter may show immediately in a package variable) if the package variable is passed as the actual assignment corresponding to this parameter. Similarly, changes made either to this parameter or to another parameter may be visible immediately through both names if the same variable is passed to both. If the function is exited with an unhandled exception, any assignment made to this parameter may be visible in the caller's variable.
s
s
These effects may or may not occur on any particular call. You should use NOCOPY only when these effects would not matter. 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.
SQL Statements
7-287
CREATE FUNCTION
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 PL/SQL User's Guide and Reference.
invoker_rights_ clause
lets you specify whether the function executes with the privileges and in the schema of the user who owns it or with the privileges and in the schema of CURRENT_USER. For information on how CURRENT_USER is determined, see Oracle8i Concepts and Oracle8i Application Developer's Guide - Fundamentals. This clause also determines how Oracle resolves external names in queries, DML operations, and dynamic SQL statements in the function. See Also: PL/SQL User's Guide and Reference. AUTHID CURRENT_USER specifies that the function executes with the privileges of CURRENT_ USER. This clause creates an "invoker-rights function." This clause also specifies that external names in queries, DML operations, and dynamic SQL statements resolve in the schema of CURRENT_USER. External names in all other statements resolve in the schema in which the function resides. AUTHID DEFINER specifies that the function executes with the privileges of the owner of the schema in which the function resides, and that external names resolve in the schema where the function resides. This is the default.
DETERMINISTIC is an optimization hint that allows the system to use a saved copy of the function's return result (if such a copy is available). The saved copy could come from a materialized view, a function-based index, or a redundant call to the same function in the same SQL statement. The query optimizer can choose whether to use the saved copy or re-call the function. The function should reliably return the same result value whenever it is called with the same values for its arguments. Therefore, do not define the function to use package variables or to access the database in any way that might affect the function's return result, because the results of doing so will not be captured if the system chooses not to call the function. A function must be declared DETERMINISTIC in order to be called in the expression of a function-based index, or from the query of a materialized view if that view is marked REFRESH FAST or ENABLE QUERY REWRITE. For information on materialized views, see Oracle8i Data Warehousing Guide. For information on function-based indexes, see "CREATE INDEX" on page 7-291. PARALLEL_ ENABLE is an optimization hint indicating that the function can be executed from a parallel execution server of a parallel query operation. The function should not use session state, such as package variables, as those variables may not be shared among the parallel execution servers. See Also: Oracle8i Application Developer's Guide - Fundamentals.
7-288 SQL Reference
CREATE FUNCTION
pl/sql_ subprogram_body
declares the function in a PL/SQL subprogram body. See Also: Oracle8i Application Developer's Guide - Fundamentals for more information on PL/ SQL subprograms. maps a Java or C method name, parameter types, and return type to their SQL counterparts. In Java_declaration, 'string' identifies the Java implementation of the method. See Also:
s s
call_spec
Oracle8i Java Stored Procedures Developer's Guide. Oracle8i Application Developer's Guide - Fundamentals for an explanation of the parameters and semantics of the C_declaration. is an alternative way of declaring a C method. This clause has been deprecated and is supported for backward compatibility only. Oracle Corporation recommends that you use the AS LANGUAGE C syntax.
AS EXTERNAL
Examples
The following 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. The function created above can be used in a SQL statement. For example:
SELECT get_bal(100) FROM DUAL;
SQL Statements
7-289
CREATE FUNCTION
The following statement creates PL/SQL standalone function GET_VAL that registers the C routine C_GET_VAL as an external function. (The parameters have been omitted from this example.)
CREATE FUNCTION get_val ( x_val IN NUMBER, y_val IN NUMBER, image IN LONG RAW ) RETURN BINARY_INTEGER AS LANGUAGE C NAME "c_get_val" LIBRARY c_utils PARAMETERS (...);
7-290 SQL Reference
CREATE INDEX
CREATE INDEX
Syntax
UNIQUE BITMAP CREATE INDEX schema . index ON table_index_clause cluster_index_clause ;
cluster_index_clause::=
schema CLUSTER . cluster index_attributes
table_index_clause::=
, ASC schema . table global_index_clause local_index_clause index_attributes domain_index_clause t_alias ( index_expr_list DESC )
index_expr_list::=
column column_expression
SQL Statements
7-291
CREATE INDEX
index_attributes::=
physical_attributes_clause LOGGING NOLOGGING ONLINE COMPUTE STATISTICS tablespace TABLESPACE DEFAULT COMPRESS NOCOMPRESS NOSORT REVERSE parallel_clause integer
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
domain_index_clause::=
PARAMETERS INDEXTYPE IS indextype ( ' string ' )
7-292 SQL Reference
CREATE INDEX
global_index_clause::=
, GLOBAL PARTITION BY RANGE ( column_list ) ( global_partition_clause )
global_partition_clause::=
partition PARTITION physical_attributes_clause TABLESPACE LOGGING NOLOGGING VALUES LESS THAN ( value_list ) tablespace
local_index_clauses::=
on_range_partitioned_table_clause on_hash_partitioned_table_clause on_composite_partitioned_table_clause LOCAL
on_range_partitioned_table_clause::=
, segment_attributes_clause partition ( PARTITION )
SQL Statements
7-293
CREATE INDEX
segment_attributes_clause::=
physical_attributes_clause TABLESPACE LOGGING NOLOGGING tablespace
on_hash_partitioned_table_clause::=
, tablespace STORE IN ( DEFAULT , TABLESPACE partition ( PARTITION ) tablespace )
on_composite_partitioned_table_clause::=
, tablespace STORE IN ( DEFAULT , segment_attribute_clause partition ( PARTITION ) index_subpartition_clause )
7-294 SQL Reference
CREATE INDEX
index_subpartition_clause::=
, tablespace STORE IN ( DEFAULT , TABLESPACE subpartition ( SUBPARTITION ) tablespace )
parallel_clause::=
NOPARALLEL integer PARALLEL
storage_clause: See "storage_clause" on page 7-605.
Purpose
To create an index on
s
One or more columns of a table, a partitioned table, an index-organized table, or a cluster One or more scalar typed object attributes of a table or a cluster A nested table storage table for indexing a nested table column
s
s
To create a domain index, which is an instance of an application-specific index of type indextype. An index is a schema 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. A partitioned index consists of partitions containing an entry for each value that appears in the indexed column(s) of the table. A function-based index is an index on expressions. It enables you to construct queries that evaluate the value returned by an expression, which in turn may include functions (built-in or user-defined).
SQL Statements
7-295
CREATE INDEX
For a discussion of indexes, see Oracle8i Concepts. For information on modifying an index, see "ALTER INDEX" on page 7-30.
Prerequisites
To create an index in your own schema, one of the following conditions must be true:
s
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.
s
s
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 tablespaces to contain the index or index partitions, or UNLIMITED TABLESPACE system privilege. To create a domain index in your own schema, you must also have EXECUTE privilege on the indextype. If you are creating a domain index in another user's schema, the index owner also must have EXECUTE privilege on the indextype and its underlying implementation type. Before creating a domain index, you should first define the indextype. See "CREATE INDEXTYPE" on page 7-309. To create a function-based index in your own schema on your own table, you must have the QUERY REWRITE system privilege. To create the index in another schema or on another schema's table, you must have the GLOBAL QUERY REWRITE privilege. The table owner must also have the EXECUTE object privilege on the function(s) used in the function-based index.
Keywords and Parameters
UNIQUE specifies that the value of the column (or columns) upon which the index is based must be unique. If the index is local nonprefixed (see local_index_clause below), then the index key must contain the partitioning key. Oracle recommends that you do not explicitly define UNIQUE indexes on tables. Uniqueness is strictly a logical concept and should be associated with the definition of a table. Therefore, define UNIQUE integrity constraints on the desired columns. See Also: The "constraint_clause" on page 7-233. Restrictions:
s s
You cannot specify both UNIQUE and BITMAP. You cannot specify UNIQUE for a domain index.
7-296 SQL Reference
CREATE INDEX
BITMAP
specifies that index is to be created as a bitmap, rather than as a B-tree. Bitmap indexes store the rowids associated with a key value as a bitmap. Each bit in the bitmap corresponds to a possible rowid, and if the bit is set, it means that the row with the corresponding rowid contains the key value. The internal representation of bitmaps is best suited for applications with low levels of concurrent transactions, such as data warehousing. See Oracle8i Concepts and Oracle8i Designing and Tuning for Performance for more information about using bitmap indexes. Restrictions:
s
You cannot specify BITMAP when creating a global partitioned index or an indexorganized table. You cannot specify both UNIQUE and BITMAP. You cannot specify BITMAP for a domain index.
s s
schema index cluster_index_ clause
is the schema to contain the index. If you omit schema, Oracle creates the index in your own schema. is the name of the index to be created. An index can contain several partitions. 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 in your current schema. You cannot create a cluster index for a hash cluster. See Also: "CREATE CLUSTER" on page 7-254.
table_index_ clause
specifies table (and its attributes) on which you are defining the index. If you do not qualify table with schema, Oracle assumes the table is contained in your own schema. You create an index on a nested table column by creating the index on the nested table storage table. Include the NESTED_TABLE_ID pseudocolumn of the storage table to create a UNIQUE index, which effectively ensures that the rows of a nested table value are distinct. Restrictions:
s s
If the index is local, then table must be partitioned. If the table is index-organized, this statement creates a secondary index. You cannot specify BITMAP or REVERSE for this secondary index, and the combined size of the index key and the logical rowid should be less than half the block size. If table is a temporary table, the index will also be temporary with the same scope (session or transaction) as table. The following restrictions apply to indexes on temporary table: - The index cannot be a partitioned index or a domain index. - You cannot specify the physical_attributes_clause or the parallel_clause. - You cannot specify LOGGING, NOLOGGING, or TABLESPACE.
s
See Also: "CREATE TABLE" on page 4-381 and Oracle8i Concepts for more information on temporary tables.
SQL Statements
7-297
CREATE INDEX
t_alias
specifies a correlation name (alias) for the table upon which you are building the index. Note: This alias is required if the index_expression_list references any object type attributes or object type methods. See "Function-based Index on Type Method Example" on page 7-306.
index_expr_list column
lets you specify the column or column expression upon which the index is based. is the name of a column in the table. A bitmap index can have a maximum of 30 columns. Other indexes can have as many as 32 columns. Restriction: You cannot create an index on columns or attributes whose type is user-defined, LONG, LONG RAW, LOB, or REF, except that Oracle supports an index on REF type columns or attributes that have been defined with a SCOPE clause. You can create an index on a scalar object attribute column or on the system-defined NESTED_TABLE_ID column of the nested table storage table. If you specify an object attribute column, the column name must be qualified with the table name. If you specify a nested table column attribute, it must be qualified with the outermost table name, the containing column name, and all intermediate attribute names leading to the nested table column attribute.
column_expression is an expression built from columns of table, constants, SQL functions, and user-defined functions. When you specify column_expression, you create a function-based index. Name resolution of the function is based on the schema of the index creator. User-defined functions used in column_expression are fully name resolved during the CREATE INDEX operation. After creating a function-based index, collect statistics on both the index and its base table using the ANALYZE statement (see "ANALYZE" on page 7-200). Oracle cannot use the function-based index until these statistics have been generated. Notes on function-based indexes:
s
When you subsequently query a table that uses a function-based index, you must ensure in the query that column_expression is not null. However, Oracle will use a function-based index in a query even if the columns specified in the WHERE clause are in a different order than their order in the column_expression that defined the function-based index. See Also: The Function-Based Index Example on page 7-305.
s
If the function on which the index is based becomes invalid or is dropped, Oracle marks the index DISABLED. Queries on a DISABLED index fail if the optimizer chooses to use the index. DML operations on a DISABLED index fail unless the index is also marked UNUSABLE and the parameter SKIP_UNUSABLE_INDEXES is set to true. See Also: "ALTER SESSION" on page 7-83 for more information on this parameter).
s
Oracle's use of function-based indexes is also affected by the setting of the QUERY_ REWRITE_ENABLED session parameter. See Also: "ALTER SESSION" on page 7-83.
7-298 SQL Reference
CREATE INDEX
s
If a public synonym for a function, package, or type is used in column_expression, and later an actual object with the same name is created in the table owner's schema, then Oracle will disable the function-based index. When you subsequently enable the function-based index using ALTER INDEX ... ENABLE or ALTER INDEX ... REBUILD, the function, package, or type used in the column_expression will continue to resolve to the function, package, or type to which the public synonym originally pointed. It will not resolve to the new function, package, or type. If the definition of a function-based index generates internal conversion to character data, use caution when changing NLS parameter settings. Function-based indexes use the current database settings for NLS parameters. If you reset these parameters at the session level, queries using the function-based index may return incorrect results. Two exceptions are the collation parameters (NLS_SORT and NLS_COMP). Oracle handles the conversions correctly even if these have been reset at the session level.
s
Restrictions on function-based indexes:
s s
Any user-defined function referenced in column_expression must be DETERMINISTIC. For a function-based globally partitioned index, the column_expression cannot be the partitioning key. All functions must be specified with parentheses, even if they have no parameters. Otherwise Oracle interprets them as column names. Any function you specify in column_expression must return a repeatable value. For example, you cannot specify the SYSDATE or USER function or the ROWNUM pseudocolumn. You cannot build a function-based index on LOB, REF, nested table, or varray columns. In addition, the function in column_expression cannot take as arguments any objects with attributes of type LOB, REF, nested table, or varray. The column_expression cannot contain any aggregate functions.
s
s
s
s
See Also: "CREATE FUNCTION" on page 7-284 and PL/SQL User's Guide and Reference. ASC | DESC specifies whether the index should be created in ascending or descending order. Indexes on character data are created in ascending or descending order of the character values in the database character set. Oracle treats descending indexes as if they were function-based indexes. You do not need the QUERY REWRITE or GLOBAL QUERY REWRITE privileges to create them, as you do with other function-based indexes. However, as with other function-based indexes, Oracle does not use descending indexes until you first analyze the index and the table on which the index is defined. See the column_expression clause of this statement. Restriction: You cannot specify either of these clauses for a domain index. You cannot specify DESC for a reverse index. Oracle ignores DESC if index is bitmapped or if the COMPATIBLE initialization parameter is set to a value less than 8.1.
SQL Statements
7-299
CREATE INDEX
index_attributes physical_ establishes values for physical and storage characteristics for the index. See "CREATE attributes_clause TABLE" on page 4-381. Restriction: You cannot specify the PCTUSED parameter for an index. PCTFREE storage_clause TABLESPACE is the percentage of space to leave free for updates and insertions within each of the index's data blocks. establishes the storage characteristics for the index. See the "storage_ clause" on page 7-605.
is the name of the tablespace to hold the index, index partition, or index subpartition. If you omit this clause, Oracle creates the index in the default tablespace of the owner of the schema containing the index. For a local index, you can specify the keyword DEFAULT in place of tablespace. New partitions or subpartitions added to the local index will be created in the same tablespace(s) as the corresponding partitions or subpartitions of the underlying table.
COMPRESS
enables key compression, which eliminates repeated occurrence of key column values and may substantially reduce storage. Use integer to specify the prefix length (number of prefix columns to compress).
s
For unique indexes, the valid range of prefix length values is from 1 to the number of key columns minus 1. The default prefix length is the number of key columns minus 1. For nonunique indexes, the valid range of prefix length values is from 1 to the number of key columns. The default prefix length is the number of key columns.
s
Oracle compresses only nonpartitioned indexes that are nonunique or unique indexes of at least two columns. Restriction: You cannot specify COMPRESS for a bitmapped index. NOCOMPRESS NOSORT disables key compression. This is the default. indicates to Oracle that the rows are stored in the database in ascending order, so that Oracle does not have to sort the rows when creating the index. If the rows of the indexed column or columns are not stored in ascending order, Oracle returns an error. For greatest savings of sort time and space, use this clause immediately after the initial load of rows into a table. Restrictions:
s s s
You cannot specify REVERSE with this clause. You cannot use this clause to create a cluster, partitioned, or bitmap index. You cannot specify this clause for a secondary index on an index-organized table.
REVERSE
stores the bytes of the index block in reverse order, excluding the rowid. You cannot specify NOSORT with this clause. You cannot reverse a bitmap index or an index-organized table.
7-300 SQL Reference
CREATE INDEX
LOGGING | NOLOGGING
specifies that the creation of the index will be logged (LOGGING) or not logged (NOLOGGING) in the redo log file. It also specifies that subsequent Direct Loader (SQL*Loader) and directload INSERT operations against the index are logged or not logged. LOGGING is the default. If index is nonpartitioned, this is the logging attribute of the index. If index is partitioned, the logging attribute specified is
s
The default value of all partitions specified in the CREATE statement (unless you specify LOGGING|NOLOGGING in the PARTITION description clause) The default value for the segments associated with the index partitions The default value for local index partitions or subpartitions added implicitly during subsequent ALTER TABLE ... ADD PARTITION operations
s s
In NOLOGGING mode, data is modified with minimal logging (to mark new extents INVALID and to record dictionary changes). When applied during media recovery, the extent invalidation records mark a range of blocks as logically corrupt, since the redo data is not logged. Thus if you cannot afford to lose this index, it is important to take a backup after the NOLOGGING operation. If the database is run in ARCHIVELOG mode, media recovery from a backup taken before the LOGGING operation will re-create the index. However, media recovery from a backup taken before the NOLOGGING operation will not re-create the index. The logging attribute of the index is independent of that of its base table. If you omit this clause, the logging attribute is that of the tablespace in which it resides. See Also: Oracle8i Concepts and Oracle8i Parallel Server Concepts for more information about logging and parallel DML. ONLINE specifies that DML operations on the table will be allowed during creation of the index. For a description of online index building and rebuilding, see Oracle8i Concepts. Restriction: Parallel DML is not supported during online index building. If you specify ONLINE and then issue parallel DML statements, Oracle returns an error. COMPUTE STATISTICS enables you to collect statistics at relatively little cost during the creation of an index. These statistics are stored in the data dictionary for ongoing use by the optimizer in choosing a plan of execution for SQL statements. The types of statistics collected depend on the type of index you are creating. Note: If you create an index using another index (instead of a table), the original index might not provide adequate statistical information. Therefore, Oracle generally uses the base table to compute the statistics, which will improve the statistics but may negatively affect performance. Additional methods of collecting statistics are available in PL/SQL packages and procedures. See Also: Oracle8i Supplied PL/SQL Packages Reference.
SQL Statements
7-301
CREATE INDEX
global_index_ clause
specifies that the partitioning of the index is user defined and is not equipartitioned with the underlying table. By default, nonpartitioned indexes are global indexes. PARTITION BY RANGE (column_list) specifies that the global index is partitioned on the ranges of values from the columns specified in column_list. You cannot specify this clause for a local index. is the name of the column(s) of a table on which the index is partitioned. The column_list must specify a left prefix of the index column list. You cannot specify more than 32 columns in column_list, and the columns cannot contain the ROWID pseudocolumn or a column of type ROWID. Note: If your enterprise has or will have databases using different character sets, use caution when partitioning on character columns. The sort sequence of characters is not identical in all character sets. See Also: Oracle8i National Language Support Guide for more information on character set support. PARTITION partition VALUES LESS THAN (value_list) describes the individual partitions. The number of clauses determines the number of partitions. If you omit partition, Oracle generates a name with the form SYS_Pn. specifies the (noninclusive) upper bound for the current partition in a global index. The value_list is a comma-separated, ordered list of literal values corresponding to column_list in the partition_by_range_clause. Always specify MAXVALUE as the value_list of the last partition. Note: If index is partitioned on a DATE column, and if the NLS date format does not specify the century with the year, you must use the TO_ DATE function with a 4-character format mask for the year. The NLS date format is determined implicitly by NLS_TERRITORY or explicitly by NLS_DATE_FORMAT. See Also:
s
Oracle8i National Language Support Guide for more information on these initialization parameters. The "Partitioned Table Example" on page 4-414.
s
Restriction: You cannot specify this clause for a local index. local_index_ clauses specify that the index is partitioned on the same columns, with the same number of partitions and the same partition bounds as table. Oracle automatically maintains LOCAL index partitioning as the underlying table is repartitioned. on_range_ partitioned_table_ clause describes an index on a range-partitioned table.
7-302 SQL Reference
CREATE INDEX
PARTITION partition
describes the individual partitions. The number of clauses determines the number of partitions. For a local index, the number of index partitions must be equal to the number of the table partitions, and in the same order. If you omit partition, Oracle generates a name that is consistent with the corresponding table partition. If the name conflicts with an existing index partition name, the form SYS_Pn is used.
on_hash_ partitioned_table_ clause
describes an index on a hash-partitioned table. If you do not specify partition, Oracle uses the name of the corresponding base table partition, unless it conflicts with an explicitly specified name of another index partition. In this case, Oracle generates a name of the form SYS_Pnnn. You can optionally specify TABLESPACE for all index partitions or for one or more individual partitions. If you do not specify TABLESPACE at the index or partition level, Oracle stores each index partition in the same tablespace as the corresponding table partition.
on_composite_ partitioned_table_ clause
describes an index on a composite-partitioned table. The first STORE IN clause specifies the default tablespace for the index subpartitions. You can override this storage by specifying a different tablespace in the index_ subpartitioning_clause. If you do not specify TABLESPACE for subpartitions either in this clause or in the index_subpartitioning_clause, Oracle uses the tablespace specified for index. If you also do not specify TABLESPACE for index, Oracle stores the subpartition in the same tablespace as the corresponding table subpartition.
STORE IN
lets you specify how index hash partitions (for a hash-partitioned index) or index subpartitions (for a composite-partitioned index) are to be distributed across various tablespaces. The number of tablespaces does not have to equal the number of index partitions. If the number of index partitions is greater than the number of tablespaces, Oracle cycles through the names of the tablespaces. is valid only for a local index on a hash or composite-partitioned table. This clause overrides any tablespace specified at the index level for a partition or subpartition, and stores the index partition or subpartition in the same partition as the corresponding table partition or subpartition.
DEFAULT
index_ specifies one or more tablespaces in which to store all subpartitions in subpartition_clause partition or one or more individual subpartitions in partition. The subpartition inherits all other attributes from partition. Attributes not specified for partition are inherited from index.
SQL Statements
7-303
CREATE INDEX
domain_index_ clause
specifies that index is a domain index. Restrictions:
s s s s s
The index_expr_list can specify only a single column. You can define only one domain index on a column. You cannot specify a BITMAP, UNIQUE, or function-based domain index. You cannot create a local domain index on a partitioned table. You cannot create a domain index on a partitioned table with row movement enabled. specifies the table columns or object attributes on which the index is defined. Each column can have only one domain index defined on it. Restrictions:
s
column
You cannot create a domain index on a column of datatype REF, varray, nested table, LONG, or LONG RAW. You can create a domain index on a column of user-defined type, but not on an attribute of a column of user-defined type if that attribute itself is a user-defined type.
s
indextype
specifies the name of the indextype. This name should be a valid schema object that you have already defined. See "CREATE INDEXTYPE" on page 7-309. specifies the parameter string that is passed uninterpreted to the appropriate indextype routine. The maximum length of the parameter string is 1000 characters. Once the domain index is created, Oracle invokes this routine (see Oracle8i Data Cartridge Developer's Guide for information on these routines.) If the routine does not return successfully, the domain index is marked FAILED. The only operation supported on an failed domain index is DROP INDEX.
PARAMETERS 'string'
parallel_clause
causes creation of the index to be parallelized. For additional information, see the Notes to the parallel_clause of "CREATE TABLE" on page 4-381. NOPARALLEL PARALLEL specifies serial execution. This is the default. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances times the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution servers. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer.
7-304 SQL Reference
CREATE INDEX
Examples
PARALLEL Example The following statement creates an index using 10 parallel execution servers, 5 to scan SCOTT.EMP and another 5 to populate the EMP_IDX index:
CREATE INDEX emp_idx ON scott.emp (ename) PARALLEL 5;
COMPRESS Example To create an index with the COMPRESS clause, you might issue the following statement:
CREATE INDEX emp_idx2 ON emp(job, ename) COMPRESS 1;
The index will compress repeated occurrences of JOB column values.
NOLOGGING Example To quickly create an index in parallel on a table that was
created using a fast parallel load (so all rows are already sorted), you might issue the following statement. (Oracle will choose the appropriate degree of parallelism.)
CREATE INDEX i_loc ON big_table (akey) NOSORT NOLOGGING PARALLEL;
Cluster Index Example To create an index for the EMPLOYEE cluster, issue the
following statement:
CREATE INDEX ic_emp ON CLUSTER employee;
No index columns are specified, because the index is automatically built on all the columns of the cluster key. For cluster indexes, all rows are indexed.
NULL Example Consider the following statement:
SELECT ename FROM emp WHERE comm IS NULL;
The above query does not use an index created on the COMM column unless it is a bitmap index. The following statements creates a function-based index on the EMP table based on an uppercase evaluation of the ENAME column:
Function-Based Index Example
SQL Statements
7-305
CREATE INDEX
CREATE INDEX emp_i ON emp (UPPER(ename));
To ensure that Oracle will use the index rather than performing a full table scan, be sure that the value of the function is not null in subsequent queries. For example, the statement
SELECT * FROM emp WHERE UPPER(ename) IS NOT NULL ORDER BY UPPER(ename);
is guaranteed to use the index, but without the WHERE clause, Oracle may perform a full table scan. In the next statements showing index creation and subsequent query, Oracle will use index EMP_FI even though the columns are in reverse order in the query:
CREATE INDEX emp_fi ON emp(cola + colb); SELECT * FROM emp WHERE colb + cola > 500;
Function-based Index on Type Method Example This example entails an object
type RECTANGLE containing two number attributes: length and width. The AREA() method computes the area of the rectangle.
CREATE TYPE rectangle AS OBJECT ( length NUMBER, width NUMBER, MEMBER FUNCTION area RETURN NUMBER DETERMINISTIC ); CREATE OR REPLACE TYPE BODY rectangle AS MEMBER FUNCTION area RETURN NUMBER IS BEGIN RETURN (length*width); END; END;
Now, if you create a table RECTAB of type RECTANGLE, you can create a functionbased index on the AREA() method as follows:
CREATE TABLE recttab OF rectangle; CREATE INDEX area_idx ON recttab x (x.area());
You can use this index efficiently to evaluate a query of the form:
SELECT * FROM recttab x WHERE x.area() > 100;
7-306 SQL Reference
CREATE INDEX
Computing Statistics Example The following statement collects statistics on the nonpartitioned EMP_INDX index:
CREATE INDEX emp_indx ON emp(empno) COMPUTE STATISTICS;
The type of statistics collected depends on the type of index you are creating.
See Also: Oracle8i Concepts. Partitioned Index Example The following statement creates a global prefixed
index STOCK_IX on table STOCK_XACTIONS with two partitions, one for each half of the alphabet. The index partition names are system generated:
CREATE INDEX stock_ix ON stock_xactions (stock_symbol, stock_series) GLOBAL PARTITION BY RANGE (stock_symbol) (PARTITION VALUES LESS THAN ('N') TABLESPACE ts3, PARTITION VALUES LESS THAN (MAXVALUE) TABLESPACE ts4);
Index on Hash-Partitioned Table Example. This statement creates a local index on
the ITEM column of the SALES table. The STORE IN clause immediately following LOCAL indicates that SALES is hash partitioned. Oracle will distribute the hash partitions between the TBS1 and TBS2 tablespaces:
CREATE INDEX sales_idx ON sales(item) LOCAL STORE IN (tbs1, tbs2);
Index on Composite-Partitioned Table Example. This statement creates a local index on the SALES table, which is composite-partitioned. The STORAGE clause specifies default storage attributes for the index. The STORE IN clause specifies one or more default tablespaces for the index subpartitions. However, this default is overridden for the four subpartitions of partition Q3_1997, because separate TABLESPACE is specified.
CREATE INDEX sales_idx ON sales(sale_date, item) STORAGE (INITIAL 1M, MAXEXTENTS UNLIMITED) LOCAL STORE IN (tbs1, tbs2, tbs3, tbs4, tbs5) (PARTITION q1_1997, PARTITION q2_1997, PARTITION q3_1997 (SUBPARTITION q3_1997_s1 TABLESPACE ts2, SUBPARTITION q3_1997_s2 TABLESPACE ts4, SUBPARTITION q3_1997_s3 TABLESPACE ts6, SUBPARTITION q3_1997_s4 TABLESPACE ts8), PARTITION q4_1997,
SQL Statements
7-307
CREATE INDEX
PARTITION q1_1998);
Bitmap Index Example To create a bitmap partitioned index on a table with four partitions, issue the following statement:
CREATE BITMAP INDEX partno_ix ON lineitem(partno) TABLESPACE ts1 LOCAL (PARTITION quarter1 TABLESPACE ts2, PARTITION quarter2 STORAGE (INITIAL 10K NEXT 2K), PARTITION quarter3 TABLESPACE ts2, PARTITION quarter4);
Nested Table Example In the following example, UNIQUE index UNIQ_PROJ_ INDX is created on storage table NESTED_PROJECT_TABLE. Including pseudocolumn NESTED_TABLE_ID ensures distinct rows in nested table column PROJS_MANAGED:
CREATE TYPE proj_type AS OBJECT (proj_num NUMBER, proj_name VARCHAR2(20)); CREATE TYPE proj_table_type AS TABLE OF proj_type; CREATE TABLE employee ( emp_num NUMBER, emp_name CHAR(31), projs_managed proj_table_type ) NESTED TABLE projs_managed STORE AS nested_project_table; CREATE UNIQUE INDEX uniq_proj_indx ON nested_project_table ( NESTED_TABLE_ID, proj_num);
7-308 SQL Reference
CREATE INDEXTYPE
CREATE INDEXTYPE
Syntax
schema CREATE INDEXTYPE , schema FOR schema USING . implementation_type ; . operator ( , paramater_type ) . indextype
Purpose
To create an indextype, which is an object that specifies the routines that manage a domain (application-specific) index. Indextypes reside in the same namespace as tables, views, and other schema objects. This statement binds the indextype name to an implementation type, which in turn specifies and refers to user-defined index functions and procedures that implement the indextype.
See Also: Oracle8i Data Cartridge Developer's Guide and Oracle8i
Concepts for more information on implementing indextypes.
Prerequisites
To create an indextype in your own schema, you must have the CREATE INDEXTYPE system privilege. To create an indextype in another schema, you must have CREATE ANY INDEXTYPE system privilege. In either case, you must have the EXECUTE object privilege on the implementation type and the supported operators. An indextype supports one or more operators, so before creating an indextype, you should first design the operator or operators to be supported and provide functional implementation for those operators.
SQL Statements
7-309
CREATE INDEXTYPE
See Also: "CREATE OPERATOR" on page 7-339.
Keywords and Parameters
schema indextype FOR is the name of the schema in which the indextype resides. If you omit schema, Oracle creates the indextype in your own schema. is the name of the indextype to be created. specifies the list of operators supported by the indextype. schema operator parameter_type is the schema containing the operator. If you omit schema, Oracle assumes the operator is in your own schema. specifies the name of the operator supported by the indextype. lists the types of parameters to the operator.
All the operators listed in this clause should be valid operators. USING specifies the type that provides the implementation for the new indextype. implementation_ type is the name of the type that implements the appropriate Oracle Data Cartridge interface (ODCI).
s
You must specify a valid type that implements the routines in the ODCI interface. The implementation type must reside in the same schema as the indextype.
s
For additional information on this interface, see Oracle8i Data Cartridge Developer's Guide.
Example
The following statement creates an indextype named TextIndexType and specifies the CONTAINS operator that is supported by the indextype and the TextIndexMethods type that implements the index interface:
CREATE INDEXTYPE TextIndexType FOR contains (VARCHAR2, VARCHAR2) USING TextIndexMethods;
7-310 SQL Reference
CREATE JAVA
CREATE JAVA
Syntax
RESOLVE AND OR CREATE REPLACE COMPILE NOFORCE
SOURCE NAMED RESOURCE JAVA SCHEMA CLASS schema
schema
. primary_name
, RESOLVER invoker_rights_clause ( ( match_string
schema_name ) )
BFILE CLOB USING BLOB BFILE
(
directory_object_name
,
server_file_name
)
subquery
; ' AS source_text key_for_BLOB '
invoker_rights_clause::=
CURRENT_USER AUTHID DEFINER
SQL Statements
7-311
CREATE JAVA
Purpose
To create a schema object containing a Java source, class, or resource. For information on the following topics, see these books:
s
For Java concepts, see Oracle8i Java Developer's Guide. For Java stored procedures, see Oracle8i Java Stored Procedures Developer's Guide For SQLJ, see Oracle8i SQLJ Developer's Guide and Reference. For JDBC, see Oracle8i JDBC Developer's Guide and Reference. For CORBA and EJB, see Oracle8i Enterprise JavaBeans and CORBA Developer's Guide.
s
s
s
s
Prerequisites
To create or replace a schema object containing a Java source, class, or resource in your own schema, you must have CREATE PROCEDURE system privilege. To create such a schema object in another user's schema, you must have CREATE ANY PROCEDURE system privilege. To replace such a schema object in another user's schema, you must also have ALTER ANY PROCEDURE system privilege.
Keywords and Parameters
OR REPLACE re-creates the schema object containing the Java class, source, or resource if it already exists. Use this clause to change the definition of an existing object without dropping, recreating, and regranting object privileges previously granted. If you redefine a Java schema object and specify RESOLVE or COMPILE, Oracle recompiles or resolves the object. Whether or not the resolution or compilation is successful, Oracle invalidates classes that reference the Java schema object. For additional information, see "ALTER JAVA" on page 7-45. Users who had previously been granted privileges on a redefined function can still access the function without being regranted the privileges. RESOLVE | COMPILE are synonymous keywords. They specify that Oracle should attempt to resolve the Java schema object that is created if this statement succeeds.
s
When applied to a class, resolution of referenced names to other class schema objects occurs. When applied to a source, source compilation occurs.
s
Restriction: You cannot specify this clause for a Java resource.
7-312 SQL Reference
CREATE JAVA
NOFORCE
rolls back the results of this CREATE command if you have specified either RESOLVE or COMPILE, and the resolution or compilation fails. If you do not specify this option, Oracle takes no action if the resolution or compilation fails (that is, the created schema object remains). loads a Java source file. loads a Java class file.
JAVA SOURCE JAVA CLASS
JAVA RESOURCE loads a Java resource file. NAMED is required for a Java source or resource. The primary_name must be enclosed in double quotation marks.
s
For a Java source, this clause specifies the name of the schema object in which the source code is held. A successful CREATE JAVA SOURCE statement will also create additional schema objects to hold each of the Java classes defined by the source. For a Java resource, this clause specifies the name of the schema object to hold the Java resource. Use double quotation marks to preserve lower- or mixed-case primary_name.
s
s
If you do not specify schema, Oracle creates the object in your own schema. Restrictions:
s s
You cannot specify NAMED for a Java class. The primary_name cannot contain a database link.
SCHEMA schema
applies only to a Java class. This optional clause specifies the schema in which the object containing the Java file resides. If you do not specify schema and you do not specify NAMED (above), Oracle creates the object in your own schema. specifies whether the methods of the class execute with the privileges and in the schema of the user who owns the class or with the privileges and in the schema of CURRENT_ USER. For information on how CURRENT_USER is determined, see Oracle8i Concepts and Oracle8i Application Developer's Guide - Fundamentals. This clause also determines how Oracle resolves external names in queries, DML operations, and dynamic SQL statements in the member functions and procedures of the type. See Also: Oracle8i Java Stored Procedures Developer's Guide. AUTHID CURRENT_USER specifies that the methods of the class execute with the privileges of CURRENT_USER. This clause is the default and creates an "invokerrights class." This clause also specifies that external names in queries, DML operations, and dynamic SQL statements resolve in the schema of CURRENT_USER. External names in all other statements resolve in the schema in which the methods reside.
invoker_rights_ clause
SQL Statements
7-313
CREATE JAVA
AUTHID DEFINER RESOLVER
specifies that the methods of the class execute with the privileges of the owner of the schema in which the class resides, and that external names resolve in the schema where the class resides.
specifies a mapping of the fully qualified Java name to a Java schema object, where
s
match_string is either a fully qualified Java name, a wildcard that can match such a Java name, or a wildcard that can match any name. schema_name designates a schema to be searched for the corresponding Java schema object. A dash (-) as an alternative to schema_name indicates that if match_string matches a valid Java name, Oracle can leave the name unresolved. The resolution succeeds, but the name cannot be used at run time by the class.
s
s
This mapping is stored with the definition of the schema objects created in this command for use in later resolutions (either implicit or in explicit ALTER ... RESOLVE statements). USING determines a sequence of character (CLOB or BFILE) or binary (BLOB or BFILE) data for the Java class or resource. Oracle uses the sequence of characters to define one file for a Java class or resource, or one source file and one or more derived classes for a Java source. BFILE identifies a previously created file on the operating system (directory_ object_name) and server file (server_file_name) containing the sequence. BFILE is usually interpreted as a character sequence by CREATE JAVA SOURCE and as a binary sequence by CREATE JAVA CLASS or CREATE JAVA RESOURCE. supplies a query that selects a single row and column of the type specified (CLOB, BLOB, or BFILE). The value of the column makes up the sequence of characters. supplies the following implicit query: SELECT LOB FROM CREATE$JAVA$LOB$TABLE WHERE NAME = 'key_for_BLOB'; Restriction: To use this case, the table CREATE$JAVA$LOB$TABLE must exist in the current schema and must have a column LOB of type BLOB and a column NAME of type VARCHAR2. AS source_text determines a sequence of characters for a Java or SQLJ source.
CLOB/BLOB/ BFILE subquery key_for_BLOB
Examples
The following statement creates a schema object containing a Java class using the name found in a Java binary file:
Java Class Example
CREATE JAVA CLASS USING BFILE (bfile_dir, 'Agent.class');
7-314 SQL Reference
CREATE JAVA
This example assumes the directory object bfile_dir, which points to the operating system directory containing the Java class Agent.class, already exists. In this example, the name of the class determines the name of the Java class schema object.
Java Source Example The following statement creates a Java source schema
object:
CREATE JAVA SOURCE NAMED "Hello" AS public class Hello { public static String hello() { return "Hello World"; } };
Java Resource Example The following statement creates a Java resource schema
object named APPTEXT from a BFILE:
CREATE JAVA RESOURCE NAMED "appText" USING BFILE (bfile_dir, 'textBundle.dat');
SQL Statements
7-315
CREATE LIBRARY
CREATE LIBRARY
Syntax
OR CREATE REPLACE LIBRARY schema . libname AS IS ' filespec ' ;
filespec: See "filespec" on page 7-516.
Purpose
To create a schema object associated with an operating-system shared library. The name of this schema object can then be used in the call_spec of CREATE FUNCTION or CREATE PROCEDURE statements, or when declaring a function or procedure in a package or type, so that SQL and PL/SQL can call to third-generation-language (3GL) functions and procedures.
See Also: "CREATE FUNCTION" on page 7-284 and PL/SQL
User's Guide and Reference for more information on functions and procedures.
Prerequisites
To create a library in your own schema, you must have the CREATE LIBRARY system privilege. To create a library in another user's schema, you must have the CREATE ANY LIBRARY system privilege. To use the procedures and functions stored in the library, you must have EXECUTE object privileges on the library. The CREATE LIBRARY statement is valid only on platforms that support shared libraries and dynamic linking.
Keywords and Parameters
OR REPLACE re-creates the library if it already exists. Use this clause to change the definition of an existing library without dropping, re-creating, and regranting schema object privileges granted on it. Users who had previously been granted privileges on a redefined library can still access the library without being regranted the privileges.
7-316 SQL Reference
CREATE LIBRARY
libname 'filespec'
is the name you with to create to represent this library when declaring a function or procedure with a call_spec. is a string literal, enclosed in single quotes. This string should be the path or filename your operating system recognizes as naming the shared library. The 'filespec' is not interpreted during execution of the CREATE LIBRARY statement. The existence of the library file is not checked until an attempt is made to execute a routine from it.
Examples
The following statement creates library EXT_LIB:
CREATE LIBRARY ext_lib AS '/OR/lib/ext_lib.so';
The following statement re-creates library EXT_LIB:
CREATE OR REPLACE LIBRARY ext_lib IS '/OR/newlib/ext_lib.so';
SQL Statements
7-317
CREATE MATERIALIZED VIEW / SNAPSHOT
CREATE MATERIALIZED VIEW / SNAPSHOT
Syntax
MATERIALIZED CREATE SNAPSHOT physical_attributes_clause TABLESPACE tablespace VIEW schema . materialized_view / snapshot
LOB_storage_clause LOGGING NOLOGGING CACHE NOCACHE , CLUSTER cluster ( column ) partitioning_clauses parallel_clause
IMMEDIATE BUILD DEFERRED WITH REDUCED WITHOUT ON PREBUILT TABLE PRECISION
physical_attributes_clause TABLESPACE USING INDEX DISABLE QUERY FOR UPDATE ENABLE AS subquery ; REWRITE tablespace refresh_clause
7-318 SQL Reference
CREATE MATERIALIZED VIEW / SNAPSHOT
refresh_clause::=
FAST COMPLETE FORCE DEMAND ON COMMIT START NEXT REFRESH PRIMARY WITH ROWID MASTER LOCAL DEFAULT USING MASTER LOCAL ROLLBACK NEVER REFRESH SEGMENT rollback_segment ROLLBACK SEGMENT KEY WITH date
physical_attributes_clause: See "CREATE TABLE" on page 4-381. parallel_clause::=
NOPARALLEL integer PARALLEL
subquery: See "SELECT and Subqueries" on page 7-569. LOB_storage_clause: See "CREATE TABLE" on page 4-381. partitioning_clauses: See "CREATE TABLE" on page 4-381.
SQL Statements
7-319
CREATE MATERIALIZED VIEW / SNAPSHOT
Purpose
To create a materialized view. The terms snapshot and materialized view are synonymous in Oracle documentation. This reference uses "materialized view" for consistency. Both refer to a database object that contains the results of a query of one or more tables. The tables in the query are called master tables (a replication term) or detail tables (a data warehouse term). This reference uses "master tables" for consistency. The databases containing the master tables are called the master databases. For replication purposes, materialized views allow you to maintain copies of remote data on your local node. The copies can be updatable with the Advanced Replication feature and are read-only without this feature. You can select data from a materialized view as you would from a table or view. In replication environments, the materialized views commonly created are primary key, rowid, and subquery materialized views. For data warehousing purposes, the materialized views commonly created are materialized aggregate views, single-table materialized aggregate views, and materialized join views. All three types of materialized views can be used by query rewrite, an optimization technique that transforms a user request written in terms of master tables into a semantically equivalent request that includes one or more materialized view. In a data warehousing environment, all master tables must be local.
See Also:
s
Oracle8i Replication for information on the types of materialized views used to support replication. Oracle8i Data Warehousing Guide for information on the types of materialized views used to support data warehousing.
s
Prerequisites
The privileges required to create a materialized view should be granted directly. To create a materialized view in your own schema:
s
You must have been granted either the CREATE MATERIALIZED VIEW or CREATE SNAPSHOT system privilege and either the CREATE TABLE or CREATE ANY TABLE system privilege.
7-320 SQL Reference
CREATE MATERIALIZED VIEW / SNAPSHOT
s
You must also have access to any master tables of the materialized view that you do not own, either through a SELECT object privilege on each of the tables or through the SELECT ANY TABLE system privilege.
To create a materialized view in another user's schema:
s
You must have the CREATE ANY MATERIALIZED VIEW or CREATE ANY SNAPSHOT system privilege and access to any master tables of the materialized view that you do not own, either through a SELECT object privilege on each of the tables or through the SELECT ANY TABLE system privilege. The owner or the materialized view must have the CREATE TABLE system privilege. The owner must also have access to any master tables of the materialized view that the schema owner does not own and to any materialized view logs defined on those master tables, either through a SELECT object privilege on each of the tables or through the SELECT ANY TABLE system privilege.
s
To create the materialized view with query rewrite enabled, in addition to the preceding privileges:
s
The owner of the master tables must have the QUERY REWRITE system privilege. If you are not the owner of the master tables, you must have the GLOBAL QUERY REWRITE system privilege. If the schema owner does not own the master tables, then the schema owner must have the GLOBAL QUERY REWRITE privilege.
s
s
The user whose schema contains the materialized view must have sufficient quota in the target tablespace to store the materialized view's master table and index, or must have the UNLIMITED TABLESPACE system privilege. When you create a materialized view, Oracle creates one internal table and at least one index, and may create one view, all in the schema of the materialized view. Oracle uses these objects to maintain the materialized view's data. You must have the privileges necessary to create these objects.
SQL Statements
7-321
CREATE MATERIALIZED VIEW / SNAPSHOT
See Also:
s
"CREATE TABLE" on page 4-381, "CREATE VIEW" on page 7-456, and "CREATE INDEX" on page 7-291 for information on these privileges. Oracle8i Replication for information about the prerequisites that apply to creating replication materialized views. Oracle8i Data Warehousing Guide for information about the prerequisites that apply to creating data warehousing materialized views.
s
s
Keywords and Parameters
schema is the schema to contain the materialized view. If you omit schema, Oracle creates the materialized view in your schema.
materialized_view / is the name of the materialized view to be created. Oracle generates names for the table snapshot and indexes used to maintain the materialized view by adding a prefix or suffix to the materialized view name. physical_ establishes values for the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters (or, attributes_clause when used in the USING INDEX clause, for the INITRANS and MAXTRANS parameters only) and the storage characteristics for the materialized view. See Also:
s
"CREATE TABLE" on page 4-381 for information on the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters "storage_clause" on page 7-605 for information about storage characteristics
s
TABLESPACE
specifies the tablespace in which the materialized view is to be created. If you omit this clause, Oracle creates the materialized view in the default tablespace of the owner of the materialized view's schema. specifies the LOB storage characteristics. See Also: "CREATE TABLE" on page 4-381 for detailed information about specifying the parameters of this clause. creates the materialized view as part of the specified cluster. A clustered materialized view uses the cluster's space allocation. Therefore, do not use the physical_attributes_clause or the TABLESPACE clause with the CLUSTER clause. establishes the logging characteristics for the materialized view. See Also: "CREATE TABLE" on page 4-381 for a description of logging characteristics.
LOB_storage_ clause
CLUSTER
LOGGING | NOLOGGING
7-322 SQL Reference
CREATE MATERIALIZED VIEW / SNAPSHOT
CACHE | NOCACHE
For data that will be accessed frequently, CACHE specifies that the blocks retrieved for this table are placed at the most recently used end of the LRU list in the buffer cache when a full table scan is performed. This attribute is useful for small lookup tables. NOCACHE specifies that the blocks are placed at the least recently used end of the LRU list. See Also: "CREATE TABLE" on page 4-381 for information about specifying CACHE or NOCACHE.
partitioning_ clauses parallel_clause
specifies that the materialized view is partitioned on specified ranges of values or on a hash function. Partitioning of materialized views is the same as partitioning tables, as described in "CREATE TABLE" on page 4-381. indicates whether parallel operations will be supported for the materialized view and sets the default degree of parallelism for queries and DML on the materialized view after creation. NOPARALLEL PARALLEL specifies serial execution. This is the default. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances times the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution servers. Normally Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer. See Also: The Notes to the parallel_clause of "CREATE TABLE" on page 4-381 for additional information. BUILD specifies when to populate the materialized view. IMMEDIATE DEFERRED specifies that the materialized view is populated immediately. This is the default. specifies that the materialized view will be populated by the next REFRESH operation. The first (deferred) refresh must always be a complete refresh. Until then, the materialized view has a staleness value of UNUSABLE, so it cannot be used for query rewrite.
ON PREBUILT TABLE
lets you register an existing table as a preinitialized materialized view. This is particularly useful for registering large materialized views in a data warehousing environment. The table must have the same name and be in the same schema as the resulting materialized view. If the materialized view is dropped, the preexisting table reverts to its identity as a table. Caution: This clause assumes that the table object reflects the materialization of a subquery. Oracle Corporation strongly recommends that you ensure that this assumption is true in order to ensure that the materialized view correctly reflects the data in its master tables.
SQL Statements
7-323
CREATE MATERIALIZED VIEW / SNAPSHOT
Restrictions:
s
Each column alias in subquery must correspond to a column in table_name, and corresponding columns must have matching datatypes. If you specify this clause, you cannot specify a NOT NULL constraint for any column that is unmanaged (that is, not referenced in subquery) unless you also specify a default value for that column. lets you authorize the loss of precision that will result if the precision of the table or materialized view columns do not exactly match the precision returned by subquery. requires that the precision of the table or materialized view columns match exactly the precision returned by subquery, or the create operation will fail. This is the default.
s
WITH REDUCED PRECISION WITHOUT REDUCED PRECISION USING INDEX
establishes the value of INITRANS, MAXTRANS, and STORAGE parameters for the index Oracle uses to maintain the materialized view's data. If USING INDEX is not specified, then default values are used for the index. Restriction: You cannot specify the PCTUSED or PCTFREE parameters in this clause.
refresh_clause
specifies the default methods, modes, and times for Oracle to refresh the materialized view. If a materialized view's master tables are modified, the data in a materialized view must be updated to make the materialized view accurately reflect the data currently in its master tables. This clause lets you schedule the times and specify the method and mode for Oracle to refresh the materialized view. Note: This clause only sets the default refresh options. For instructions on actually implementing the refresh, refer to Oracle8i Replication and Oracle8i Data Warehousing Guide. FAST specifies the incremental refresh method, which performs the refresh according to the changes that have occurred to the master tables. The changes are stored either in the materialized view log associated with the master table (for conventional DML changes) or in the direct loader log (for direct-load INSERTs). You can create a materialized aggregate view even if you have not yet created materialized view logs for the underlying master tables. However, if you are creating any other type of materialized view, the CREATE statement will fail unless those materialized view logs already exist. (Oracle creates the direct loader log automatically when a directload INSERT takes place. No user intervention is needed.)
7-324 SQL Reference
CREATE MATERIALIZED VIEW / SNAPSHOT
After create time, Oracle will perform the fast refresh for conventional DML only if the appropriate materialized view logs exist. For both conventional DML changes and for direct-path loads, other conditions may restrict the eligibility of a materialized view for fast refresh. See Also:
s
Oracle8i Replication for restrictions on fast refresh in replication environments. Oracle8i Data Warehousing Guide for restrictions on fast refresh in data warehouse environments.
s
Materialized views are not eligible for fast refresh if the defining query contains an analytic function. See Also: "Analytic Functions" on page 4-7. COMPLETE specifies the complete refresh method, which is implemented by executing the materialized view's defining query. If you request a complete refresh, Oracle performs a complete refresh even if a fast refresh is possible. specifies that when a refresh occurs, Oracle will perform a fast refresh if one is possible or a complete refresh otherwise. If you do not specify a refresh method (FAST, COMPLETE, or FORCE), FORCE is the default. specifies that a fast refresh is to occur whenever Oracle commits a transaction that operates on a master table of the materialized view. Restriction: This clause is supported only for materialized join views and single-table materialized aggregate views. See Also: Oracle8i Replication and Oracle8i Data Warehousing Guide. ON DEMAND specifies that the materialized view will be refreshed on demand by calling one of the three DBMS_MVIEW refresh procedures. If you omit both ON COMMIT and ON DEMAND, ON DEMAND is the default. See Also:
s
FORCE
ON COMMIT
Oracle8i Supplied PL/SQL Packages Reference for information on these procedures. Oracle8i Data Warehousing Guide on the types of materialized views you can create by specifying REFRESH ON DEMAND.
s
If you specify ON COMMIT or ON DEMAND, you cannot also specify START WITH or NEXT. START WITH specifies a date expression for the first automatic refresh time.
SQL Statements
7-325
CREATE MATERIALIZED VIEW / SNAPSHOT
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 with respect to the creation time of the materialized view. If you specify a START WITH value but omit the NEXT value, Oracle refreshes the materialized view 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 materialized view. WITH PRIMARY KEY specifies that a primary key materialized view is to be created. This is the default, and should be used in all cases except those described for WITH ROWID. Primary key materialized views allow materialized view master tables to be reorganized without affecting the materialized view's ability to continue to fast refresh. The master table must contain an enabled primary key constraint. See Also: Oracle8i Replication for detailed information about primary key materialized views WITH ROWID specifies that a rowid materialized view is to be created. Rowid materialized views provide compatibility with master tables in releases of Oracle prior to 8.0. You can also use rowid materialized views if the materialized view does not include all primary key columns of the master tables. Rowid materialized views must be based on a single remote table and cannot contain any of the following:
s s s s s
distinct or aggregate functions GROUP BY or CONNECT BY clauses subqueries joins set operations
Rowid materialized views cannot be fast refreshed after a master table reorganization until a complete refresh has been performed. USING ROLLBACK SEGMENT specifies the remote rollback segment to be used during materialized view refresh, where rollback_segment is the name of the rollback segment to be used.
7-326 SQL Reference
CREATE MATERIALIZED VIEW / SNAPSHOT
s
DEFAULT specifies that Oracle will choose automatically which rollback segment to use. If you specify DEFAULT, you cannot specify rollback_segment. Note: DEFAULT is most useful when modifying a materialized view, as described in "ALTER MATERIALIZED VIEW / SNAPSHOT" on page 7-47.
s
MASTER specifies the remote rollback segment to be used at the remote master site for the individual materialized view. LOCAL specifies the remote rollback segment to be used for the local refresh group that contains the materialized view. See Also: Oracle8i Replication for information on specifying the local materialized view rollback segment using the DBMS_ REFRESH package.
s
If you do not specify MASTER or LOCAL, Oracle uses LOCAL by default. If you do not specify rollback_segment, Oracle automatically chooses the rollback segment to be used. The master rollback segment is stored on a per-materialized-view basis and is validated during materialized view creation and refresh. If the materialized view is complex, the master rollback segment, if specified, is ignored. NEVER REFRESH prevents the materialized view from being refreshed with any Oracle refresh mechanism or procedure. If you issue a REFRESH statement on the materialized view, Oracle returns an error. FOR UPDATE allows a subquery, primary key, or rowid materialized view to be updated. When used in conjunction with Advanced Replication, these updates will be propagated to the master. See Also: Oracle8i Replication. QUERY REWRITE specifies whether the materialized view is eligible to be used for query rewrite. ENABLE enables the materialized view for query rewrite. See Also: Oracle8i Data Warehousing Guide for more information on query rewrite. Notes:
s
Query rewrite is disabled by default, so you must specify this clause to make materialized views eligible for query rewrite. Be sure to analyze the materialized view after you create it. Oracle needs the statistics generated by the ANALYZE operation to optimize query rewrite.
s
SQL Statements
7-327
CREATE MATERIALIZED VIEW / SNAPSHOT
Restrictions:
s
You can enable query rewrite only if all user-defined functions in the materialized view are DETERMINISTIC. You can enable query rewrite only if expressions in the statement are repeatable. For example, you cannot include CURRENT_TIME or USER, sequence values (such as the CURRVAL or NEXTVAL pseudocolumns), or the SAMPLE clause (which may sample different rows as the contents of the materialized view change).
s
See Also: "CREATE FUNCTION" on page 7-284 and Oracle8i Data Warehousing Guide. DISABLE AS subquery specifies that the materialized view is not eligible for use by query rewrite. However, a disabled materialized view can be refreshed.
specifies the materialized view's defining query. When you create the materialized view, Oracle executes this query and places the results in the materialized view. This query is any valid SQL query. However, not all queries are fast refreshable, nor are all queries eligible for query rewrite. Notes:
s s
Oracle does not execute the query immediately if you specify BUILD DEFERRED. Oracle recommends that you qualify each table and view in the FROM clause of the materialized view query with the schema containing it. For some additional caveats, see the AS subquery clause of "CREATE TABLE" on page 4-381.
Restrictions:
s
A materialized view query can select from tables or views owned by the user SYS, but you cannot enable QUERY REWRITE on such a materialized view. You cannot refer to a user-defined type anywhere in the materialized view query. Materialized join views and materialized aggregate views with a GROUP BY clause cannot select from an index-organized table. Materialized views cannot contain columns of datatype LONG. If the subquery refers to a temporary table, you cannot create a materialized view log for this materialized view, nor can you specify the QUERY REWRITE clause of CREATE MATERIALIZED VIEW or ALTER MATERIALIZED VIEW. If the FROM list of the materialized view references another materialized view, you must control the refresh order of the materialized views manually. That is, you must refresh the materialized view depended upon and then the dependent materialized view in order to maintain freshness.
s s
s s
s
7-328 SQL Reference
CREATE MATERIALIZED VIEW / SNAPSHOT
If you are creating a materialized view enabled for query rewrite:
s
The subquery cannot contain (either directly or through a view) references to ROWNUM, USER, SYSDATE, remote tables, sequences, or PL/SQL functions that write or read database or package state. The materialized view and the master tables of the materialized view must be local.
s
If you want the materialized view to be eligible for fast refresh using a materialized view log, some additional restrictions may apply. See Also:
s
Oracle8i Data Warehousing Guide for more information on restrictions relating to data warehousing Oracle8i Replication for more information on restrictions relating to replication.
s
Examples
Materialized Aggregate View Examples The following statement creates and
populates a materialized aggregate view and specifies the default refresh method, mode, and time:
CREATE MATERIALIZED VIEW mv1 REFRESH FAST ON COMMIT BUILD IMMEDIATE AS SELECT t.month, p.prod_name, SUM(f.sales) AS sum_sales FROM time t, product p, fact f WHERE f.curDate = t.curDate AND f.item = p.item GROUP BY t.month, p.prod_name;
The following statement creates and populates the materialized aggregate view SALES_BY_MONTH_BY_STATE. The materialized view will be populated with data as soon as the statement executes successfully. By default, subsequent refreshes will be accomplished by reexecuting the materialized view's query:
CREATE MATERIALIZED VIEW sales_by_month_by_state TABLESPACE my_ts PARALLEL (10) ENABLE QUERY REWRITE BUILD IMMEDIATE REFRESH COMPLETE AS SELECT t.month, g.state, SUM(f.sales) AS sum_sales FROM fact f, time t, geog g WHERE f.cur_date = t.cur_date AND f.city_id = g.city_id GROUP BY month, state;
SQL Statements
7-329
CREATE MATERIALIZED VIEW / SNAPSHOT
Prebuilt Materialized View Example The following statement creates a
materialized aggregate view for the preexisting summary table, SALES_SUM_ TABLE:
CREATE TABLE sales_sum_table (month DATE, state VARCHAR2(25), sales NUMBER); CREATE MATERIALIZED VIEW sales_sum_table ON PREBUILT TABLE ENABLE QUERY REWRITE AS SELECT t.month, g.state, SUM(f.sales) AS sum_sales FROM fact f, time t, geog g WHERE f.cur_date = t.cur_date AND f.city_id = g.city_id GROUP BY month, state;
In this example, the materialized view has the same name as the prebuilt table and also has the same number of columns with the same datatypes as the prebuilt table.
Materialized Join View Example
The following statement creates the materialized
join view MJV:
CREATE MATERIALIZED VIEW mjv REFRESH FAST AS SELECT l.rowid as l_rid, l.pk, l.ofk, l.c1, l.c2, o.rowid as o_rid, o.pk, o.cfk, o.c1, o.c2, c.rowid as c_rid, c.pd, c.c1, c.c2 FROM l, o, c WHERE l.ofk = o.pk(+) AND o.ofk = c.pk(+);
Subquery Materialized View Example The following statement creates a subquery materialized view based on the ORDERS and CUSTOMERS tables in the SALES schema at a remote database:
CREATE MATERIALIZED VIEW sales.orders FOR UPDATE AS SELECT * FROM sales.orders@dbs1.acme.com o WHERE EXISTS (SELECT * FROM sales.customers@dbs1.acme.com c WHERE o.c_id = c.c_id);
The following statement creates the primary-key materialized view HUMAN_GENOME:
Primary Key Example
CREATE MATERIALIZED VIEW human_genome REFRESH FAST START WITH SYSDATE NEXT WITH PRIMARY KEY AS SELECT * FROM genome_catalog; SYSDATE + 1/4096
7-330 SQL Reference
CREATE MATERIALIZED VIEW / SNAPSHOT
Rowid Example The following statement creates a rowid materialized view:
CREATE MATERIALIZED VIEW emp_data REFRESH WITH ROWID AS SELECT * FROM emp_table73;
Periodic Refresh Example The following statement creates the primary key materialized view EMP_SF and populates it with data from SCOTT's employee table in New York:
CREATE MATERIALIZED VIEW emp_sf PCTFREE 5 PCTUSED 60 TABLESPACE users STORAGE (INITIAL 50K NEXT 50K) REFRESH FAST NEXT sysdate + 7 AS SELECT * FROM scott.emp@ny;
The statement does not include a START WITH parameter, so Oracle determines the first automatic refresh time by evaluating the NEXT value using the current SYSDATE. Provided that a materialized view log currently exists for the employee table in New York, Oracle performs a fast refresh of the materialized view every 7 days, beginning 7 days after the materialized view is created. Because the materialized view conforms to the conditions for fast refresh, Oracle will perform a fast refresh. The above statement also establishes storage characteristics that Oracle uses to maintain the materialized view.
Automatic Refresh Times Example The following statement creates the complex materialized view ALL_EMPS that queries the employee tables in Dallas and Baltimore:
CREATE MATERIALIZED VIEW 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 materialized view tomorrow at 11:00 am and subsequently every Monday at 3:00 pm. The default refresh method is FORCE. ALL_ EMPS contains a UNION, which is not supported for fast refresh, so Oracle will automatically perform a complete refresh.
SQL Statements
7-331
CREATE MATERIALIZED VIEW / SNAPSHOT
The above statement also establishes storage characteristics for both the materialized view and the index that Oracle uses to maintain it:
s
The first storage_clause establishes the sizes of the first and second extents of the materialized view as 50 kilobytes each. The second storage_clause (appearing with the USING INDEX clause) establishes the sizes of the first and second extents of the index as 25 kilobytes each.
s
Rollback Segment Example The following statement creates the primary key
materialized view SALES_EMP with rollback segment MASTER_SEG at the remote master and rollback segment SNAP_SEG for the local refresh group that contains the materialized view:
CREATE MATERIALIZED VIEW sales_emp REFRESH FAST START WITH SYSDATE NEXT SYSDATE + 7 USING MASTER ROLLBACK SEGMENT master_seg LOCAL ROLLBACK SEGMENT snap_seg AS SELECT * FROM bar;
The following statement is incorrect and generates an error because it specifies a segment name with a DEFAULT rollback segment:
CREATE MATERIALIZED VIEW bogus REFRESH FAST START WITH SYSDATE NEXT SYSDATE + 7 USING DEFAULT ROLLBACK SEGMENT snap_seg AS SELECT * FROM faux;
7-332 SQL Reference
CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG
CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG
Syntax
MATERIALIZED CREATE SNAPSHOT physical_attributes_clause TABLESPACE LOGGING NOLOGGING CACHE NOCACHE parallel_clause , ( KEY , , ROWID KEY filter_column ) partitioning_clauses tablespace VIEW LOG ON schema . table
PRIMARY ROWID WITH PRIMARY ROWID
KEY
PRIMARY
INCLUDING NEW EXCLUDING ; VALUES
SQL Statements
7-333
CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
storage_clause: See "storage_clause" on page 7-605. parallel_clause::=
NOPARALLEL integer PARALLEL
partitioning_clauses: See "CREATE TABLE" on page 4-381.
Purpose
To create a materialized view log. A materialized view log is a table associated with the master table of a materialized view. The terms snapshot and materialized view are synonymous. Both refer to a table that contains the results of a query of one or more tables, each of which may be located on the same or on a remote database. When DML changes are made to the master table's data, Oracle stores rows describing those changes in the materialized view log and then uses the materialized view log to refresh materialized views based on the master table. This process is called a fast refresh. Without a materialized view log, Oracle must reexecute the materialized view query to refresh the materialized view. This process is called a complete refresh. Usually, a fast refresh takes less time than a complete refresh. A materialized view log is located in the master database in the same schema as the master table. You need only a single materialized view log for a master table. Oracle can use this materialized view log to perform fast refreshes for all fast-refreshable materialized views based on the master table.
7-334 SQL Reference
CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG
To fast refresh a materialized join view (a materialized view containing a join), you must create a materialized view log for each of its master tables.
See Also:
s
Oracle8i Data Warehousing Guide and Oracle8i Replication for information on materialized views in general. "CREATE MATERIALIZED VIEW / SNAPSHOT" on page 7-318 and Oracle8i Concepts for more information on materialized views. "ALTER MATERIALIZED VIEW LOG / SNAPSHOT LOG" on page 7-58 for information on modifying a materialized view log. "DROP MATERIALIZED VIEW LOG / SNAPSHOT LOG" on page 7-487 for information on dropping a materialized view log. Oracle8i Concepts for information on using direct loader logs.
s
s
s
s
Prerequisites
The privileges required to create a materialized view log directly relate to the privileges necessary to create the underlying objects associated with a materialized view log.
s
If you own the master table, you can create an associated materialized view log if you have the CREATE TABLE privilege. If you are creating a materialized view log for a table in another user's schema, you must have the CREATE ANY TABLE and COMMENT ANY TABLE privileges, as well as either the SELECT privilege for the master table or SELECT ANY TABLE.
s
In either case, the owner of the materialized view log must have sufficient quota in the tablespace intended to hold the materialized view log or must have the UNLIMITED TABLESPACE system privilege. For detailed information about the prerequisites for creating a materialized view log, see Oracle8i Replication.
SQL Statements
7-335
CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG
Keywords and Parameters
schema is the schema containing the materialized view log's master table. If you omit schema, Oracle assumes the master table is contained in your own schema. Oracle creates the materialized view log in the schema of its master table. You cannot create a materialized view log for a table in the schema of the user SYS. is the name of the master table for which the materialized view log is to be created. You cannot create a materialized view log for a view.
table
physical_ establishes values for physical and storage characteristics for the materialized view log. attributes_clause See the descriptions of these parameters in "CREATE TABLE" on page 4-381 and "storage_ clause" on page 7-605. TABLESPACE specifies the tablespace in which the materialized view log is to be created. If you omit this clause, Oracle creates the materialized view log in the default tablespace of the owner of the materialized view log's schema. establishes the logging characteristics for the materialized view log. For a description of logging characteristics, see "CREATE TABLE" on page 4-381. For data that will be accessed frequently, CACHE specifies that the blocks retrieved for this log are placed at the most recently used end of the LRU list in the buffer cache when a full table scan is performed. This attribute is useful for small lookup tables. NOCACHE specifies that the blocks are placed at the least recently used end of the LRU list. See Also: "ALTER TABLE" on page 7-123 for information about specifying CACHE or NOCACHE. parallel_clause specifies whether parallel operations will be supported for the materialized view log. For additional information, see the Notes to the parallel_clause of "CREATE TABLE" on page 4-381. NOPARALLEL PARALLEL specifies serial execution. This is the default. causes Oracle to select a degree of parallelism equal to the number of CPUs available on all participating instances times the value of the PARALLEL_THREADS_PER_CPU initialization parameter.
LOGGING | NOLOGGING CACHE | NOCACHE
PARALLEL integer specifies the degree of parallelism, which is the number of parallel threads used in the parallel operation. Each parallel thread may use one or two parallel execution servers. Normally, Oracle calculates the optimum degree of parallelism, so it is not necessary for you to specify integer. partitioning_ clauses WITH specifies that the materialized view log is partitioned on specified ranges of values or on a hash function. Partitioning of materialized view logs is the same as partitioning of tables, as described in "CREATE TABLE" on page 4-381. specifies whether the materialized view log should record the primary key, the rowid, or both the primary key and rowid when rows in the master are updated.
7-336 SQL Reference
CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG
This clause also specifies whether the materialized view log records filter columns, which are non-primary-key columns referenced by subquery materialized views. PRIMARY KEY specifies that the primary key of all rows updated should be recorded in the materialized view log. The primary key of updated rows in the master table must be recorded in the materialized view log. specifies that the rowid of all rows updated should be recorded in the materialized view log. The rowid must be recorded in the materialized view log. is a comma-separated list that specifies the filter columns to be recorded in the materialized view log. For fast-refreshable primarykey materialized views defined with subqueries, all filter columns referenced by the defining subquery must be recorded in the materialized view log.
ROWID
filter_column
Oracle records the primary key of all rows updated in the master by default. NEW VALUES specifies whether Oracle saves both old and new values in the materialized view log. INCLUDING saves both new and old values in the log. If this log is for a table on which you have a single-table materialized aggregate view, and if you want the materialized view to be eligible for fast refresh, you must specify INCLUDING. disables the recording of new values in the log. This is the default. You can use this clause to avoid the overhead of recording new values. However, do not use this clause if you have a fast-refreshable singletable materialized aggregate view defined on this table.
EXCLUDING
Examples
The following statement creates a materialized view log on an employee table that records only primary key values:
Primary Key Examples
CREATE MATERIALIZED VIEW LOG ON emp WITH PRIMARY KEY;
Oracle can use this materialized view log to perform a fast refresh on any simple primary key materialized view subsequently created on the EMP table. The following statement also creates a materialized view log that record only the primary keys of updated rows:
CREATE MATERIALIZED VIEW LOG ON emp PCTFREE 5 TABLESPACE users STORAGE (INITIAL 10K NEXT 10K);
SQL Statements
7-337
CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG
The following statement creates a materialized view log that records both the primary keys and the rowids of updated rows:
ROWID Example
CREATE MATERIALIZED VIEW LOG ON sales WITH ROWID, PRIMARY KEY;
Filter Column Example The following statement creates a materialized view log
that records primary keys and updates to the filter column ZIP:
CREATE MATERIALIZED VIEW LOG ON address WITH (zip);
NEW VALUES Example The following example creates a master table, then creates a materialized view log that specifies INCLUDING NEW VALUES:
CREATE TABLE agg (u NUMBER, a NUMBER, b NUMBER, c NUMBER, d NUMBER); CREATE MATERIALIZED VIEW LOG ON agg WITH ROWID (u,a,b,c,d) INCLUDING NEW VALUES;
You could create the following materialized aggregate view to use the AGG log:
CREATE MATERIALIZED VIEW sn0 REFRESH FAST ON COMMIT AS SELECT SUM(b+c), COUNT(*), a, d, COUNT(b+c) FROM agg GROUP BY a,d;
This materialized view is eligible for fast refresh because the log it uses includes both old and new values.
7-338 SQL Reference
CREATE OPERATOR
CREATE OPERATOR
Syntax
OR CREATE REPLACE OPERAT0R schema . operator binding_clause ;
binding_clause::=
, , BINDING ( parameter_type ) RETURN return_type implementation_clause
implementation_clause::=
, , ANCILLARY TO primary_operator COMPUTE context_clause using_clause ( parameter_type DATA )
ANCILLARY
context_clause::=
WITH INDEX CONTEXT , SCAN CONTEXT implementation_type
using_clause::=
package schema USING . type . function_name .
SQL Statements
7-339
CREATE OPERATOR
Purpose
To create a new operator and define its bindings. Operators can be referenced by indextypes and by DML and query SQL statements. The operators, in turn, reference functions, packages, types, and other user-defined objects. For a discussion of these dependencies, and of operators in general, see Oracle8i Data Cartridge Developer's Guide and Oracle8i Concepts.
Prerequisites
To create an operator in your own schema, you must have CREATE OPERATOR system privilege. To create an operator in another schema, you must have the CREATE ANY OPERATOR system privilege. In either case, you must also have EXECUTE privilege on the functions and operators referenced.
Keywords and Parameters
OR REPLACE replaces the definition of the operator schema object. Restriction: You can replace the definition only if the operator has no dependent objects (for example, indextypes supporting the operator). schema operator binding_clause is the schema containing the operator. If you omit schema, Oracle assumes the operator is in your own schema. is the name of the operator to be created. specifies one or more parameter datatypes (parameter_type) for binding the operator to a function. The signature of each binding (that is, the sequence of the datatypes of the arguments to the corresponding function) must be unique according to the rules of overloading. The parameter_type can itself be an object type. If it is, you can optionally qualify it with its schema. Restriction: You cannot specify a parameter_type of REF, LONG, or LONG RAW. See Also: PL/SQL User's Guide and Reference for more information about overloading. RETURN specifies the return datatype (return_type) for the binding. The return_type can itself be an object type. If so, you can optionally qualify it with its schema. Restriction: You cannot specify a return_type of REF, LONG, or LONG RAW.
7-340 SQL Reference
CREATE OPERATOR
implementation_clause ANCILLARY TO primary_operator context_clause COMPUTE ANCILLARY DATA using_clause specifies that the operator binding is ancillary to the specified primary operator binding (primary_operator). If you specify this clause, do not specify a previous binding with just one number parameter. specifies the name of the implementation type used by the functional implementation of the operator as a scan context. specifies that the operator binding computes ancillary data.
specifies the function that provides the implementation for the binding. function_name is the name of the function. The function can be a standalone function, packaged function, type method, or a synonym for any of these.
Example
This example creates an operator called MERGE in the SCOTT schema with two bindings. The first binding is for merging two VARCHAR2 values and returning a VARCHAR2 result. The second binding is for merging two geometries into a single geometry. The corresponding functional implementations for the bindings are also specified.
CREATE OPERATOR scott.merge BINDING (varchar2, varchar2) RETURN varchar2 USING text.merge, (spatial.geo, spatial.geo) RETURN spatial.geo USING spatial.merge;
SQL Statements
7-341
CREATE OUTLINE
CREATE OUTLINE
Syntax
OR CREATE FOR CATEGORY category ON statement ; REPLACE OUTLINE outline
Purpose
To create a stored outline, which is a set of attributes used by the optimizer to generate an execution plan. You can then instruct the optimizer to use a set of outlines to influence the generation of execution plans whenever a particular SQL statement is issued, regardless of changes in factors that can affect optimization. (To modify an outline so that it takes into account changes in these factors, see "ALTER OUTLINE" on page 7-63.) You enable or disable the use of stored outlines dynamically for an individual session or for the system. See "ALTER SESSION" on page 7-83 and "ALTER SYSTEM" on page 7-102.
See Also: Oracle8i Designing and Tuning for Performance.
Prerequisites
To create an outline, you must have the CREATE ANY OUTLINE system privilege.
Keywords and Parameters
OR REPLACE outline FOR CATEGORY category ON statement replaces an existing outline with a new outline of the same name. is the unique name to be assigned to the stored outline. If you do not specify outline, the system generates an outline name. specifies an optional name used to group stored outlines. For example, you could specify a category of outlines for end-of-week use and another for end-of-quarter use. If you do not specify category, the outline is stored in the DEFAULT category. is the SQL statement for which Oracle will create an outline when the statement is compiled. You can specify any one of the following statements:
7-342 SQL Reference
CREATE OUTLINE
s s s s s
SELECT DELETE UPDATE INSERT ... SELECT CREATE TABLE ... AS SELECT
Note: You can specify multiple outlines for a single statement, but each outline for the same statement must be in a different category.
Example
The following statement creates a stored outline by compiling the ON statement. The outline is called SALARIES and is stored in the category SPECIAL.
CREATE OUTLINE salaries FOR CATEGORY special ON SELECT ename, sal FROM emp;
When this same SELECT statement is subsequently compiled, if the USE_STORED_ OUTLINES parameter is set to SPECIAL, Oracle generates the same execution plan as was generated when the outline SALARIES was created.
SQL Statements
7-343
CREATE PACKAGE
CREATE PACKAGE
Syntax
OR CREATE invoker_rights_clause IS pl/sql_package_spec AS ; REPLACE PACKAGE schema . package
invoker_rights_clause::=
CURRENT_USER AUTHID DEFINER
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. For information on creating standalone functions and procedures, see "CREATE FUNCTION" on page 7-284 and "CREATE PROCEDURE" on page 7-353. For information on modifying a package, see "ALTER PACKAGE" on page 7-64. For information on dropping a package, see "DROP PACKAGE" on page 7-491. For detailed discussions of packages and how to use them, see Oracle8i Application Developer's Guide - Fundamentals and Oracle8i Supplied PL/SQL Packages Reference.
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 depend 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.
7-344 SQL Reference
CREATE PACKAGE
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.
See Also: PL/SQL User's Guide and Reference.
Keywords and Parameters
OR REPLACE re-creates the package specification if it already exists. Use this clause to change the specification of an existing package without dropping, re-creating, 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 "ALTER PACKAGE" on page 7-64. Users who had previously been granted privileges on a redefined package can still access the package without being regranted the privileges. If any function-based indexes depend on the package, Oracle marks the indexes DISABLED. schema package is the schema to contain the package. If you omit schema, Oracle creates the package in your own schema. is the name of the package to be created. If creating the package results in compilation errors, Oracle returns an error. You can see the associated compiler error messages with the SHOW ERRORS command. invoker_rights_ clause lets you specify whether the functions and procedures in the package execute with the privileges and in the schema of the user who owns it or with the privileges and in the schema of CURRENT_USER. This specification applies to the corresponding package body as well. (For information on how CURRENT_USER is determined, see Oracle8i Concepts and Oracle8i Application Developer's Guide - Fundamentals.) This clause also determines how Oracle resolves external names in queries, DML operations, and dynamic SQL statements in the package. See Also: PL/SQL User's Guide and Reference. AUTHID CURRENT_USER specifies that the package executes with the privileges of CURRENT_USER. This clause creates an "invoker-rights package." This clause also specifies that external names in queries, DML operations, and dynamic SQL statements resolve in the schema of CURRENT_USER. External names in all other statements resolve in the schema in which the package resides. AUTHID DEFINER specifies that the package executes with the privileges of the owner of the schema in which the package resides and that external names resolve in the schema where the package resides. This is the default.
SQL Statements
7-345
CREATE PACKAGE
pl/sql_package_ spec
is the package specification, which can contain type definitions, cursor declarations, variable declarations, constant declarations, exception declarations, PL/SQL subprogram specifications, and call specifications (declarations of a C or Java routine expressed in PL/ SQL). For a list of restrictions on user-defined functions in a package, see "Restrictions on UserDefined Functions" on page 7-286. See Also:
s
PL/SQL User's Guide and Reference for more information on PL/SQL package program units. Oracle8i Supplied PL/SQL Packages Reference for information on Oracle supplied packages.
s
Example
The following 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 the following public program objects:
s
the functions HIRE and CREATE_DEPT the procedures REMOVE_EMP, REMOVE_DEPT, INCREASE_SAL, and INCREASE_ COMM the exceptions NO_COMM and NO_SAL
s
s
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
7-346 SQL Reference
CREATE PACKAGE
PACKAGE BODY statement that creates the body of the EMP_MGMT package, see "CREATE PACKAGE BODY" on page 7-348.
SQL Statements
7-347
CREATE PACKAGE BODY
CREATE PACKAGE BODY
Syntax
OR CREATE IS pl/sql_package_body AS ; REPLACE PACKAGE BODY schema . package
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. For information on creating standalone functions and procedures, see "CREATE FUNCTION" on page 7-284 and "CREATE PROCEDURE" on page 7-353. Packages are an alternative to creating procedures and functions as standalone schema objects. For a discussion of packages, including how to create packages, see "CREATE PACKAGE" on page 7-344. For some illustrations, see "Examples" on page 7-349. For information on modifying a package, see "ALTER PACKAGE" on page 7-64. For information on removing a package from the database, see "DROP PACKAGE" on page 7-491.
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 depend 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. 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.
7-348 SQL Reference
CREATE PACKAGE BODY
See Also: PL/SQL User's Guide and Reference.
Keywords and Parameters
OR REPLACE re-creates the package body if it already exists. Use this clause to change the body of an existing package without dropping, re-creating, and regranting object privileges previously granted on it. If you change a package body, Oracle recompiles it. For information on recompiling package bodies, see "ALTER PACKAGE" on page 7-64. Users who had previously been granted privileges on a redefined package can still access the package without being regranted the privileges. schema package pl/sql_package_ body is the schema to contain the package. If you omit schema, Oracle creates the package in your current schema. is the name of the package to be created. is the package body, which can contain PL/SQL subprogram bodies or call specifications (declarations of a C or Java routine expressed in PL/SQL). For a list of restrictions on user-defined functions in a package, see "Restrictions on UserDefined Functions" on page 7-286. See Also:
s
Oracle8i Application Developer's Guide - Fundamentals for more information on writing PL/ SQL or C package program units. Oracle8i Java Stored Procedures Developer's Guide for information on JAVA package program units.
s
Examples
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);
SQL Statements
7-349
CREATE PACKAGE BODY
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
7-350 SQL Reference
CREATE PACKAGE BODY
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 IF; 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:
s
the functions HIRE and CREATE_DEPT the procedures REMOVE_EMP, REMOVE_DEPT, INCREASE_SAL, and INCREASE_ COMM
s
These objects are declared in the package specification, so 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_
SQL Statements
7-351
CREATE PACKAGE BODY
COMMS separate from the EMP_MGMT package that calls the INCREASE_COMM procedure. These objects are defined in the package body, so 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. These objects are declared in the package body rather than the package specification, so 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, the function CREATE_DEPT is part of the package, so CREATE_ DEPT can change the value of TOT_DEPTS.
7-352 SQL Reference
CREATE PROCEDURE
CREATE PROCEDURE
Syntax
OR CREATE REPLACE PROCEDURE , IN OUT IN ( argument OUT NOCOPY datatype ) schema . procedure
invoker_rights_clause
IS AS
pl/sql_subprogram_body ; call_spec
invoker_rights_clause::=
CURRENT_USER AUTHID DEFINER
call_spec::=
Java_declaration LANGUAGE C_declaration
Java_declaration::=
JAVA NAME ' string '
SQL Statements
7-353
CREATE PROCEDURE
C_declaration::=
NAME C PARAMETERS ( name LIBRARY parameters ) lib_name WITH CONTEXT
Purpose
To create a standalone stored procedure or a call specification. A procedure is a group of PL/SQL statements that you can call by name. A call specification ("call spec") declares a Java method or a third-generation language (3GL) routine so that it can be called from SQL and PL/SQL. The call spec tells Oracle which Java method to invoke when a call is made. It also tells Oracle what type conversions to make for the arguments and return value. Stored procedures offer advantages in the areas of development, integrity, security, performance, and memory allocation.
7-354 SQL Reference
CREATE PROCEDURE
See Also:
s
Oracle8i Application Developer's Guide - Fundamentals for more information on stored procedures, including how to call stored procedures. "CREATE FUNCTION" on page 7-284 for information specific to functions, which are similar in many ways. "CREATE PACKAGE" on page 7-344 for information on creating packages. (The CREATE PROCEDURE statement creates a procedure as a standalone schema object. You can also create a procedure as part of a package.) "ALTER PROCEDURE" on page 7-67 and "DROP PROCEDURE" on page 7-493 for information on modifying and dropping a standalone procedure. "CREATE LIBRARY" on page 7-316 for more information about shared libraries. Oracle8i Application Developer's Guide - Fundamentals for more information about registering external procedures.
s
s
s
s
s
Prerequisites
Before creating a procedure, the user SYS must run the SQL script DBMSSTDX.SQL. The exact name and location of this script depends on your operating system. To create a procedure in your own schema, you must have the CREATE PROCEDURE system privilege. To create a procedure in another user's schema, you must have CREATE ANY PROCEDURE system privilege. To replace a procedure in another schema, you must have the ALTER ANY PROCEDURE system privilege. To invoke a call spec, you may need additional privileges (for example, EXECUTE privileges on the C library for a C call spec). 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.
SQL Statements
7-355
CREATE PROCEDURE
See Also: PL/SQL User's Guide and Reference or Oracle8i Java Stored
Procedures Developer's Guide for more information on such prerequisites.
Keywords and Parameters
OR REPLACE re-creates the procedure if it already exists. Use this clause to change the definition of an existing procedure without dropping, re-creating, and regranting object privileges previously granted on it. If you redefine a procedure, Oracle recompiles it. For information on recompiling procedures, see "ALTER PROCEDURE" on page 7-67. Users who had previously been granted privileges on a redefined procedure can still access the procedure without being regranted the privileges. If any function-based indexes depend on the package, Oracle marks the indexes DISABLED. schema procedure is the schema to contain the procedure. If you omit schema, Oracle creates the procedure in your current schema. is the name of the procedure to be created. If creating the procedure results in compilation errors, Oracle returns an error. You can see the associated compiler error messages with the SQL*Plus command SHOW ERRORS. argument IN OUT IN OUT 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. specifies that you must specify a value for the argument when calling the procedure. specifies that the procedure passes a value for this argument back to its calling environment after execution. 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. NOCOPY instructs Oracle to pass this argument as fast as possible. This clause can significantly enhance performance when passing a large value like a record, an index-by table, or a varray to an OUT or IN OUT parameter. (IN parameter values are always passed NOCOPY.)
s
When you specify NOCOPY, assignments made to a package variable may show immediately in this parameter (or assignments made to this parameter may show immediately in a package variable) if the package variable is passed as the actual assignment corresponding to this parameter. Similarly, changes made either to this parameter or to another parameter may be visible immediately through both names if the same variable is passed to both. If the procedure is exited with an unhandled exception, any assignment made to this parameter may be visible in the caller's variable.
s
s
7-356 SQL Reference
CREATE PROCEDURE
These effects may or may not occur on any particular call. You should use NOCOPY only when these effects would not matter. datatype is the datatype of the argument. An argument can have any datatype supported by PL/SQL. Datatypes cannot specify length, precision, or scale. For example, VARCHAR2(10) is not valid, but VARCHAR2 is valid. Oracle derives the length, precision, and scale of an argument from the environment from which the procedure is called. invoker_rights_ clause lets you specify whether the procedure executes with the privileges and in the schema of the user who owns it or with the privileges and in the schema of CURRENT_USER. (For information on how CURRENT_USER is determined, see Oracle8i Concepts and Oracle8i Application Developer's Guide - Fundamentals.) This clause also determines how Oracle resolves external names in queries, DML operations, and dynamic SQL statements in the procedure. See Also: PL/SQL User's Guide and Reference. AUTHID CURRENT_USER specifies that the procedure executes with the privileges of CURRENT_ USER. This clause creates an "invoker-rights procedure." This clause also specifies that external names in queries, DML operations, and dynamic SQL statements resolve in the schema of CURRENT_USER. External names in all other statements resolve in the schema in which the procedure resides. AUTHID DEFINER pl/sql_ subprogram_body specifies that the procedure executes with the privileges of the owner of the schema in which the procedure resides, and that external names resolve in the schema where the procedure resides. This is the default.
declares the procedure in a PL/SQL subprogram body. See Also: Oracle8i Application Developer's Guide - Fundamentals for more information on PL/ SQL subprograms. maps a Java or C method name, parameter types, and return type to their SQL counterparts.
s s
call_spec
In Java_declaration, 'string' identifies the Java implementation of the method. For an explanation of the parameters and semantics of the C_declaration, see Oracle8i Application Developer's Guide - Fundamentals.
See Also: Oracle8i Java Stored Procedures Developer's Guide. AS EXTERNAL is an alternative way of declaring a C method. This clause has been deprecated and is supported for backward compatibility only. Oracle Corporation recommends that you use the AS LANGUAGE C syntax.
Examples
The following statement creates the procedure CREDIT in the schema SAM:
CREATE PROCEDURE sam.credit (acc_no IN NUMBER, amount IN NUMBER) AS
SQL Statements
7-357
CREATE PROCEDURE
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 the following arguments: ACC_NO AMOUNT is the number of the bank account to be credited. The argument's datatype is NUMBER. 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. In the following example, external procedure C_FIND_ROOT expects a pointer as a parameter. Procedure FIND_ROOT passes the parameter by reference using the BY REF phrase:
CREATE PROCEDURE find_root ( x IN REAL ) IS LANGUAGE C NAME "c_find_root" LIBRARY c_utils PARAMETERS ( x BY REF );
7-358 SQL Reference
CREATE PROFILE
CREATE PROFILE
Syntax
resource_parameters CREATE PROFILE profile LIMIT password_parameters ;
resource_parameters::=
SESSIONS_PER_USER CPU_PER_SESSION CPU_PER_CALL integer CONNECT_TIME UNLIMITED IDLE_TIME DEFAULT LOGICAL_READS_PER_SESSION LOGICAL_READS_PER_CALL COMPOSITE_LIMIT K M integer PRIVATE_SGA UNLIMITED DEFAULT
SQL Statements
7-359
CREATE PROFILE
password_parameters::=
FAILED_LOGIN_ATTEMPTS PASSWORD_LIFE_TIME expr PASSWORD_REUSE_TIME UNLIMITED PASSWORD_REUSE_MAX DEFAULT PASSWORD_LOCK_TIME PASSWORD_GRACE_TIME function PASSWORD_VERIFY_FUNCTION NULL DEFAULT
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. To specify resource limits for a user, you must:
s
Enable resource limits dynamically with the ALTER SYSTEM statement (see "ALTER SYSTEM" on page 7-102) or with the initialization parameter RESOURCE_LIMIT. (This parameter does not apply to password resources. Password resources are always enabled.) Create a profile that defines the limits using the CREATE PROFILE statement. Assign the profile to the user using the CREATE USER or ALTER USER statement (see "CREATE USER" on page 7-451 and "ALTER USER" on page 7-193).
s
s
Keywords and Parameters
profile is the name of the profile to be created. Use profiles to limit the database resources available to a user for a single call or a single session.
7-360 SQL Reference
CREATE PROFILE
Oracle enforces resource limits in the following ways:
s
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, Oracle returns an error. 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, and 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, leaving the current transaction intact.
s
s
Notes:
s
You can use fractions of days for all parameters that limit time, with days as units. For example, 1 hour is 1/24 and 1 minute is 1/1440. You can specify resource limits for users regardless of whether the resource limits are enabled. However, Oracle does not enforce the limits until you enable them.
s
UNLIMITED
When specified with a resource parameter, indicates that a user assigned this profile can use an unlimited amount of this resource. When specified with a password parameter, indicates that no limit has been set for the parameter. 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. The DEFAULT profile initially defines unlimited resources. You can change those limits with the ALTER PROFILE statement. 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.
DEFAULT
resource_parameters SESSIONS_PER_USER CPU_PER_SESSION CPU_PER_CALL CONNECT_TIME IDLE_TIME limits a user to integer concurrent sessions. limits the CPU time for a session, expressed in hundredth of seconds. limits the CPU time for a call (a parse, execute, or fetch), expressed in hundredths of seconds. limits the total elapsed time of a session, expressed in minutes. limits periods of continuous inactive time during a session, expressed in minutes. Long-running queries and other operations are not subject to this limit.
SQL Statements
7-361
CREATE PROFILE
LOGICAL_READS_PER_ SESSION
specifies the number of data blocks read in a session, including blocks read from memory and disk.
LOGICAL_READS_PER_CALL specifies the number of data blocks read for a call to process a SQL statement (a parse, execute, or fetch). PRIVATE_SGA specifies the amount of private space a session can allocate in the shared pool of the system global area (SGA), expressed in bytes. Use K or M to specify this limit in kilobytes or megabytes. Note: This limit applies only if you are using 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 specifies the total resources cost for a session, expressed in service units. Oracle calculates the total service units as a weighted sum of CPU_PER_SESSION, CONNECT_TIME, LOGICAL_READS_PER_SESSION, and PRIVATE_SGA. For information on how to specify the weight for each session resource, see "ALTER RESOURCE COST" on page 7-73. password_parameters FAILED_LOGIN_ATTEMPTS PASSWORD_LIFE_TIME For a detailed description and explanation of how to use password management and protection, see Oracle8i Administrator's Guide. specifies the number of failed attempts to log in to the user account before the account is locked. limits the number of days the same password can be used for authentication. The password expires if it is not changed within this period, and further connections are rejected. specifies the number of days before which a password cannot be reused. If you set PASSWORD_REUSE_TIME to an integer value, then you must set PASSWORD_REUSE_MAX to UNLIMITED. specifies the number of password changes required before the current password can be reused. If you set PASSWORD_REUSE_MAX to an integer value, then you must set PASSWORD_REUSE_TIME to UNLIMITED. specifies the number of days an account will be locked after the specified number of consecutive failed login attempts. specifies the number of days after the grace period begins during which a warning is issued and login is allowed. If the password is not changed during the grace period, the password expires. allows a PL/SQL password complexity verification script to be passed as an argument to the CREATE PROFILE statement. Oracle provides a default script, but you can create your own routine or use third-party software instead. function is the name of the password complexity verification routine.
PASSWORD_REUSE_TIME
PASSWORD_REUSE_MAX
PASSWORD_LOCK_TIME PASSWORD_GRACE_TIME
PASSWORD_VERIFY_ FUNCTION
7-362 SQL Reference
CREATE PROFILE
NULL Restrictions on password parameters:
s
indicates that no password verification is performed.
If PASSWORD_REUSE_TIME is set to an integer value, PASSWORD_REUSE_MAX must be set to UNLIMITED. If PASSWORD_REUSE_MAX is set to an integer value, PASSWORD_REUSE_TIME must be set to UNLIMITED. If both PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX are set to UNLIMITED, then Oracle uses neither of these password resources. If PASSWORD_REUSE_MAX is set to DEFAULT and PASSWORD_REUSE_TIME is set to UNLIMITED, then Oracle uses the PASSWORD_REUSE_MAX value defined in the DEFAULT profile. If PASSWORD_REUSE_TIME is set to DEFAULT and PASSWORD_REUSE_MAX is set to UNLIMITED, then Oracle uses the PASSWORD_REUSE_TIME value defined in the DEFAULT profile. If both PASSWORD_REUSE_TIME and PASSWORD_REUSE_MAX are set to DEFAULT, then Oracle uses whichever value is defined in the DEFAULT profile.
s
s
s
s
Examples
The following statement creates the profile SYSTEM_MANAGER:
CREATE PROFILE system_manager LIMIT SESSIONS_PER_USER CPU_PER_SESSION CPU_PER_CALL CONNECT_TIME LOGICAL_READS_PER_SESSION LOGICAL_READS_PER_CALL PRIVATE SGA COMPOSITE_LIMIT UNLIMITED UNLIMITED 3000 45 DEFAULT 1000 15K 5000000;
If you then assign the SYSTEM_MANAGER profile to a user, the user is subject to the following limits in subsequent sessions:
s
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 read from memory and disk is subject to the limit specified in the DEFAULT profile.
s
s
s
s
SQL Statements
7-363
CREATE PROFILE
s
A single call made by the user cannot read more than 1000 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 statement. Since the SYSTEM_MANAGER profile omits a limit for IDLE_TIME and for password limits, the user is subject to the limits on these resources specified in the DEFAULT profile.
s
s
s
The following statement creates the profile PROF:
CREATE PROFILE prof LIMIT PASSWORD_REUSE_MAX DEFAULT PASSWORD_REUSE_TIME UNLIMITED;
The following statement creates profile MYPROFILE with password profile limits values set:
CREATE PROFILE myprofile LIMIT FAILED_LOGIN_ATTEMPTS 5 PASSWORD_LIFE_TIME 60 PASSWORD_REUSE_TIME 60 PASSWORD_REUSE_MAX UNLIMITED PASSWORD_VERIFY_FUNCTION verify_function PASSWORD_LOCK_TIME 1/24 PASSWORD_GRACE_TIME 10;
7-364 SQL Reference
CREATE ROLE
7SQL Statements
CREATE ROLE
Syntax
NOT IDENTIFIED BY IDENTIFIED password
EXTERNALLY GLOBALLY
CREATE
ROLE
role
;
Purpose
To create a role, which 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 and then grant the role to a user. The user can then enable the role and exercise the privileges granted by the role. A role contains all privileges granted to the role and all privileges of other roles granted to it. A new role is initially empty. You add privileges to a role with the GRANT statement. For information on granting roles, see "GRANT system_ privileges_and_roles" on page 7-519. For information on enabling roles, see "ALTER USER" on page 7-193. When you create a role that is NOT IDENTIFIED or is IDENTIFIED EXTERNALLY or BY password, Oracle grants you the role with ADMIN OPTION. However, when you create a role IDENTIFIED GLOBALLY, Oracle does not grant you the role. For information on modifying a role, see"ALTER ROLE" on page 7-76. For information on removing a role from the database, see "DROP ROLE" on page 7-495. For information on enabling and disabling roles for the current session, see "SET ROLE" on page 7-600. For a detailed description and explanation of using global roles, see Oracle8i Distributed Database Systems.
Prerequisites
You must have CREATE ROLE system privilege.
SQL Statements
7-365
CREATE ROLE
Keywords and Parameters
role is the name of the role to be created. Oracle recommends that the role contain at least one single-byte character regardless of whether the database character set also contains multibyte characters. Some roles are defined by SQL scripts provided on your distribution media. For a list of these predefined roles, see "GRANT system_privileges_and_roles" on page 7-519. NOT IDENTIFIED IDENTIFIED indicates that this role is authorized by the database and that no password is required to enable the role. indicates that a user must be authorized by the specified method before the role is enabled with the SET ROLE statement: BY password creates a local user and indicates that the user must specify the password to Oracle when enabling the role. The password can contain only single-byte characters from your database character set regardless of whether this character set also contains multibyte characters. creates an external user and indicates that a user must be authorized by an external service (such as an operating system or third-party service) before enabling the role. Depending on the operating system, the user may have to specify a password to the operating system before the role is enabled. GLOBALLY creates a global user and indicates that a user must be authorized to use the role by the enterprise directory service before the role is enabled with the SET ROLE statement, or at login.
EXTERNALLY
If you omit both the NOT IDENTIFIED clause and the IDENTIFIED clause, the role defaults to NOT IDENTIFIED.
Examples
The following statement creates global role VENDOR:
CREATE ROLE vendor IDENTIFIED GLOBALLY;
The following statement creates the role TELLER:
CREATE ROLE teller IDENTIFIED BY cashflow;
Users who are subsequently granted the TELLER role must specify the password CASHFLOW to enable the role with the SET ROLE statement.
7-366 SQL Reference
CREATE ROLLBACK SEGMENT
CREATE ROLLBACK SEGMENT
Syntax
PUBLIC CREATE ROLLBACK SEGMENT rollback_segment
TABLESPACE storage_clause
tablespace
;
storage_clause: See "storage_clause" on page 7-605.
Purpose
To create a rollback segment. A rollback segment is an object that Oracle uses to store data necessary to reverse, or undo, changes made by transactions. For information on altering a rollback segment, see "ALTER ROLLBACK SEGMENT" on page 7-78. For information on removing a rollback segment, see "DROP ROLLBACK SEGMENT" on page 7-496.
Prerequisites
You must have CREATE ROLLBACK SEGMENT system privilege.
Keyword and Parameters
PUBLIC specifies that the rollback segment is public and is available to any instance. If you omit this clause, the rollback segment is private and is available only to the instance naming it in its initialization parameter ROLLBACK_SEGMENTS. is the name of the rollback segment to be created. identifies the tablespace in which the rollback segment is created. If you omit this clause, Oracle creates the rollback segment in the SYSTEM tablespace. Restriction: You cannot create a rollback segment in a tablespace that is system managed (that is, during creation you specified EXTENT MANAGEMENT LOCAL AUTOALLOCATE). See "CREATE TABLESPACE" on page 4-419.
rollback_segment TABLESPACE
SQL Statements
7-367
CREATE ROLLBACK SEGMENT
Notes:
s
A tablespace can have multiple rollback segments. Generally, multiple rollback segments improve performance. The tablespace must be online for you to add a rollback segment to it. When you create a rollback segment, it is initially offline. To make it available for transactions by your Oracle instance, bring it online using the ALTER ROLLBACK SEGMENT statement. To bring it online automatically whenever you start up the database, add the segment's name to the value of the ROLLBACK_SEGMENTS initialization parameter.
s s
See also: Oracle8i Administrator's Guide for more information on creating rollback segments and making them available. storage_clause specifies the characteristics for the rollback segment. See the "storage_clause" on page 7-605. Notes:
s
The OPTIMAL parameter of the storage_clause is of particular interest, because it applies only to rollback segments. You cannot specify the PCTINCREASE parameter of the storage_clause with CREATE ROLLBACK SEGMENT.
s
Examples
The following statement creates a rollback segment with default storage values in the system tablespace:
CREATE ROLLBACK SEGMENT rbs_2 TABLESPACE system;
The above statement is equivalent to the following:
CREATE ROLLBACK SEGMENT rbs_2 TABLESPACE system STORAGE ( INITIAL 10K NEXT 10K MAXEXTENTS UNLMIITED);
7-368 SQL Reference
CREATE SCHEMA
CREATE SCHEMA
Syntax
create_table_statement CREATE SCHEMA AUTHORIZATION schema create_view_statement grant_statement ;
Purpose
To create multiple tables and views and perform multiple grants in a single transaction. To execute a CREATE SCHEMA 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.
Note: This statement does not actually create a schema. Oracle
automatically creates a schema when you create a user (see "CREATE USER" on page 7-451). This statement lets you populate your schema with tables and views and grant privileges on those objects without having to issue multiple SQL statements in multiple transactions.
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.
Keyword and Parameters
schema create_table_ statement is the name of the schema. The schema name must be the same as your Oracle username. is a CREATE TABLE statement to be issued as part of this CREATE SCHEMA statement. See "CREATE TABLE" on page 4-381. Do not end this statement with a semicolon (or other terminator character).
SQL Statements
7-369
CREATE SCHEMA
create_view_ statement grant_statement
is a CREATE VIEW statement to be issued as part of this CREATE SCHEMA statement. See "CREATE VIEW" on page 7-456. Do not end this statement with a semicolon (or other terminator character). is a GRANT object_privileges statement to be issued as part of this CREATE SCHEMA statement. See "GRANT object_privileges" on page 7-532. Do not end this statement with a semicolon (or other terminator character).
The CREATE SCHEMA statement supports the syntax of these statements only as defined by standard SQL, rather than the complete syntax supported by Oracle. The order in which you list the CREATE TABLE, CREATE VIEW, and GRANT statements is unimportant. The statements within a CREATE SCHEMA statement can reference existing objects or objects you create in other statements within the same CREATE SCHEMA statement. Restriction: The syntax of the parallel_clause is allowed for a CREATE TABLE statement in CREATE SCHEMA, but parallelism is not used when creating the objects. See also: The parallel_clause of "CREATE TABLE" on page 4-381.
Example
The following statement creates a schema named BLAIR for the user BLAIR, creates the table SOX, creates the view RED_SOX, and grants SELECT privilege on the RED_ SOX view to the user WAITES.
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;
7-370 SQL Reference
CREATE SEQUENCE
CREATE SEQUENCE
Syntax
INCREMENT START MAXVALUE NOMAXVALUE MINVALUE NOMINVALUE CYCLE NOCYCLE CACHE NOCACHE ORDER schema CREATE SEQUENCE . sequence NOORDER ; integer integer WITH integer BY integer
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. 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 acquires may have gaps because sequence numbers are being generated by the other user. One user can never acquire 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.
SQL Statements
7-371
CREATE SEQUENCE
Sequence numbers are generated independently of tables, so 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. Once a sequence is created, you can access its values in SQL statements with the CURRVAL pseudocolumn (which returns the current value of the sequence) or the NEXTVAL pseudocolumn (which increments the sequence and returns the new value).
See Also:
s
"Pseudocolumns" on page 2-56 for more information on using the above pseudocolumns. "ALTER SEQUENCE" on page 7-81 or "DROP SEQUENCE" on page 7-497 for information on modifying or dropping a sequence.
s
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.
Keywords and Parameters
schema sequence is the schema to contain the sequence. If you omit schema, Oracle creates the sequence in your own schema. is the name of the sequence to be created.
7-372 SQL Reference
CREATE SEQUENCE
If you specify none of the following 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.
s
To create a sequence that increments without bound, for ascending sequences, omit the MAXVALUE parameter or specify NOMAXVALUE. For descending sequences, omit the MINVALUE parameter or specify the NOMINVALUE. To create a sequence that stops at a predefined limit, for an ascending sequence, specify a value for the MAXVALUE parameter. For a descending sequence, specify a value for the MINVALUE parameter. Also specify the NOCYCLE. 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. If you do not specify MINVALUE, then it defaults to NOMINVALUE (that is, the value 1). specifies the interval between sequence numbers. This integer value can be any positive or negative integer, but it cannot be 0. This value can have 28 or fewer digits. The absolute of this value must be less than the difference of MAXVALUE and MINVALUE. 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. specifies the first sequence number to be generated. Use this clause 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. This integer value can have 28 or fewer digits. Note: This value is not necessarily the value to which an ascending cycling sequence cycles after reaching its maximum or minimum value.
s
s
INCREMENT BY
START WITH
MAXVALUE
specifies the maximum value the sequence can generate. This integer value can have 28 or fewer digits. MAXVALUE must be equal to or greater than START WITH and must be greater than MINVALUE. specifies a maximum value of 1027 for an ascending sequence or -1 for a descending sequence. This is the default. specifies the sequence's minimum value. This integer value can have 28 or fewer digits. MINVALUE must be less than or equal to START WITH and must be less than MAXVALUE. specifies a minimum value of 1 for an ascending sequence or -(1026) for a descending sequence. This is the default. 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. specifies that the sequence cannot generate more values after reaching its maximum or minimum value. This is the default.
NOMAXVALUE MINVALUE NOMINVALUE CYCLE
NOCYCLE
SQL Statements
7-373
CREATE SEQUENCE
CACHE
specifies how many values of the sequence Oracle preallocates and keeps in memory for faster access. This integer value can have 28 or fewer digits. 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. You cannot cache more values than will fit in a given cycle of sequence numbers. Therefore, the maximum value allowed for CACHE must be less than the value determined by the following formula: (CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT) If a system failure occurs, all cached sequence values that have not been used in committed DML statements are lost. The potential number of lost values is equal to the value of the CACHE parameter.
NOCACHE
specifies that values of the sequence are not preallocated.
If you omit both CACHE and NOCACHE, Oracle caches 20 sequence numbers by default. ORDER guarantees that sequence numbers are generated in order of request. You may want to use this clause if you are using the sequence numbers as timestamps. Guaranteeing order is usually not important for sequences used to generate primary keys. ORDER is necessary only 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. NOORDER does not guarantee sequence numbers are generated in order of request. This is the default.
Example
The following 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.
7-374 SQL Reference
CREATE SNAPSHOT
CREATE SNAPSHOT
In Oracle8i, "snapshots" are synonymous with "materialized views." Please see "CREATE MATERIALIZED VIEW / SNAPSHOT" on page 7-318.
SQL Statements
7-375
CREATE SNAPSHOT LOG
CREATE SNAPSHOT LOG
In Oracle8i, "snapshots" are synonymous with "materialized views." Please see "CREATE MATERIALIZED VIEW LOG / SNAPSHOT LOG" on page 7-333.
7-376 SQL Reference
CREATE SYNONYM
CREATE SYNONYM
Syntax
PUBLIC CREATE schema FOR . object SYNONYM @ dblink ; schema . synonym
Purpose
To create a synonym. A synonym is an alternative name for a table, view, sequence, procedure, stored function, package, materialized view, Java class schema object, or another synonym. For general information on synonyms, see Oracle8i Concepts. 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. Table 44 lists the SQL statements in which you can refer to synonyms.
Table 74 Using Synonyms
DML Statements SELECT INSERT UPDATE DELETE EXPLAIN PLAN LOCK TABLE DDL Statements AUDIT NOAUDIT GRANT REVOKE COMMENT
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.
SQL Statements
7-377
CREATE SYNONYM
To create a PUBLIC synonym, you must have CREATE PUBLIC SYNONYM system privilege.
Keywords and Parameters
PUBLIC creates a public synonym. Public synonyms are accessible to all users. Oracle uses a public synonym only when resolving references to an object if the object is not prefaced by a schema and the object is not followed by a database link. If you omit this clause, the synonym is private and is accessible only within its schema. A private synonym name must be unique in its schema. schema is the schema to contain the synonym. If you omit schema, Oracle creates the synonym in your own schema. You cannot specify a schema for the synonym if you have specified PUBLIC. is the name of the synonym to be created. CAUTION: The functional maximum length of the synonym name is 32 bytes. Names longer than 30 bytes are permitted for Java functionality only. If you specify a name longer than 30 bytes, Oracle encrypts the name and places a representation of the encryption in the data dictionary. The actual encryption is not accessible, and you cannot use either your original specification or the data dictionary representation as the synonym name. FOR identifies the object for which the synonym is created. If you do not qualify object with schema, Oracle assumes that the schema object is in your own schema. The schema object can be of the following types:
s s s s s s s
synonym
table or object table view or object view sequence stored procedure, function, or package materialized view Java class schema object synonym
The schema object need not currently exist and you need not have privileges to access the object. Restrictions:
s s
The schema object cannot be contained in a package. You cannot create a synonym for an object type.
7-378 SQL Reference
CREATE SYNONYM
dblink
You can use a complete or partial dblink to create a synonym for a schema object on a remote database where the object is located. 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. See Also:
s
"Referring to Objects in Remote Databases" on page 2-79 for more information on referring to database links. "CREATE DATABASE LINK" on page 7-273 for more information on creating database links.
s
If you omit dblink, Oracle assumes the object is located on the local database. Restriction: You cannot specify dblink for a Java class synonym.
Examples
Oracle attempts to resolve references to objects at the schema level before resolving them at the PUBLIC synonym level. 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;
To define the synonym MARKET for the table MARKET_RESEARCH in the schema SCOTT, issue the following statement:
CREATE SYNONYM market FOR scott.market_research;
To create a PUBLIC synonym for the EMP table in the schema SCOTT on the remote SALES database, you could issue the following statement:
CREATE PUBLIC SYNONYM emp FOR scott.emp@sales;
SQL Statements
7-379
CREATE SYNONYM
A synonym may have the same name as the base table, provided the base table is contained in another schema.
7-380 SQL Reference
CREATE TABLE
CREATE TABLE
Syntax
relational_table:
GLOBAL CREATE TEMPORARY TABLE DELETE ON ( relational_properties ) COMMIT PRESERVE ROWS schema . table
physical_properties
table_properties ;
object_table:
GLOBAL CREATE schema OF . object_type DELETE ON COMMIT PRESERVE OID_clause OID_index_clause physical_properties table_properties ; ROWS TEMPORARY TABLE ( object_properties ) schema . table
relational_properties::=
, DEFAULT column datatype expr column_ref_constraint column_constraint
table_constraint table_ref_constraint
SQL Statements
7-381
CREATE TABLE
object properties::=
column attribute table_constraint table_ref_constraint
DEFAULT
expr
column_ref_constraint
column_constraint
physical_properties::=
segment_attributes_clause segment_attributes_clause HEAP ORGANIZATION INDEX index_organized_table_clause , CLUSTER cluster ( column ) LOB_storage_clause varray_storage_clause nested_table_storage_clause
table_properties::=
range_partitioning_clause hash_partitioning_clause composite_partitioning_clause CACHE NOCACHE MONITORING NOMONITORING
row_movement_clause
parallel_clause
enable_disable_clause
AS
subquery
subquery::= See "SELECT and Subqueries" on page 7-569. table_constraint, column_constraint, table_ref_constraint, column_ref_constraint, constraint_state: See the "constraint_clause" on page 7-233
7-382 SQL Reference
CREATE TABLE
OID_clause::=
SYSTEM OBJECT IDENTIFIER IS PRIMARY KEY GENERATED
OID_index_clause::=
index OIDINDEX (
physical_attributes_clause ) TABLESPACE tablespace
segment_attributes_clause::=
physical_attributes_clause TABLESPACE LOGGING NOLOGGING tablespace
row_movement_clause::=
ENABLE ROW DISABLE MOVEMENT
SQL Statements
7-383
CREATE TABLE
physical_attributes_clause::=
PCTFREE PCTUSED INITRANS MAXTRANS storage_clause
integer integer integer integer
storage_clause: See the "storage_clause" on page 7-605. index_organized_table_clause::=
segment_attributes_clause PCTTHRESHOLD compression_clause integer
index_organized_overflow_clause
compression_clause::=
integer COMPRESS NOCOMPRESS
index_organized_overflow_clause::=
INCLUDING column_name OVERFLOW segment_attributes_clause
7-384 SQL Reference
CREATE TABLE
LOB_storage_clause::=
, ( LOB ( LOB_item ) STORE AS LOB_item ) STORE AS ( LOB_parameters ( ) )
LOB_segname LOB_segname (
LOB_parameters
LOB_parameters
)
LOB_parameters::=
TABLESPACE ENABLE
tablespace
STORAGE DISABLE storage_clause CHUNK integer integer
IN
ROW
PCTVERSION CACHE
LOGGING NOCACHE CACHE READS NOLOGGING
varray_storage_clause::=
LOB_segname VARRAY varray_item STORE AS LOB LOB_segname ( LOB_parameters ) ( LOB_parameters )
SQL Statements
7-385
CREATE TABLE
nested_table_storage_clause::=
NESTED TABLE nested_item STORE AS storage_table
physical_properties ( ( object_properties ) )
LOCATOR RETURN AS VALUE
range_partitioning_clause::=
, PARTITION BY RANGE ( column_list ) ( partition_definition )
composite_partitioning_clause::=
, ( partition_definition )
subpartition_clause PARTITION BY RANGE ( column_list )
partition_definition::=
partition PARTITION segment_attributes_clause COMPRESS NOCOMPRESS OVERFLOW segment_attributes_clause VALUES LESS THAN ( value_list )
LOB_storage_clause varray_storage_clause partition_level_subpartitioning
7-386 SQL Reference
CREATE TABLE
subpartition_clause::=
, SUBPARTITION BY HASH ( column_list ) , STORE SUBPARTITIONS quantity IN ( tablespace )
partition_level_subpartitioning::=
, STORE SUBPARTITIONS quantity , subpartition ( SUBPARTITION hash_partitioning_storage_clause ) IN ( tablespace )
hash_partitioning_clause::=
PARTITION BY HASH ( column_list )
, STORE PARTITIONS quantity , partition ( PARTITION hash_partitioning_storage_clause ) IN ( tablespace )
SQL Statements
7-387
CREATE TABLE
hash_partitioning_storage_clause::=
TABLESPACE tablespace
LOB VARRAY
(
LOB_item varray_item
)
STORE AS
AS LOB
( (
TABLESPACE TABLESPACE
tablespace tablespace
) )
STORE
parallel_clause::=
NOPARALLEL integer PARALLEL
enable_disable_clause::=
, UNIQUE PRIMARY DISABLE CONSTRAINT constraint schema using_index_clause EXCEPTIONS INTO . table CASCADE ( KEY column )
VALIDATE ENABLE NOVALIDATE
7-388 SQL Reference
CREATE TABLE
using_index_clause::=
LOCAL global_index_clause PCTFREE INITRANS MAXTRANS TABLESPACE storage_clause NOSORT LOGGING NOLOGGING USING INDEX integer integer integer tablespace
global_index_clause::=
, GLOBAL PARTITION BY RANGE ( column_list ) ( global_partition_clause )
global_partition_clause::=
partition PARTITION physical_attributes_clause TABLESPACE LOGGING NOLOGGING VALUES LESS THAN ( value_list ) tablespace
SQL Statements
7-389
CREATE TABLE
Purpose
To create a relational table, the basic structure to hold user data. To create an object table or a table that uses an object type for a column definition. An object table is a table explicitly defined to hold object instances of a particular type. You can also create an object type and then use it in a column when creating a relational table. Tables are created with no data unless a query is specified. You can add rows to a table with the INSERT statement. After creating a table, you can define additional columns, partitions, and integrity constraints with the ADD clause of the ALTER TABLE statement. You can change the definition of an existing column or partition with the MODIFY clause of the ALTER TABLE statement.
See also: Oracle8i Application Developer's Guide - Fundamentals and "CREATE TYPE" on page 7-437 for more information about creating objects.
Prerequisites
To create a relational table in your own schema, you must have 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. In addition to the table privileges above, to create a table that uses types, the owner of the table must have the EXECUTE object privilege in order to access all types referenced by the table, or you must have the EXECUTE ANY TYPE system privilege. These privileges must be granted explicitly and not acquired through a role. Additionally, if the table owner intends to grant access to the table to other users, the owner must have been granted the EXECUTE privileges to the referenced types with the GRANT OPTION, or have the EXECUTE ANY TYPE system privilege with the ADMIN OPTION. Without these privileges, the table owner has insufficient privileges to grant access on the table to other users. To enable a UNIQUE or PRIMARY KEY constraint, you must have the privileges necessary to create an index on the table. You need these privileges because Oracle creates an index on the columns of the unique or primary key in the schema containing the table.
7-390 SQL Reference
CREATE TABLE
See Also:
s
"CREATE INDEX" on page 7-291. Oracle8i Application Developer's Guide - Fundamentals for more information about the privileges required to create tables using types.
s
Keywords and Parameters
GLOBAL TEMPORARY specifies that the table is temporary and that its definition is visible to all sessions. The data in a temporary table is visible only to the session that inserts the data into the table. A temporary table has a definition that persists the same as the definitions of regular tables, but it contains either session-specific or transaction-specific data. You specify whether the data is session- or transaction-specific with the ON COMMIT keywords (below). See Also: Oracle8i Concepts for more information on temporary tables. Restrictions:
s s
Temporary tables cannot be partitioned, index-organized, or clustered. You cannot specify any referential integrity (foreign key) constraints on temporary tables. Temporary tables cannot contain columns of nested table or varray type. You cannot specify the following clauses of the LOB_storage_clause: TABLESPACE, storage_clause, LOGGING or NOLOGGING, MONITORING or NOMONITORING, or LOB_ index_clause. Parallel DML and parallel queries are not supported for temporary tables. (Parallel hints are ignored. Specification of the parallel_clause returns an error.) You cannot specify the segment_attributes_clause, nested_table_storage_clause, or parallel_ clause. Distributed transactions are not supported for temporary tables.
s s
s
s
s
schema table OF object_type
is the schema to contain the table. If you omit schema, Oracle creates the table in your own schema. is the name of the table (or object table) to be created. explicitly creates an object table of type object_type. The columns of an object table correspond to the top-level attributes of type object_type. Each row will contain an object instance, and each instance will be assigned a unique, system-generated object identifier (OID) when a row is inserted. If you omit schema, Oracle creates the object table in your own schema. See Also: "CREATE TYPE" on page 7-437 for more information about creating objects.
SQL Statements
7-391
CREATE TABLE
Objects residing in an object table are referenceable. See Also: "User-Defined Type Categories" on page 2-30, "User-Defined Functions" on page 4-118, "Expressions" on page 5-1, "CREATE TYPE" on page 7-437, and Oracle8i Administrator's Guide for more information about using REFs. column specifies the name of a column of the table. If you also specify AS subquery, you can omit column and datatype unless you are creating an index-organized table (IOT). If you specify AS subquery when creating an IOT, you must specify column, and you must omit datatype. The absolute maximum number of columns in a table is 1000. However, when you create an object table (or a relational table with columns of object, nested table, varray, or REF type), Oracle maps the columns of the user-defined types to relational columns, creating in effect "hidden columns" that count toward the 1000-column limit. For details on how Oracle calculates the total number of columns in such a table, please refer to Oracle8i Administrator's Guide. attribute datatype specifies the qualified column name of an item in an object. is the datatype of a column. Oracle-supplied datatypes are defined in "Datatypes" on page 2-9. Restrictions:
s
You cannot specify a LOB column or a column of type VARRAY for a partitioned indexorganized table. The datatypes for nonpartitioned index-organized tables are not restricted. You can specify a column of type ROWID, but Oracle does not guarantee that the values in such columns are valid rowids.
s
You can omit datatype:
s
If you also specify AS subquery. (If you are creating an index-organized table and you specify AS subquery, you must omit the datatype.) If the statement also designates the column as part of a foreign key in a referential integrity constraint. (Oracle automatically assigns to the column the datatype of the corresponding column of the referenced key of the referential integrity constraint.)
s
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 "Expressions" on page 5-1. Restriction: A DEFAULT expression cannot contain references to other columns, the pseudocolumns CURRVAL, NEXTVAL, LEVEL, and ROWNUM, or date constants that are not fully specified.
7-392 SQL Reference
CREATE TABLE
table_ref_ constraint and column_ref_ constraint column_constraint
These clauses let you further describe a column of type REF. The only difference between these clauses is that you specify table_ref from the table level, so you must identify the REF column or attribute you are defining. You specify column_ref after you have already identified the REF column or attribute. For syntax and description of these constraints, see the "constraint_clause" on page 7-233. defines an integrity constraint as part of the column definition. See the syntax description of column_constraint in the "constraint_clause" on page 7-233. You can create UNIQUE, PRIMARY KEY, and REFERENCES constraints on scalar attributes of object type columns. You can also create NOT NULL constraints on object type columns, and CHECK constraints that reference object type columns or any attribute of an object type column.
table_constraint
defines an integrity constraint as part of the table definition. See the syntax description of table_constraint in the "constraint_clause" on page 7-233. Note: You must specify a PRIMARY KEY constraint for an index-organized table, and it cannot be DEFERRABLE.
segment_attributes_clause: physical_ attributes_clause specifies the value of the PCTFREE, PCTUSED, INITRANS, and MAXTRANS parameters and the storage characteristics of the table.
s
For a nonpartitioned table, each parameter and storage characteristic you specify determines the actual physical attribute of the segment associated with the table. For partitioned tables, the value you specify for the parameter or storage characteristic is the default physical attribute of the segments associated with all partitions specified in this CREATE statement (and in subsequent ALTER TABLE ... ADD PARTITION statements), unless you explicitly override that value in the PARTITION clause of the statement that creates the partition.
s
PCTFREE
specifies the percentage of space in each data block of the table, object table OID index, or partition reserved for future updates to the table's rows. The value of PCTFREE must be a value from 0 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 PARTITION description and in the statements that create and alter clusters, indexes, materialized views, and materialized view logs. The combination of PCTFREE and PCTUSED determines whether new rows will be inserted 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, object table OID index, or index-organized table overflow data segment. A block becomes a candidate for row insertion when its used space falls below PCTUSED. PCTUSED is specified as a positive integer from 0 to 99 and defaults to 40.
SQL Statements
7-393
CREATE TABLE
PCTUSED has the same function in the PARTITION description and in the statements that create and alter clusters, materialized views, and materialized view logs. PCTUSED is not a valid table storage characteristic for an index-organized table (ORGANIZATION INDEX). The sum of PCTFREE and PCTUSED must be equal to or less than 100. You can use PCTFREE and PCTUSED together to utilize space within a table more efficiently. For information on the performance effects of different values PCTUSED and PCTFREE, see Oracle8i Designing and Tuning for Performance. INITRANS specifies the initial number of transaction entries allocated within each data block allocated to the table, object table OID index, partition, LOB index segment, or overflow data segment. 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 the PARTITION description, clusters, indexes, materialized views, and materialized view 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, object table OID index, partition, LOB index segment, or indexorganized overflow data segment. 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 of 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 the PARTITION description, clusters, materialized views, and materialized view logs as in tables. storage_clause specifies the storage characteristics for the table, object table OID index, partition, LOB storage, LOB index segment, or index-organized table overflow data segment. 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 7-605. specifies the tablespace in which Oracle creates the table, object table OID index, partition, LOB storage, LOB index segment, or index-organized table overflow data segment. If you omit TABLESPACE, then Oracle creates that item in the default tablespace of the owner of the schema containing the table.
TABLESPACE
7-394 SQL Reference
CREATE TABLE
For heap-organized tables with one or more LOB columns, if you omit the TABLESPACE clause for LOB storage, Oracle creates the LOB data and index segments in the tablespace where the table is created. However, for an index-organized table with one or more LOB columns, if you omit TABLESPACE, the LOB data and index segments are created in the tablespace in which the primary key index segment of the index-organized table is created. For nonpartitioned tables, the value specified for TABLESPACE is the actual physical attribute of the segment associated with the table. For partitioned tables, the value specified for TABLESPACE is the default physical attribute of the segments associated with all partitions specified in the CREATE statement (and on subsequent ALTER TABLE ... ADD PARTITION statements), unless you specify TABLESPACE in the PARTITION description. See Also: "CREATE TABLESPACE" on page 4-419 for more information on tablespaces. LOGGING | NOLOGGING specifies whether the creation of the table (and any indexes required because of constraints), partition, or LOB storage characteristics will be logged in the redo log file.The logging attribute of the table is independent of that of its indexes. This attribute also specifies that subsequent Direct Loader (SQL*Loader) and direct-load INSERT operations against the table, partition, or LOB storage are logged (LOGGING) or not logged (NOLOGGING). For a table or table partition, if you omit LOGGING|NOLOGGING, the logging attribute of the table or table partition defaults to the logging attribute of the tablespace in which it resides. For LOBs, if you omit LOGGING|NOLOGGING,
s
If you specify CACHE, then LOGGING is used (because you cannot have CACHE NOLOGGING). If you specify NOCACHE or CACHE READS, the logging attribute defaults to the logging attribute of the tablespace in which it resides.
s
NOLOGGING does not apply to LOBs that are stored inline with row data. That is, if you specify NOLOGGING for LOBs with values less than 4000 bytes and you have not disabled STORAGE IN ROW, Oracle ignores the NOLOGGING specification and treats the LOB data the same as other table data. For nonpartitioned tables, the value specified for LOGGING is the actual physical attribute of the segment associated with the table. For partitioned tables, the logging attribute value specified is the default physical attribute of the segments associated with all partitions specified in the CREATE statement (and in subsequent ALTER TABLE ... ADD PARTITION statements), unless you specify LOGGING|NOLOGGING in the PARTITION description. In NOLOGGING mode, data is modified with minimal logging (to mark new extents INVALID and to record dictionary changes). When applied during media recovery, the extent invalidation records mark a range of blocks as logically corrupt, because the redo data is not fully logged. Therefore, if you cannot afford to lose this table, you should take a backup after the NOLOGGING operation.
SQL Statements
7-395
CREATE TABLE
The size of a redo log generated for an operation in NOLOGGING mode is significantly smaller than the log generated with the LOGGING attribute set. If the database is run in ARCHIVELOG mode, media recovery from a backup taken before the LOGGING operation restores the table. However, media recovery from a backup taken before the NOLOGGING operation does not restore the table. See Also: Oracle8i Concepts and Oracle8i Administrator's Guide for more information about logging and parallel DML. RECOVERABLE | UNRECOVERABLE These keywords are deprecated and have been replaced with LOGGING and NOLOGGING, respectively. Although RECOVERABLE and UNRECOVERABLE are supported for backward compatibility, Oracle Corporation strongly recommends that you use the LOGGING and NOLOGGING keywords. Restrictions:
s s s
You cannot specify RECOVERABLE for partitioned tables or LOB storage characteristics. You cannot specify UNRECOVERABLE for a partitioned or index-organized tables. You can specify UNRECOVERABLE only with AS subquery.
ORGANIZATION HEAP ORGANIZATION INDEX index_organized_ table_clause
specifies that the data rows of table are stored in no particular order. This is the default. specifies that table is created as an index-organized table. In an index-organized table, the data rows are held in an index defined on the primary key for the table. specifies that Oracle should maintain the table rows (both primary key column values and non-key column values) in a B*-tree index built on the primary key. Index-organized tables are therefore best suited for primary key-based access and manipulation. An indexorganized table is an alternative to
s
A nonclustered table indexed on the primary key by using the CREATE INDEX statement A clustered table stored in an indexed cluster that has been created using the CREATE CLUSTER statement that maps the primary key for the table to the cluster key
s
Restrictions:
s s
You cannot specify a column of type ROWID for an index-organized table. A partitioned index-organized table cannot contain columns of LOB or varray type. (This restriction does not apply to nonpartitioned index-organized tables.)
Note: You must specify a primary key for an index-organized table, because the primary key uniquely identifies a row. The primary key cannot be DEFERRABLE. Use the primary key instead of the rowid for directly accessing index-organized rows.
7-396 SQL Reference
CREATE TABLE
PCTTHRESHOLD integer
specifies the percentage of space reserved in the index block for an index-organized table row. Any portion of the row that exceeds the specified threshold is stored in the overflow segment. PCTTHRESHOLD must be a value from 1 to 50. Restriction:
s s
PCTTHRESHOLD must be large enough to hold the primary key. You cannot specify PCTTHRESHOLD for individual partitions of an index-organized table.
OVERFLOW
specifies that index-organized table data rows exceeding the specified threshold are pl