Вы находитесь на странице: 1из 74

SQL Language Quick Reference

This Reference briefly describes elements of SQL and the ORACLE7 data dictionary. For details on SQL, refer to the SQL Language Reference Manual. For information on the data dictionary see the ORACLE7 Server Administrators Guide or the ORACLE7 Server Application Developers Guide. For information on Trusted ORACLE, see the Trusted ORACLEL7 Server Administrators Guide.

Index of Major Sections


Functions Format Models Pseudocolumns Datatypes Names and Reserved Words 3 8 12 12 13 Privileges Expressions and Conditions Operators SQL Commands Embedded SQL 15 Comments 19 Special Tables Data Dictionary Views 22 Dynamic Tables 24 64 63 64 65 71

Index of Commands
ALTER CLUSTER ALTER DATABASE ALTER FUNCTION ALTER INDEX ALTER PACKAGE ALTER PROCEDURE ALTER PROFILE ALTER RESOURCE COST ALTER ROLE ALTER ROLLBACK SEGMENT ALTER SEQUENCE ALTER SESSION ALTER SNAPSHOT ALTER SNAPSHOT LOG ALTER SYSTEM ALTER TABLE ALTER TABLESPACE ALTER TRIGGER ALTER USER ALTER VIEW ANALYZE AUDIT (SQL Statements) AUDIT (Schema Objects) 24 24 27 27 27 27 27 28 28 28 29 29 30 31 31 32 34 34 34 35 35 36 38 COMMENT COMMIT CREATE CLUSTER CREATE CONTROLFILE CREATE DATABASE CREATE DATABASE LINK CREATE FUNCTION CREATE INDEX CREATE PACKAGE CREATE PACKAGE BODY CREATE PROCEDURE CREATE PROFILE CREATE ROLE CRATE ROLLBACK SEGMENT CREATE SCHEMA CREATE SEQUENCE CREATE SNAPSHOT CREATE SNAPSHOT LOG CREATE SYNONYM CREATE TABLE CREATE TABLESPACE CREATE TRIGGER CREATE USER 39 39 39 40 41 41 42 42 43 43 43 44 44 45 45 45 46 47 47 48 52 53 53 CREATE VIEW DELETE DROP EXPLAIN PLAN GRANT (System Privileges and Roles) GRANT (Object Privileges) INSERT LOCK TABLE NOAUDIT (SQL Statements) NOAUDIT (Schema Objects) RENAME REVOKE (System Privileges and Roles) REVOKE (Object Privileges) ROLLBACK SAVEPOINT SELECT SET ROLE SET TRANSACTION TRUNCATE UPDATE 54 54 55 57 57 57 58 58 58 59 59 59 59 60 60 60 62 62 63 63

Parameters mentioned in this Reference


Parameter c_alias char Explanation Column alias. Another name for a column specified in SELECT statement. Column constant in single quotes or expression of datatype CHAR or VARCHAR2.

column_element Column definition. For the format of a column element refer to the CREATE TABLE statement. condition constraint dblink Expression that logically evaluates to TRUE, FALSE, or UNKNOWN. The name of an integrity constraint, stored in the data dictionary. Database link.

Document Templates

expr location integer m,n nls_sort subquery rowid t_alias scn sid,serial#

Any expression. Operatingsystemdependent specification of a files location. Usually either a device or a directory. Number constant or expression of datatype NUMBER. Must evaluate to an integer. Any number constant or expression of datatype NUMBER. An expression of the form NLS_SORT = name, where name is either BINARY or the name of a linguistic sort sequence Query expression in another statement, such as CREATE TABLEAS subquery Expression of datatype ROWID> Table alias. Another name for a table specified in a SELECT statement System Change Number. A number that uniquely identifies a transaction. Session ID and serial number. A combination that uniquely identified a session.

Functions
SingleRow Number Functions Functions
Value Returned Absolute value of n. Smallest integer greater than or equal to n.99 Cosine of n in radians.

ABS(n) CEIL(n) COS(n) COSH(n) EXP(n) FLOOR(n) LN(n) LOG(m,n) MOD(m,n) POWER(m,n) ROUND(n[,m]) SIGN(n) SIN(n)

Hyperbolic cosine of n in radians..


e raised to the nth power. Largest integer equal to or less than n. Natural logarithm of n, where n > 0 Logarithm, base m, of n. Remainder of m divided by n. <MI%2>m raised to the nth power.<%0> n rounded to m decimal places; m defaults to 0. If n<0, 1; if n=0, 0; if n>0, 1. Sine of n in radians.

SINH(n) SQRT(n) TAN(n) TANH(n) TRUNC(n[,m])

Hyperbolic sine of n in radians. Square root of n; if n<0, NULL. Tangent of n in radians. Hyperbolic tangent of n in radians. <MI%2>n truncated to m decimal places; m defaults to 0.<%0>

SingleRow Character Functions Single row character functions that return character values:
Function CHR(n) CONCAT(char1,char2) INITCAP(char) LOWER(char) LPAD(char1,n[,char2]) Value Returned CharacDate of the first day of the week named by char that is equal to or later than the date d. Concatenates char1 and char2. char, with first letter of each word capitalized. char, with all letters lowercase. char1, leftpadded to length n with the sequence of characters in char2; char2 defaults to . A multi byte character that does not fit is replaced with a blank. char, with initial characters removed up to the first character not in set. set defaults to . char, with first letter of each word capitalized. nls_sort defines handling of languagespecific capitalization. char, with all letters lowercase. nls_sort defines handling of languagespecific capitalization. char, with all letters uppercase. nls_sort defines handling of languagespecific capitalization. char, with every occurrence of search_string replaced by replacement_string. If you do not specify replacement_string, ORACLE removes all occurrences of search_string. char1, rightpadded to length n with the sequence of characters in char2; char2 defaults to a blank. A multibyte character that does not fit is replaced with a blank.

LTRIM(char[,set]) NLS_INITCAP(n [, nls_sort])

NLS_LOWER(n [, nls_sort]) NLS_UPPER(n [, nls_sort]) REPLACE(char,search_string [,replacement_string])

RPAD(char1,n[,char2])

Document Templates

RTRIM(char[,set]) SOUNDEX(char) SUBSTR(char,m[,n]) SUBSTRB(char,m[,n]) TRANSLATE(char,from,to) UPPER(char)

char, with final characters removed after the last character not in set. set defaults to . A char value representing the sound of the word(s) in char. A substring of char, beginning at character m, n characters long (if n is omitted, to end of char). A substring of char, beginning at byte m, n bytes long (if n is omitted, to end of char). char, translated from the character set from to the character set to. char, with all letters uppercase.

Single row character functions that return character values:

Function ASCII(char)

Value Returned Returns a decimal number equivalent to the value of the first character of char in the database character set. (An ASCII value on ASCII systems.) Returns value of first byte in a multibyte character. Position of the mth occurrence of char2 in char1, beginning search at character position n. m and n default to 1. Position is relative to the first character of char1, even if n>1. Position of the mth occurrence of char2 in char1, beginning search at byte position n. m and n default to 1. Position is relative to the first byte of char1, even if n>1. Length of char in characters Length of char in bytes The NLSequivalent value used when sorting char.

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

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

LENGTH(char) LENGTHB(char) NLSSORT(char) Group Functions Function AVG([DISTINCT|ALL]n) COUNT([ALL]*) COUNT([DISTINCT|ALL]expr}) MAX([DISTINCT|ALL]expr) MIN([DISTINCT|ALL]expr)

Value Returned Average value of n, ignoring nulls. Number of rows retunred by a query or subquery. Number of rows where expr is not null. Maximum value of expr. Min imum value of expr.

STDDEV([DISTINCT|ALL]n) SUM([DISTINCT|ALL]n) VARIANCE([DISTINCT|ALL]n)

Standard deviation of n, ignoring nuyll values. Sum values of n. Variance of n, ignoring null values.

Date Functions Function ADD_MONTHS(d,n) LAST_DAY(d) MONTHS_BETWEEN(d,e) NEW_TIME(d,a,b) Value Returned Date d plus n months. Date of last day of month containing d. <%2>Number of months by which e precedes d.<%0> Date and time in time zone b when date and time in time zone a are d. a and b are CHAR values identifying time zones. Date of the first day of the week named by char that is equal to or later than the date d. Current date and time.

NEXT_DAY(d,char) SYSDATE

Date Truncation and Rounding Function ROUND(d[,fmt]) TRUNC(d[,fmt]) Value Returned d rounded as specified by rounding unit fmt. d truncated as specified by fmt.

Format Models for ROUND and TRUNC This table list the date format elements used to control truncation and rounding. If no format element is specified, fmt defaults to DD. Format Element CC or SCC YYYY or SYYYY YYY or YY or Y Y,YYY or YEAR or SYEAR Q MONTH or MON or MM or RM WW or IW Value Returned First day of the century First day of the year (rounds up on July 1)

First day of the quarter (rounds up on 16th day of 2nd month of the quarter) Same day of the month (rounds up on 16th day) Same day of the week as jan 1st of that year

Document Templates

Format Element W DDD or DD or J DAY or DY or D HH or HH12 or HH24 MI

Value Returned Same day of the week as the 1st of the month Day First day of the week Hour Minute

Conversion Functions
Function CHARTORWID(char) CONVERT(char,dest_char_set [,source_char_set]) HEXTORAW(char) RAWTHOHEX(raw) Value Returned char, converted from a CHAR value to a ROWID value. CHAR, converted from source_char_set. representation to dest_char_set representation. char, converted from a hexadecimal number to a binary RAW value. raw, converted from a binary value of datatype RAW to a dezadecimal numver of datatype CHAR. rowid, converted from a ROWID value to a CHAR value. expr, converted from a NUMBER or DATE value to a CHAR value in the format specified by fmt. If you omit fmt, ORACLE converts DATE values to default date format and NUMVWER value3s to CHAR values exactly wide ehnought to hold all significant digits. nls_num_fmt sets the international numver format specifications. In Trusted ORACLE, converst values of type MLS or MLS_LABEL to type VARCHAR2. char, converted from a CHAR value in the format fmt to a DATE value. If you omit fmt, char must be in default date format. nls_lang specifies the language4 used for day and month. char, with all singlebyte characters tha have a multibyte equivalent converted to their multibyte form.

ROWIDTOCHAR9rowid) TO_CHAR(expr[,fmt [,nls_num_fmt ]])

TO_DATE(char[,fmt [,nls_lang]])

TO_MULTI_BYTE(char)

TO_NUMBER(char [,fmt [, nls_lang]])

char, which is a character value containing a number in the format specified by the optional fmt, converted to a NUMBER value. nls_lang specifies the language used for numeric characters and currency symbols. char, with all multibyte characters that have a singlebyte equivalent converted to their singlebyte form.

TO_SINGLE_BYTE(char)

Other Functions
Function DECODE(expr,search1,return1, [search2,return2,]...[default]) DUMP(expr[,display_format [,start_position[,length]]]) GREATEST(expr[,expr]...) LEAST(expr[,expr]...) NVL(expr1,expr2) UID USER USERENV(option) Value Returned If expr equals any search, returns the following return; if not, returns default. expr in ORACLE internal format. expr with the greatest value. expr with the least value. expr2, if expr1 is null; otherwise returns expr1. <%2>Number that uniquely identifies the current user.<%0> Name of the current user. Information about the current session. Specify option in single quotes. Options: ENTRYID, SESSIONID, TERMINAL, and LANGUAGE. The number of bytes in ORACLEs internal representation of expr. Current system time/date.

VSIZE(expr) SYSDATE

Format Models
Date Format Models for TO_CHAR and TO_DATE
This table lists the date format elements. You can use any combinationof these elements as the fmt argument of the TO_CHAR or TO_DATE functions. fmt defaults to the default DATE format, DDMONYY.

Document Templates

Format Element SCC or CC YYYY or SYYYY YYY or YY or Y IYYY IYY or IY or I Y,YYY SYEAR or YEAR RR BC or AD B.C. or A.D. Q MM RM MONTH MON WW or W IW DDD or DD or D DAY DY J AM or PM A.M. or P.M. HH or HH12 HH24 MI SS or SSSSS /,.;: ...text...

Value Returned Century; S prefixes BC date with . Year; S prefixes BC date with . Last 3,2, or 1 digit(s) of year. Century defaults to current. 4digit ISO standard year. Last 3,2, or 1 digit(s) of ISO year. Year with comma in this position. Year spelled out; S prefixes BC date with . Last 2 digits of year, for years in next century. BC/AD indicator. BC/AD indicator with periods. Quarter of year (1,2,3,4; JANMAR=1) Month of year (0112; JAN=01) Roman Numeral month (I..XII;JAN=I). Month name, padded with blanks to 9 characters. Name of month, abbreviated (JAN,FEB,etc.). Week of year (1052) or month (15) ISO standard week of the year (1..21 or 1..53). Day of year (1366) or month (131) or week (17). Name of day, blankpadded to 9 characters. Name of day, 3lettter abbreviation. Julian day (days since December 31, 4713 BC). Meridian indicator. Meridian indicator with periods. Hour of the day (112). Hour of day (023). Minute (059). Second (059) or seconds past midnight (086399). Punctuation is reproduced in the result. QUoted string is reporduced in the result.

Date Format Prefixes and Suffixes

You can add this prefix to date format elements:

FM FX

Fill mode. Suppresses blank padding when prefixed to MONTH or DAY. FM is a toggle. Use FM twice to reenable blank padding. Format exact. Specifies exact matching for the character argument and date format model of a TO_DATE function

You can add this suffixes to date format elements:

TH SP SPTH and THSP

Ordinal number (DDTH for 4TH). Spelledout number (DDSP for FOUR). Spelledout ordinal number (DDSPTH for FOURTH). The following strings specify output in uppercase, initial caps, or lowercase:

Date Format Case Control


The following strings output in uppercase, initial caps, or lowercase: Uppercase DAY DY MONTH MON YEAR AM PM A.M., A.m. p.m., p.M. Initial Caps Day Dy Month Mon Year Am Pm Lowercase day dy month mon year am pm am pm

When prefixes or suffices are added to a date format, the case (uppercase, initial caps, or lowercase) is determined by the format element, not by the prefix or suffix. For example, ddTH produces 04th, not 04TH.

Number Format Models for TO_CHAR

This table lists the number format elements. You can use a combinationof these elements as the fmt argument of the TO_CHAR function.

10

Document Templates

Format Element 9 0 $ B MI S PR D G C L , . V EEEE RN or rn DATE

Example 9999 0999 $9999 B9999 9999MI S9999 9999PR 99D99 9G999 C999 L999 9,999 99.99 999V99 9.999EEEE RN DATE

Function Number of 9s determines length of returned character. Prefixes value with leading zeroes. Prefixes value with dollar sign. Returns zero value as blank, instead of 0. Returns after negative values. Returns + for positive values and for negative values. Returns negative values in <angle brackets>. Returns the decimal character. Returns the group separator. Returns the international currency symbol. Returns the local currency symbol. Returns a comma in this position. Returns a period in this position. Multiplies value by 10n, where nis the number of 9s after the V. Returns value in scientific notation. fmt must contain exactly for Es. upper or lowercase Roman numerals (numbers in range 1..3999). Returns value converted from Julian date to MM/DD/YY date format. Since the parameters are specified inside a quoted string, the parametervalues must be specified with two single quotes, instead of one.

NLS Parameters

nls_num_fmt ::=
, NLS_NUMERIC_CHARACTERS = dg NLS_CURRENCY = local_currency_suymbol NLS_ISO_CURRENCY = territory where d = decimal character g = group separator

nls_lang ::=

11

NLS_DATE_LANGUAGE = language

nls_sort ::=
NLS_SORT = sort

Languagespecific sort sequence

PseudoColumns
Pseudocolumns are similar to table columns. You can query any of these pseudocolumns, but you cannot change their values with DML statements: Column Name sequence.CURRVAL sequence.NEXTVAL table.LEVEL [table.]ROWID Value Current value of sequence for the current session. (sequence.NEXTVAL must be referenced first.) Next value of sequence for the current session. 1 for a root node, 2 for a child of a root, etc. Used in the SELECT statement during treestructured queries. Value that uniquely identifies a single row among other rows in the table. ROWID values are of datatype ROWID, not NUMBER or CHAR. Position of a single row among other rows selected by a query. ORACLE selects rows in an arbitrary order and evaluates ROWNUM before sorting rows for an ORDER BY clause.

ROWNUM

Datatypes
ORACLE accepts the following datatypes: CHAR(size) CHARACTER(size) DATE LONG LONG RAW Fixed length character string of size characters. Default 1. Maximum 255. Same as CHAR Dates ranging from January 1, 4712 BC to December 31, 4712 AD. Variable length character string of up to 2 gigabytes. Binary data of up to 2 gigabytes, or 2!!super!!31 1.

12

Document Templates

NUMBER(p,s) RAW(size) ROWID VARCHAR2(size) VARCHAR(size)

Number having precision p and scale s. p ranges from 1 to 38. Default is 38. s ranges from 84 to 127. Binary data of up to size bytes. Maximum 2000 bytes. Size must be specified. Values from the pseudocolumn ROWID. Variable length character string having maximum length of size. Maximum 2,000. De fault 1. Same as VARCHAR2.

Names and Reserved Words


Names
Names of database objects are between 1 and 30 characters long, except for database names, which can be no longer than 8 characters do not contain quotation marks do not duplicate the name of another object

Names that are always enclosed in double quotation marks can ignore the following rules. Otherwise, names begin with a letter AZ contain only the characters AZ, 09, $, #, and _ do not duplicate a SQL reserved word Only names that are enclosed in double quotes are case sensitive. All other names are case insensitive.

SQL Reserved Words

SQL reserved words have special meanings in SQL statements. You maynot use these words as names for database objects: (Words marked with * are also reserved PL/SQL.)

13

ACCESS* ADD* ALL* ALTER* AND* ANY* AS* ASC* AUDIT BETWEEN* BY* CHAR* CHECK* CLUSTER* COLUMN COMMENT COMPRESS* CONNECT* CREATE* CURRENT* DATE* DECIMAL

DEFAULT* DELETE* DESC* DISTINCT* DROP* ELSE* EXCLUSIVE EXISTS* FILE FLOAT FOR* FROM* GRANT* GROUP* HAVING* IDENTIFIED* IMMEDIATE IN* INCREMENT INDEX* INITIAL INSERT

INTEGER INTERSECT* INTO* IS* LEVEL* LIKE* LOCK LONG MAXEXTENTS MINUS* MODE MODIFY NOAUDIT NOCOMPRESS* NOT* NOWAIT NULL* NUMBER* OF* OFFLINE ON* ONLINE

OPTION* OR* ORDER* PCTFREE* PRIOR* PRIVILEGES PUBLIC* RAW RENAME* RESOURCE* REVOKE ROW ROWID ROWLABEL ROWNUM* ROWS SELECT* SESSION SET* SHARE SIZE* SMALLINT

START* SUCCESSFUL SYNONYM SYSDATE TABLE* THEN* TO* TRIGGER UID UNION* UNIQUE* UPDATE* USER VALIDATE VALUES* VARCHAR* VARCHAR2* VIEW* WHENEVER WHERE* WITH*

PL/SQL Reserved Words

14

Document Templates

ABORT ACCEPT ACCESS ADD ALL ALTER AND ANY ARRAY AS ASC ASSERT ASSIGN AT AUTHORIZATION AVG BEGIN BETWEEN BODY BOOLEAN BY CASE CHAR CHAR_BASE CHECK CLOSE CLUSTER CLUSTERS COLAUTH COLUMNS COMMIT COMPRESS CONNECT CONSTANT COUNT CRASH

CREATE CURRENT CURSOR DATABASE DATA_BASE DATE DBA DEBUGOFF DEBUGON DECLARE DEFAULT DEFINITION DELAY DELETE DELTA DESC DIGITS DISPOSE DISTINCT DO DROP ELSE ELSIF END ENTRY EXCEPTION EXCEPTION_INIT EXISTS EXIT FALSE FETCH FOR FORM FROM FUNCTION GENERIC

GOTO GRANT GROUP HAVING IDENTIFIED IF IN INDEX INDEXES INDICATOR INSERT INTERSECT INTO IS LEVEL LIKE LIMITED LOOP MAX

PACKAGE PARTITION PCTFREE PRAGMA PRIOR PRIVATE PROCEDURE PUBLIC RAISE RANGE RECORD RELEASE REM RENAME RESOURCE RETURN REVERSE REVOKE ROLLBACK

SUM TABAUTH TABLE TABLES TASK TERMINATE THEN TO TRUE TYPE UNION UNIQUE UPDATE USE VALUES VARCHAR VARCHAR2 VARIANCE VIEW

MIN MINUS MOD NEW NOCOMPRESS NOT NULL NUMBER NUMBER_BASE OR ON OPEN OPTION OR ORDER OTHERS OUT

ROWNUM ROWTYPE RUN SAVEPOINT WSCHEMA SELECT SEPARATE SET SIZE SPACE SQL SQLCODE SQLERRM START STATEMENT STDDEV SUBTYPE

VIEWS WHEN WHERE WHILE WITH WORK XOR

Privileges
System Privileges
ANALYZE ANY AUDIT ANY These privileges apply to a whole class of objects. Analyze any table, index, or cluster in any schema. Audit any object in any schema.

15

TRUNCATE ANY CREATE CLUSTER ALTER ANY CLUSTER CREATE ANT CLUSTER DROP ANY CLUSTER ALTER DATABASE CREATE DATABASE LINK CREATE PUBLIC DATABASE LINK DROP PUBLIC DATABASE LINK CREATE INDEX ALTER ANY INDEX CREATE ANY INDEX DROP ANY INDEX CREATE PROCEDURE ALTER ANY PROCEDURE CREATE ANY PROCEDURE DROP ANY PROCEDURE EXECUTE ANY PROCEDURE GRANT ANY PRIVILEGE ALTER PROFILE CEATE PROFILE DROP PROFILE ALTER RESOURCE COST CREATE ROLE ALTER ANY ROLE DROP ANY ROLE GRANT ANY ROLE

Truncate any table or cluster in any schema. Create a cluster in own schema. Alter any cluster in any schema. Create a cluster in own schema.

Drop any cluster in any schema.


Alter the database.

Create private database links in own schema.


Create public database links. Drop public database links. Create index in own schema on any table in the same schema. Alter any index in any schema. Create an index in any schedma on any table in the same schema. Drop any index in any schema. Create stored procedures, functions, and p[ackages in own schema. Alter any stored procedure, function, or package in any schema. Create store procedures, functions, and packages in any schema. Drop stored procedures, functions, and packages in any schema. Execute any stored procedure, function, or package, or reference amy public package variable in any schema. Grant system privileges even if not currently owned. Alter any profile in the database. Create profiles Drop any profile in the database. Set costs for sesssion resources Create roles. Alter any role in the database. Drop any role in the database. Grant any role in the database.

16

Document Templates

ALTER ROLLBACK SEGMENT CREATE ROLLBACK SEGMENT DROP ROLLBACK SEGMENT ALTER SESSION CREATE SESSION RESTRICTED SESSION CREATE SEQUENCE ALTER ANY SEQUENCE CREATE ANY SEQUENCE DROP ANY SEQUENCE SELECT ANY SEQUENCE CREATE SNAPSHOT ALTER ANY SNAPSHOT CREATE ANY SNAPSHOT DROP ANY SNAPSHOT CREATE SYNONYM CREATE ANY SYNONYM DROP ANY SYNONYM CREATE PUBLIC SYNONYM DROP PUBLIC SYNONYM AUDIT SYSTEM ALTER SYSTEM

Alter rollback segments. Create rollback segments. Drop rollback segments. Trace facility, national language characteristics, close a database link. Connects the database. Logon after the database is started using STARTUP RESTRICT. Create a sequence in own schema. Alter any sequence in any schema. Create a sequence in any shcema. Drop any sequence in any schema. Reference any sequence in any schema. Create snapshots in any schema. Requires CREAE ANY TABLE, as well. Alter any snapshot in the schema. Create cnapshots in any schema. Requires CREATE ANY TABLE, as well. Drop any snapshot in any schema. Create a synonym in won schema. Create a synonym in any schema. Drop any synonym in any schema, except public synonyms. Create public synonyms. Drop public synonyms. Audit system events. resource limits, server and dispatcher processes, change and archive redo log files, distriburted recovery, checkpoint, verify file access. Create tables in own schema. Requires UNLIMITED TABLESPACE, or a quota on a tablespace. Alter any table in any schema. Backup any table in any schema with ALTER TABLE command. Comment on any table, view, or column in any schema. Create a table in any schema.

CREATE TABLE ALTER ANY TABLE BACKUP ANY TABLE COMMENT ANY TABLE CREATE ANY TABLE

17

DELETE ANY TABLE DROP ANY TABLE INSERT ANY TABLE LOCK ANY TABLE SELECT ANY TABLE UPDATE ANY TABLE ALTER TABLESPACE CREATE TABLESPACE DROP TABLESPACE MANAGE TABLESPACE UNLIMITED TABLESPACE FORCE TRANSACTION FORCE ANY TRANSACTION CREATE TRIGGER ALTER ANY TRIGGER CREATE ANY TRIGGER DROP ANY TRIGGER ALTER USER BECOME USER CREATE USER DROP USER CREATE VIEW CREATE ANY VIEW DROP ANY VIEW

Delete rows from any table, view, or snapshot in any schema. Drop any table in any schema. insert into any table, view, or snapshot in any schema. Lock any table in any schema. Query any table, view, or snapshot in any schema. Update rows in any table, view, or snapshot in any schema. Alter tablespaces. Create tablespaces. Drop tablespaces. Tablespace online and offline. Tablespace backups. Use an unlimited amount of any tablespace. Force commit or rollback of own distributed transaction in the local database. Force commit or rollback of any distributed transaction in the local database. Create triggers in own schema. Enable, disable, or compile trigger in any schema. Create a trigger in any schema associated with any table in any schema. Drop any trigger in any schema. Alter other users: password, authentication method, quotas, tablespaces, assign a profile & default roles Become another user. Create users, assign quotas on any tablespace, set default and temporary tablespaces, assign a profile. Drop another user. Create a view in own schema Create a view in any schema. Drop any view in any schema. These privileges apply to specific objects. Explanation All of the object privileges that can be applied. Same as ALL.

Object Privileges
Object Privilege ALL ALL PRIVILEGES

18

Document Templates

ALTER DELETE EXECUTE INDEX INSERT REFERENCES SELECT UPDATE

Change definition. Delete rows. Execute the object, reference its variables. Create an index on the table. Insert rows. Create a constraint that refers to the table. Not granted to roles. Query rows. Change rows. Procedure Functions Object Privilege ALTER DELETE EXECUTE INDEX INSERT REFERENCES SELECT UPDATE Table Views Sequences Packages Snaphots

Expressions and Conditions


The following diagrams show the possible expressions and conditions denoted by expr and condition in the SQL command syntax diagrams.

19

expr ::= column table. schema. view. snapshot. text number sequence. CURRVAL NEXTVAL NULL function , ( DISTINCT ALL (expr) + PRIOR expr * / + || , DECODE (expr search, result , default expr_list expr_list ::= , ( expr ) ) expr expr expr ) psuedocolumn ROWLABEL

20

Document Templates

condition ::= expr = != ^= = <> < <= > >= expr_list * != ^= = <> SOME ANY ALL expr NOT IN expr_list query , expr_list NOT expr NOT expr IS NOT char_expr NOT EXISTS query (condition) NOT condition condition AND OR condition LIKE pattern ESCAPE c NULL BETWEEN expr AND expr IN expr_list query query , expr_list expr_list query SOME ANY ALL expr_list query expr query

21

Operators and Operator Precedence


Arithmetic Operators
Operator + (one operand) */ + (two operands) Function Denotes a positive or negative expression. Multiplication and division. Addition and subtraction.

Logical Operators
Operator || Function Concatenates character values.

Logical Operators
Operator NOT AND OR Function reverses a logical expressions result Combines two or more logical expresseions: TRUE if all are true; otherwise FALSE. Combines two or more logical exprtession: TRUE if any are true; otherwise FALSE.

Comparison Operators
Operator = != ^= = <> > >= < <= IN NOT IN ANY,SOME ALL [NOT]between x and y [NOT] EXISTS Function Tests for equaulty. Tests for inequality. Greater than, greater than or equal to, less than, less than or equal to. Equal to any memvber of a set or subquery. ALso equivalent to !=ANY. Not equal to any memver of a set or subquery. Also equivalent to !=ALL. True if the condition is satisfied by one or more values contained in a list of expressions or returned by a subquery. True if the condition is satisfied by all values contaiend in a list of expressions or returned by a subquery. [Not] greater than or equal to x and less than or equal to y. TRUE if a subquery returns [does not return] at least one row.

22

Document Templates

[NOT] LIKE p [ESCAPEc]

Matches [does not match] a specified pattern. % matches any sequence of characters; _ matches any single character. The ESCAPE character preceding % or _ causes themn to be treated literaly. Matches multiple bytes for a multibyte character. Is [not] null.

IS [NOT] NULL

Set Operators used in SELECT Statements


Operator UNION UNION ALL INTERSECT MINUS (+) * PRIOR ALL DISTINCT Function Combines two qureies; returns all distinct rows returned by either individual query. Combines two queries; returns all rows returned by either query, including duplicates. Combines two queries; returns all distinct rows returned by both individual queries. Combines two queries; returns all distinct rows returned by the 1st but not by the 2nd. Indicates that the preceding column is an outer join column. Wildcard operator used instead of column names to select all columns from a table or view. Used in a treestructured query to define a parentchild relationship between nodes in a treestructured query. See SELECT. Retains duplicate rows in a query (ALL is the default, as compared to DISTINCT). Eliminates duplicate rows from the result of a query.

Operator Precedence
When evaluating an expression, ORACLE evaluates operators with greater precedence first. Operators on the same line have the same precedence. Note: Parentheses() override normal precedence. ORACLE evaluates operators inside parentheses before those outside. Wihtout parentheses, operators at the same precedence are evaluated from left to right.

SQL Operator Precedence + unary arithemetic operators */ arithmetic operators + binary arithemetic operators || character operator PRIOR operator

23

All comparison operators NOT logical operator AND logical operator OR logical operator
Arithmetic Operator Precedence + unary arithmetic operators * / arithmetic operators + binary arithmetic operators

SQL Commands
ALTER CLUSTER Redefines storage allocations for an existing cluster.

ALTER CLUSTER schema.

cluster

SIZE integer K M ALLOCATE EXTENT

SIZE integer K M DATAFILE filename INSTANCE integer

extent_specs

ALTER DATABASE Changes the operation of the database with respect to redo log files and database files. Backs up control files and archives redo log files. Mounts, dismounts, opens and closes a database. Performs media recovery.

24

Document Templates

ALTER DATABASE database , ADD LOGFILE THREAD integer ADD LOGFILE MEMBER log_member_clause ARCHIVELOG BACKUP CONTROLFILE TO filename REUSE CONVERT , CREATE DATAFILE filename , AS DATAFILE filename ONLINE OFFLINE DROP DISABLE THREAD integer , DROP LOGFILE GROUP integer , ( filename filename , filename THREAD integer PUBLIC MOUNT EXCLUSIVE PARALLEL NOARCHIVELOG OPEN RESETLOGS NORESETLOGS RECOVER recover_clause , filename , filename ) filespec GROUP integer filespec

DROP LOGFILE MEMBER ENABLE

RENAME FILE

TO

25

RENAME GLOBAL_NAME

TO database .domain

SET security_mode_clause

log_member_clause ::= , , filename REUSE ( TO GROUP integer , filename filename recover_clause ::= )

AUTOMATIC

FROM location

DATABASE

UNTIL CANCEL UNTIL TIME date UNTIL CANCEL scn USING BACKUP CONTROLFILE ,

TABLESPACE

tablespace

DATAFILE

, filename

LOGFILE filename CONTINUE DEFAULT CANCEL security_mode_clause ::= DBMAC ON OFF DBHIGH = text DBLOW = text

26

Document Templates

ALTER FUNCTION Recompiles a standalone function.


ALTER FUNCTION schema. function COMPILE

ALTER INDEX Redefines storage allocations for an existing index.


ALTER INDEX schema. index

INITRANS integer MAXTRANS integer STORAGE storage_clause

ALTER PACKAGE Recompiles the specification or body of a stored package.


ALTER PACKAGE schema. package COMPILE PACKAGE BODY

ALTER PROCEDURE Recompiles a standalone stored procedure.


ALTER PROCEDURE schema. procedure COMPILE

ALTER PROFILE Add, modify, or remove a resource limit in a profile.

27

ALTER PROFILE profile LIMIT

SESSIONS_PER_USER CPU_PER_SESSION CPU_PER_CALL CONNECT_TIME IDLE_TIME LOGICAL_READS_PER_SESSION LOGICAL_READS_PER_CALL COMPOSITE_LIMIT PRIVATE_SGA integer K M UNLIMITED DEFAULT

INTEGER UNLIMITED DEFAULT

ALTER RESOURCE COST Specify a formula to calculate the total resource cost for a session.

ALTER RESOURCE COST

CPU_PER_SESSION INTEGER CONNECT_TIME INTEGER LOGICAL_READS_PER_SESSION INTEGER PRIVATE_SGA INTEGER

ALTER ROLE Changes the authorization needed to enable a role.


ALTER ROLE role NOT IDENTIFIED IDENTIFIED BY password EXTERNALLY

ALTER ROLLBACK SEGMENT

28

Document Templates

Redefines storage allocations for an existing rollback_segment,


ALTER ROLLBACK SEGMENT rollback_segment ONLINE OFFLINE STORAGE storage_clause

ALTER SEQUENCE Redefines an existing sequence.


ALTER SEQUENCE schema. sequence

INCREMENT BY integer MAXVALUE integer NOMAXVALUE MINVALUE integer NOMINVALUE CYCLE NOCYCLE CACHE integer NOCACHE ORDER NORODER

ALTER SESSION Modifies the current user session by enabling and disabling the SQL trace facility, changing national language characteristics, or closing a remote database link.

29

ALTER SESSION

SET

SQL_TRACE =

TRUE FALSE

GLOBAL_NAMES =

TRUE FALSE

NLS_LANGUAGE = language NLS_TERRITORY = territory NLS_DATE_FORMAT = fmt NLS_DATE_LANGUAGE = language NLS_NUMERIC_CHARACTERS = text NLS_ISO_CURRENCY = territory NLS_CURRENCY = text NLS_SORT = sort BINARY OPTIMIZER_GOAL = FIRST ROWS ALL_ROWS RULE CHOOSE MLS_LABEL_FORMAT = fmt LABEL = text DBHIGH DBLOW OSLABEL ADVISE COMMIT ROLLBACK NOTHING CLOSE DATABASE LINK dblink ENABLE ENABLE COMMIT IN PROCEDURE

ALTER SNAPSHOT

30

Document Templates

Change storage characteristics or redefine the refresh time and mode for a snapshot.
ALTER SNAPSHOT schema. snapshot

extent_specs REFRESH FAST COMPLETE FORCE START WITH date NEXT date

ALTER SNAPSHOT LOG Change storage characteristics or remove rows from a snapshot log.
ALTER SNAPSHOT LOG ON schema. table extent_specs

ALTER SYSTEM Perform a specialized system function.

31

ALTER SYSTEM

SET

RESOURCE_LIMIT =

TRUE FALSE

GLOBAL_NAMES =

TRUE FALSE

LICENSE_MAX_SESSIONS = integer LICENSE_MAX_USERS = integer LICENSE_SESSIONS_WARNING = integer MTS_SERVERS = integer MTS_DISPATCHERS = protocol, integer

SWITCH LOGFILE CHECKPOINT CHECK DATAFILES GLOBAL LOCAL ENABLE DISABLE DISTRIBUTED RECOVERY RESTRICTED SESSION

FLUSH SHARED_POOL KILL SESSION sid, serial# ARCHIVE LOG archive_log_clause archive_log_clause ::= STOP THREAD integer START SEQ integer CHANGE integer CURRENT GROUP integer LOGFILE filename NEXTP ALL

TO location

ALTER TABLE

32

Document Templates

Redefines the columns, constraints, or storage allocations of an existing table.


ALTER TABLE schema. table

ADD

column_element table_constraint

(
MODIFY

column_element table_constraint column_element

(
extent_specs DROP drop_clause ALLOCATE EXTENT

column_element

DATAFILE filename INSTANCE integer SIZE integer K M

ENABLE enable_clause DISABLE disable_clause

drop_clause ::= DROP PRIMARY KEY

,
UNIQUE ( column

CASCADE

CONSTRAINT constraint

33

ALTER TABLESPACE Redefines an existing tablespace by adding or renaming a database file, or by redefining default storage allocations. Also changes the state of a tablespace by moving the tablespace online or offline, or by <%3>signifying that a backup of the database files has begun or completed
ALTER TABLESPACE tablespace

,
ADD DATAFILE filespec

,
RENAME DATAFILE filename TO DEFAULT STORAGE storage_clause ONLINE OFFLINE NORMAL TEMPORARY IMMEDIATE

,
filename

BEGIN END

BACKUP

ALTER TRIGGER Enable, disable, or recompile a database trigger.


ALTER TRIGGER schema. trigger ENABLE DISABLE

ALTER USER Changes the password, default tablespace, or temporary tablespace of an existing user.

34

Document Templates

ALTER USER user

IDENTIFIED

BY password EXTERNALLY

DEFAULT TABLESPACE tablespace TEMPORARY TABLESPACE tablespace

QUOTA

integer K M UNLIMITED

ON tablespace

PROFILE profile

,
DEFAULT ROLE ALL role

,
EXCEPT NONE role

ALTER VIEW schema.

view

COMPILE

ALTER VIEW Recompiles a database view, affecting dependencies.


ALTER VIEW schema. view COMPILE

ANALYZE Validates the structure of an index, table, or cluster, or collects performance statistics for them.

35

ANALYZE

INDEX schema.

index

statistics_clause VALIDATE STRUCTURE

TABLE schema.

table

statistics_clause VALIDATE STRUCTURE list_chained_clause

CLUSTER schema.

cluster

statistics_clause ::= COMPUTE STATISTICS DELETE STATISTICS ESTIMATE STATISTICS

validate_clause ::= VALIDATE STRUCTURE CASCADE list_chained_clause ::= LIST CHAINED ROWS INTO schema. table

AUDIT (Form I) Enables auditing of specific SQL statements or types of objects.


, AUDIT system_priv statement_opt addl_stmt_opt BY , user

BY

SESSION ACCESS

WHENEVER NOT

SUCCESSFUL

36

Document Templates

statement_opt ::= CLUSTER DATABASE LINK PUBLIC EXISTS NOT INDEX PROCEDURE ROLE ROLLBACK SEGMENT SEQUENCE SESSION SYNONYM PUBLIC SYSTEM TABLE TABLESPACE TRIGGER USER VIEW AUDIT GRANT

37

addl_stmt_opt ::= EXECUTE GRANT ALTER GRANT SELECT ALTER COMMENT DELETE GRANT INSERT LOCK SELET UPDATE TABLE SEQUENCE PROCEDURE

AUDIT (Schema objects) Enables auditing of access to specific database objects. The DEFAULT option enables auditing of all (specified) objects that are subsequently created. Auditable objects include tables, views, sequences, functions, procedures, packages, and snapshots. Procedure Functions Object Privilege ALTER AUDIT COMMENT DELETE EXECUTE GRANT INDEX INSERT LOCK RENAME SELECT UPDATE Table Views Sequences Packages Snaphots

38

Document Templates

SELECT UPDATE

AUDIT

object_opt

ON schema. DEFAULT

object

BY

SESSION ACCESS

WHENEVER NOT

SUCCESSFUL

COMMENT Adds a comment about a table, view, or column to the data dictionary.
COMMENT command ::= TABLE schema. table view snapshot table.column schema. view.column snapshot.column IS text

COMMENT ON

COLUMN

COMMIT Saves the changes in the current transaction to the database. Also erases the transactions savepoints and releases the transactions locks.
COMMIT WORK COMMENT text FORCE transaction_ID , scn

CREATE CLUSTER Creates a new cluster and specifies its cluster key columns.

39

,
CREATE CLUSTER schema. cluster ( column datatype

extent_specs SIZE integer K M TABLESPACE tablespace INDEX HASHKEYS integer HASH IS column

CREATE CONTROL FILE Recreates the database control file.


CREATE CONTROLFILE RESUE SET DATABASE database

,
UNIQUE GROUP integer filwapec RESETLOGS NORESETLOGS

,
DATAFILE filespec MAXLOGFILES integer MAXLOGMEMBERS integer MAXLOGHISTORY integer MAXDATAFILES tablespace MAXINSTANCES storage_clause ARCHIVELOG NOARCHIVELOG

40

Document Templates

CREATE DATABASE Creates a new database setting the maximum numbers of instances, database files, and redo log files; specifying database files and redo log files; and choosing the mode for the redo log.
CREATE DATABASE database

CONTROLFILE REUSE , LOGFILE GROUP integer MALOGFILES integer MAXLOGMEMBERS integer MAXLOGHISTORY integer , DATAFILE filespec filespec

MAXDATAFILES integer MAXINSTANCES integer ARCHIVELOG NOARCHIVELOG EXCLUSIVE CHARACTER SET charset filespec (for data files) ::= filename SIZE integer K M filespec (for redo log files) ::= filename , ( filename ) SIZE integer K M REUSE REUSE

CREATE DATABASE LINK extent_specs Creates a link from the local database to a user on a remote database specified by a connect_string.
INSTANCE integer

41

CREATE PUBLIC

DATABASE LINK dblink

CONNECT TO user IDENTIFIED BY password

USING connect_string

CREATE FUNCTION Creates a stored function.


CREATE OR REPLACE FUNCTION schema. function

,
( argument IN datatype

RETURN datatype

IS AS

pl/sql_subprogram_body

CREATE INDEX Creates a new index on the specified columns in a table or cluster.

42

Document Templates

CREATE INDEX schema.

index

,
ON schema. table ( column ASC DESC CLUSTER schema. cluster

extent_specs TABLESPACE tablespace NOSORT

CREATE PACKAGE Creates a stored package specification.


CREATE OR REPLACE PACKAGE schema. package

IS AS

pl/sql_package_spec

CREATE PACKAGE BODY Creates the body of a stored package.


CREATE OR REPLACE PACKAGE BODY schema. package

IS AS

pl/sql_package_body

CREATE PROCEDURE

43

Creates a stored procedure.


CREATE OR REPLACE PROCEDURE schema. procedure

,
( argument IN OUT IN OUT IS AS pl/sql_subprogram_body datatype

CREATE PROFILE Creates a user profile and specifies its resource limits.
CREATE PROFILE profile LIMIT

SESSION_PER_USER CPU_PER_SESSION CPU_PER_CALL CONNECT_TIME IDLE_TIME LOGICAL_READS_PER_SESSION COMPOSITE_LIMIT PRIVATE_SGA

integer UNLIMITED DEFAULT

integer K M UNLIMITED DEFAULT

CREATE ROLE Creates a security role.

44

Document Templates

CREATE ROLE role NOT INDENTIFIED IDENTIFIED By password EXTERNALLY

CREATE ROLLBACK SEGMENT Creates a new rollback_segment.


CREATE PUBLIC ROLLBACK SEGMENT rollback_segment

TABLESPACE tablespace STORAGE storage_clause

CREATE SCHEMA Issues multiple CREATE TABLE, CREATE VIEW, and GRANT commands in a single transaction.
CREATE SCHEMA AUTORIZATION schema

CREATE TABLE command CREATE VIEW command GRANT command

CREATE SEQUENCE Creates a new sequence suitable for generation of primary keys.

45

CREATE SEQUENCE schema.

SEQUENCE

INCREMENT BY integer START WITH integer MAXVALUE integer NOMAXVALUE MINVALUE integer NOMINVALUE CYCLE NOCYCLE CACHE integer NOCACHE ORDER NOORDER

CREATE SNAPSHOT Creates a snapshot of a database from one or more master tables.

46

Document Templates

CREATE SNAPSHOT schema.

snapshot

extent_specs TABLESPACE tablespace

,
CLUSTER cluster ( column

REFRESH FAST COMPLETE FORCE AS subquery START WITH date NEXT date

CREATE SNAPSHOT LOG Creates a snapshot log identifying changes made to the master table.

CREATE SNAPSHOT LOG ON schema.

table extent_specs TABLESPACE tablespace

CREATE SYNONYM Creates a new synonym for a table, view, sequence, packaged procedure, toplevel function or procedure (one that is not defined inside a package), or for another synonym.

47

CREATE PUBLIC FOR schema.

SYNONYM schema. object @dblink

synonym

CREATE TABLE Creates a new table, defining its columns, constraints, and storage allocations.<%5>

,
CREATE TABLE schema. table ( column_element table_constraint

extent_specs TABLESPACE tablespace

,
CLUSTER cluster ( column

ENABLE enable_clause DISABLE disable_clause extent_specs ::=

AS subquery

PCTFREE integer PCTUSED integer INITRANS integer MAXTRANS integer STORAGE storage_clause

PCT_USED is not allowed when the storage parameters are specified as part of an INDEX clause or in a CREATE INDEX statement.

48

Document Templates

column_element ::= column datatype DEFAULT expr column_constraint

column_constraint ::= NULL CONSTRAINT constraint NOT UNIQUE PRIMARY KEY REFERENCES col_ref ON DELETE CASCADE

CHECK (condition)

index_clause DISABLE

exceptions_clause

index_clause ::= USING INDEX TABLESPACE tablespace extent_specs

exceptions_clause ::= EXCEPTIONS INTO schema. table

49

col_ref ::= table schema. (column)

disable_clause ::= , UNIQUE ( column ) CASCADE

PRIMARY KEY CONSTRAINT constraint ALL TRIGERS

enable_clause ::= ENABLE ALL TRIGGERS integrity_constraint

integrity_constraint ::= , UNIQUE ( PRIMARY KEY CONSTRAINT constraint column ) index_clause index_clause

50

Document Templates

storage_clause ::=

INITIAL integer NEXT integer K M MINEXTENTS integer MAXEXTENTS integer PCTINCREASE integer OPTIMAL integer K M NULL FREELISTS integer FREELIST GROUPS integer

Storage Clause Notes: OPTIMAL is only allowed for rollback segments. FREELIST GROUPS is only allowed for tables, clusters, and indexes. FREELISTS is only allowed for tables and clusters.

51

table_constraint ::=

CONSTRAINT constraint , UNIQUE PRIMARY KEY , FOREIGN KEY ( column ) REFERENCES ref_lst ON DELETE CASCADE CHECK (condition) ( column )

index_clause DISABLE

exceptions_clause

ref_lst ::= table schema. ( , column )

CREATE TABLESPACE Creates a new area in the database for storage of tables, indexes, rollback segments, and temporary segments. Specifies the database files, the default storage allocations, and whether the tablespace is initially online or offline.

52

Document Templates

, CREATE TABLESPACE tablespace DATAFILE filespec

DEFAULT STORAGE storage_clause ONLINE OFFLINE

CREATE TRIGGER Creates a database trigger.


CREATE OR REPLACE OR DELETE INSERT UPDATE , OFF column ON schema. table TRIGGER schema. trigger BEFORE AFTER

FOR EACH ROW

REFRENCING

OLD AS NEW AS

old new

pl/sql_block WHEN (condition)

CREATE USER Defines a database user.

53

CREATE USER user

IDENTIFIED

BY pasword EXTERNALLY

DEFAULT TABLESPACE tablespace TEMPORARY TABLESPACE tablespace

QUOTA

integer K M UNLIMITED

ON tablespace

PROFILE profile

CREATE VIEW Creates a new view of one or more tables and/or other views.
CREATE OR REPLACE FORCE NOFORCE AS subquery VIEW schema. view

,
( alias

WITH CHECK OPTION CONSTRAINT constraint

DELETE Removes rows from a table or view that meet the WHERE condition. Removes all rows if no WHERE clause is specified.

54

Document Templates

DELETE FROM schema.

table view @dblink alias

WHERE condition

DROP This command removes objects from the database. The appropriate privileges are required for each object. For example, removing a PUBLIC database link requires the DROP PUBLIC DATABASE LINK privilege.

55

DROP

CLUSTER schema.

cluster cluster_clause DATABASE LINK dblink

PUBLIC FUNCTION schema. INDEX schema. PACKAGE BODY PROCEDURE schema. PROFILE profile CASCADE ROLE role ROLLBACK SEGMENT segment SEQUENCE schema. SNAPSHOT schema. SNAPSHOT LOG ON schema. SYNONYM PUBLIC TABLE schema. TABLESPACE tablespace contents_clause TRIGGER schema. USER user CASCADE VIEW schema. view trigger schema. table CASCADE CONSTRAINTS synonym table snapshot sequence schema. procedure package index function

56

Document Templates

cluster_clause ::= INCLUDING TABLES CASCADE CONSTRAINTS contents_clause ::= INCLUDING TABLES CASCADE CONSTRAINTS

EXPLAIN PLAN Describes each step of the execution plan for a SQL statement and optionally places the description in a plan table.
EXPLAIN PLAN SET STATEMENT_ID = text FOR statement INTO schema. table @dblink

GRANT (System Privileges and Roles) Gives system privileges to users and other roles.

,
GRANT system_priv role TO

,
user role PUBLIC

WITH ADMIN OPTION

GRANT (Object Privileges) Gives privileges for a particular object (a table, view, synonym, package, procedure, etc.) to users and to roles.

57

, GRANT object_priv ALL PRIVILEGES (

,
column

,
ON schema. object TO user role PUBLIC WITH GRANT OPTION

INSERT Adds new rows to a table or view.


INSERT INTO schema. table view @dblink , VALUES subquery , ( column ( expr

LOCK TABLE Overrides default lock mode and reserves access to a table for the current transaction. Permits or restricts access by other users.
, LOCK TABLE schema. table view @dblink

IN lockmode MODE NOWAIT

NOAUDIT (SQL Statements) Disables auditing of specific SQL statements, as established by Form I of the AUDIT command.

58

Document Templates

, NOAUDIT statement_opt addl_stmt_opt system_priv BY , user

WHENEVER NOT

SUCCESSFUL

NOAUDIT (Form II) Disables auditing of specific database objects, as established by Form II of the AUDIT command.
, NOAUDIT object_opt ON schema. object

WHENEVER NOT

SUCCESSFUL

RENAME Renames a table, view, or synonym from old to new.


RENAME old TO new

REVOKE (Form I) Revokes system privileges and roles from users and from roles. Reverses the action of the GRANT (System Privileges and Roles) command.

,
REVOKE system_priv role FROM

,
user role PUBLIC

REVOKE (Object Privileges)

59

Revokes object privileges from users and from roles. Reverses the action of the GRANT (Object Privileges) command.
, REVOKE object_priv ALL PRIVILEGES ON schema. object

,
FROM user role PUBLIC CASCADE CONSTRAINTS

ROLLBACK Undoes all changes made since the savepoint. Undoes all changes in the current transaction if no savepoint is specified.
ROLLBACK WORK TO SAVEPOINT FORCE transaction_ID savepoint

SAVEPOINT Identifies a savepoint in the current transaction to which changes can be rolled back.
SAVEPOINT savepoint

SELECT Queries one or more tables or views. Returns rows and columns of data. May be used as statement or as a subquery in another statement.

60

Document Templates

SELECT ALL DISTINCT

select_list FROM table_list WHERE condition

CONNECT BY condition START WITH condition

, GROUP BY expr HAVING condition

UNION UNION ALL INTERSECT MINUS

SELECT command

, ORDER BY expr position ASC DESC FOR UPDATE OF update_list NOWAIT

61

select_list ::= * , table schema. view snapshot .*

expr c_alias table_list ::= table schema. view snapshot update_list ::= , column table. schema. view. @dblink t_alias

SET ROLE Enables a specific role for a session and disables all other roles for a user. Along with SET TRANSACTION, must be at the start of the transaction.
, SET ROLE role IDENTIFIED BY password ALL , EXCEPT NONE role

SET TRANSACTION Enforces read consistency at the transaction level, or specifies the rollback segment to be used for the transaction. Along with SET ROLE, must be at the start of the transaction.

62

Document Templates

SET TRANSACTION

READ ONLY READ WRITE USE ROLLBACK SEGMENT rollback_segment

TRUNCATE Removes all rows from a table or cluster.


TRUNCATE TABLE schema. CLUSTER schema. cluster table DROP REUSE STORAGE

UPDATE Changes the values of columns in rows that meet the WHERE condition in a table or view. Changes all rows if no WHERE condition is specified.
UPDATE schema. table view @dblink alias

, ,
SET ( column = column

)
expr

(subquery)

(subquery)

WHERE condition

Comments
Comments set off by /* and */ may appear anywhere within a SQL statement:
ALTER USER SCOTT /* This is a comment */ IDENTIFIED BY TIGER;

63

ANSIstandard comments may also be used. All characters from a doublehyphen to the end of the line are ignored.
ALTER USER SCOTT This comment goes to the end of the line IDENTIFIED BY TIGER;

Embedded SQL Commands


You can use the ORACLE precompilers to embed SQL statements into an application program. For the syntax of embedded SQL statements, refer to the SQL Language Reference Manual, Part No. 77870.

Special Tables
CHAINED_ROWS Table
Lists chained rows in a table or cluster named inthe ANALYZE command. Column OWNER_NAME TABLE_NAME CLUSTER_NAME HEAD_ROWID TIMESTAMP Datatype VARCHAR2(30) VARCHAR2(30) VARCHAR2(30) ROWID DATE

EXCEPTIONS Table
Used to identify rows that violate integrity constraintswhen constraints are enabled. Column ROWID OWNER TABLE_NAME CONSTRAINT Datatype ROWID VARCHAR2(30) VARCHAR2(30) VARCHAR2(30)

PLAN_TABLE
This table may be filled in with the EXPLAIN PLANcommand, to get a description of the execution plan for a SQL statement. To interpret the plan, see the ORACLE RDBMS Performance Tuning Guide.

64

Document Templates

Column STATEMENT_ID TIMESTAMP REMARKS OPERATION OPTIONS OBJECT_NODE OBJECT_OWNER OBJECT_NAME OBJECT_INSTANCE OBJECT_TYPE SEARCH_COLUMNS ID PARENT_ID POSITION OTHER

Datatype VARCHAR2(30) DATE VARCHAR2(80) VARCHAR2(30) VARCHAR(230) VARCHAR2(30) VARCHAR2(30) VARCHAR(30) NUMBER VARCHAR2(30) NUMBER NUMBER NUMBER NUMBER LONG

Data Dictionary Views


The Data Dictionary contains information about database objects, users, and events. You can access this information through these views of the data dictionary: View ALL_CATALOG ALL_COL_COMMENTS ALL_COL_PRIVS ALL_COL_PRIVS_MADE AL_COL_PRIVS_RECD ALL_CONSTRAINTS ALL_CONS_COLUMNS ALL_DB_LINKS Description All tables, views, synonyms, and sequences accessible to the user. Comments on columns of accessible tables and views. Synonym for COLUM N_PRIVILEGES. Grants on columns for which the user or PUBLIC is the grantee. Grants on columns for which the user or PUBLIC is the grantee. Constraint definitions on accessible tables. Information about accessible columns in constraint definitions. Database links accessible to the user.

65

View ALL_DEF_AUDIT_OPTS ALL_DEPENDENCIES ALL_ERRORS ALL_INDEXES ALL_IND_COLUMNS ALL_LABELS ALL_COUNTED_DBS ALL_OBJECTS ALL_SEQUENCES ALL_SNAPSHOTS ALL_SOURCE ALL_SYNONYMS ALL_TABLES ALL_TAB_COLUMNS ALL_TAB_COMMENTS ALL_TAB_PRIVS ALL_TAB_PRIVS_MADE ALL_TAB_PRIVS_RECD ALL_TRIGGERS ALL_USERS ALL_VIEWS AUDIT_ACTIONS CAT CLU CODE_PIECES CODE_SIZE COLS COLUMN_PRIVILEGES DBA_2PC_NEIGHBORS DBA_2PC_PENDING

Description Auditing options for newly created objects. Dependencies between objects. Current errors on all stored objects in the database. Description of indexes on tables accessible to the user. Columns of the indexes on accessible tables. Trusted ORACLE view that lists system labels. Trusted ORACLE view that lists mounted databases. Objects accessible to the user. Description of sequences accessible to the user. All snapshots accessible to the user. Text source of all stored objects in the database. All synonyms accessible to the user. Description of tables accessible to the user. Columns of all tables, vies, and clusters. Comments on tables and views accessible o the user. Synonym for TABLE_PRIVILEGES. Users grants and grants on users objects. Grants on objects for which the user or PUBLIC is the grantee. Triggers accessible to the current user. Information about all users of the database. Text of views accessible to the user. Description table for audit trail action type codes. Synonym for USER_CATALOG Synonym for USER_CLUSTERS. Used for building the _OBJECT_SIZE views. Used for building the _OBJECT_SIZE views. Synonym for USER_TAB_COLUMNS. Grants on columns for which the user is the grantor, grantee, or owner, or PUBLIC is the grantee. Information about incoming and outgoing connections for pending transactions. Information about failed distributed transactions in PREPARED state.

66

Document Templates

View DBA_AUDIT_EXISTS DBA_AUDIT_OBJECT DBA_AUDIT_SESSION DBA_AUDIT_STATEMENT DBA_AUDIT_TRAIL DBA_BLOCKERS DBA_CATALOG DBA_CLUSTERS DBA_CLU_COLUMN DBA_COL_COMMENTS DBA_COL_PRIVS DBA_CONSTRAINTS DBA_CONS_COLUMNS DBA_DATA_FILES DBA_DB_LINKS DBA_DDL_LOCKS DBA_DEPENDENCIES DBA_DML_LOCKS DBA_ERRORS DBA_EXP_FILES DBA_EXP_OBJECTS DBA_EXP_VERSION DBA_EXTENTS DBA_FREE_SPACE DBA_INDEXES DBA_IND_COLUMNS DBA_LOCKS DBA_OBJECTS DBA_OBJECT_SIZE DBA_OBJ_AUDIT_OPTS DBA_PRIV_AUDIT_OPTS DBA_PROFILES

Description AUdit trail entries created by the AUDIT EXISTS command. Synonym for USER_AUDIT_OBJECT. Synonym for USER_AUDIT_SESSION. Synonym for USER_AUDIT_STATEMENT. Synonym for USER_AUDIT_TRAIL. Sessions holding a lock someone wants. All database tables, views, synonyms, and sequences. Description of all clusters in the database. Mapping of table columns to cluster columns. COmments on columns of all tables and views. All grants on columns in the database. Constraint definitions on accessible tables. Information about accessible columns in constraint definitions. Information about database files. All database links in the database. All DDL locks held and requested. Dependencies to and from all objects. All DML locks held and requested. Current errors on all stored objects in the database. Description of export files. Objects that have been incrementally exported. Version number of the last export session. Extents of all segments in the database. Free extents in all tablespace. Description for all indexes in the database. Columns on indexes on all tables and clusters. All locks held and requested. All objects in the database. All PL/SQL objects. AUditing options for all tables and views. Auditing options for privileges. Profiles assigned to each user.

67

View DBA_ROLE_PRIVS DBA_ROLES DBA_ROLLBACK_SEGS DBA_SEGMENTS DBA_SEQUENCES DBA_SNAPSHOTS DBA_SNAPSHOT_LOGS DBA_SOURCE DBA_STMT_AUDIT_OPTS DBA_SYNONYMS DBA_SYS_PRIVS DBA_TABLES DBA_TABLESPACES DBA_TAB_COLUMNS DBA_TAB_COMMENTS DBA_TAB_PRIVS DBA_TRIGGERS DBA_TS_QUOTAS DBA_USERS DBA_VIEWS DBA_WAITERS DBMS_ALERT_INFO DBMS_LOCK_ALLOCATED DEPTREE DICT DICTIONARY DICT_COLUMNS ERROR_COLUMNS GLOBAL_NAME IDEPTREE IND

Description Description of roles granted to users and to roles. All roles that exist in the database. Description of roles granted to users and to roles. Storage allocated for all database segments. Description of all sequences in the database. All snapshots in the database. All snapshot logs in the database. Text source of all stored objects in the database. Describes current system auditing options across the system and by user All synonyms in the database. description of system privileges granted to users and to roles. Description of all tables in the database. Description of all tablespace in the database. Columns of all tables, views, and clusters. Comments on all tables and views in the database. All grants on objects in the database. Description of all triggers in the database. Tablespace quotas for all users. Information about all users of the database. Text of all views in the database. Sessions waiting for a lock. Table of registered alerts. Table of user allocated locks. Object dependency tree. Synonym for DICTIONARY. Description of data dictionary tables and views. Description of columns in data dictionary tables and views. Description of columns in data dictionary tables and views. Databases global name. Indented object dependency tree. Synonym for USER_INDEXES.

68

Document Templates

View INDEX_HISTOGRAM INDEX_STATS LOADER_COL_INFO LOADER_CONSTRAINT_INFO LOADER_INDCOL_INFO LOADER_IND_INFO LOADER_PARAM_INFO LOADERTAB_INFO LOADER_TRIGGERINFO OBJ PARSED_PIECES PARSED_SIZE PUBLIC_DEPENDENCY RESOURCE_COST ROLE_ROLE_PRIVS ROLE_SYS_PRIVS ROLE_TAB_PRIVS SEQ SESSION_PRIVS SESSION_ROLES SOURCE_SIZE STMT_AUDIT_OPTION_MAP SYN SYSTEM_PRIVILEGE_MAP TABLE_PRIVILEGES TABLE_PRIVILEGE_MAP TABS USER_AUDIT_OBJECT USER_AUDIT_SESSION

Description Index statistics from the ANALYZE INDEX VALIDATE STRUCTURE command. SQL* Loader direct load view. SQL* Loader direct load view. SQL* Loader direct load view. SQL* Loader direct load view. SQL* Loader direct load view. SQL* Loader direct load view. SQL* Loader direct load view. SQL* Loader direct load view. Synonym for USER_OBJECTS. Used for building the _OBJECT_SIZE views. Used for building the _OBJECT_SIZE views. Dependencies to and from objects. Cost for each resource. Information about roles granted to other roles. Information about system privileges granted to roles. Information about table privileges granted to roles. Synonym for USER_SEQUENCES. Privileges which are currently available to the user. Roles which the user currently has enabled. Used for building the _OBJECT_SIZE views. Description table for auditing option type codes. Synonym for USER_SYNONYMS. Description table for system privilege codes. Grants on objects for which the user is the grantor, grantee, or owner, or PUBLIC is the grantee. Description table for object privilege codes. Synonym for USER_TABLES. Audit trail records for statement concerning objects. All audit trail records concerning connections and disconnections for the user.

69

View USER_AUDIT_STATEMENT USER_AUDIT_TRAIL USER_CATALOG USER_CLUSTERS USER_CLU_COLUMNS USER_COL_COMMENTS USER_COL_PRIVS USER_COL_PRIVS_MADE USER_COL_PRIVS_RECD USER_CONSTRAINTS USER_CONS_COLUMNS USER_DB_LINKS USER_DEPENDENCIES USER_ERRORS USER_EXTENTS USER_FREE_SPACE USER_INDEXES USER_IND_COLUMNS USER_OBJECTS USER_OBJECT_SIZE USER_OBJ_AUDIT_OPTS USER_RESOURCE_LIMITS USER_ROLE__PRIVS USER_SEGMENTS USER_SEQUENCES USER_SNAPSHOTS USER_SNAPSHOT_LOGS USER_SOURCE USER_SYNONYMS USER_SYS_PRIVS

Description Audit trail entries for the following statements: grant, revoke, audit, noaudit, and ALTER SYSTEM Audit trail entries relevant to the user. Tables, views, synonyms, and sequences owned by the user. Description of users own clusters. Mapping of table columns to cluster columns. Comments on columns of users tables or views. Grants on columns for which the user is the owner, grantor, or grantee. All grants on columns of objects owned by the user. Grants on columns for which the user is the grantee. Constraint definitions on users tables. Information about columns in constraint definitions owned by the user. Database links owned by the user. Dependencies to and from a users objects. Current errors on all stored objects in the database. Extents of the segments owned by the user. Free extents in tablespace accessible to the user. Description of the users own indexes. Columns of the users indexes or on users tables. Objects owned by the user. Users PL/SQL objects. Auditing options for users own tables and views. Displays the resource limits for the current user. Roles granted to the user. Storage allocation for all database segments. Description of the users own sequences. Snapshots the user can view. All snapshot logs owned by the user. Text source of all stored objects in the database. The users private synonyms. System privileges granted to the user.

70

Document Templates

View USER_TABLES USER_TABLESPACES USER_TABCOLUMNS USER_TAB_COMMENTS USER_TAB_PRIVS USER_TAB_PRIVS_MADE USER_TAB_PRIVS_RECD USER_TRIGGERS USER_TS_QUOTAS USER_USERS USER_VIEWS

Description Description of the users own tables. Description of accessible tablespaces. Columns of users tables, views, and clusters. Comments on the tables and views owned by the user. Grants on objects for which the user is the owner, grantor, or grantee. All grants on objects owned by the user. Grants on objects for which the user is the grantee. Description of the users triggers. Tablespace quotas for the user. Information about the current user. Text of views owned by the user.

Dynamic Performance Tables


The system performance tables are accessible to the user SYS. Table V$ACCESS V$ARCHIVE V$BACKUP V$BGPROCESS V$CIRCUITS V$DATABASE V$DATAFILE V$DBFILE V$DB_OBJECT_CACHE V$DISPATCHERS V$ENABLEDPRIVS V$FILESTAT V$INSTANCE V$LATCH Description Describes the owners of tables. information on archive logs. Backup status of online data files. Describes the background processes. information on virtual circuits. Database information from the control file. Data file information from the control file. information about each database file in the database. Shows objects cached in the library cache. Information on the dispatcher processes. information about enabled privileges. information about file read/write statistics. State of the current instance. Information about each type of latch. (The rows of this table and the rows. of V$LATCHNAME correspond onetoone.)

71

Table V$LATCHHOLDER V$LATCHNAME

Description Information about the current latch holders. The decoded latch names for the latches shown in table V$LATCH. (The rows of this tale and the rows of V$LATCH correspond onetoone.) Statistics on library cache management. Information on license limits. SQL* Loader direct statistics. SQL* Loader direct statistics. Information about locks and resources. Log information from the control file. Log history information from the control file. Archived log names. Information about redo log files. Current values of NLS parameters. Cursors that each session has open and parsed. Information about current parameter values. Information about currently active processes. Information on multithread message queues. Archived logs needed for media recovery. Status of files needing media recovery. Status of files needing media recovery. Histogram of lock request times. Information about resources. Names of rollback segments (Although this table has no join key with V$ROLLSTAT, the rows on the two tables correspond onetoone.) Statistics for data dictionary activity: each row contains statistics for one data dictionary cache. Trusted ORACLE view of secondary mounted databases. Session information for each current session. For each current session, the current statistics values. Wait status of active sessions. User session I/O statistics.

V$LIBRARYCACHE V$LICENSE V$LOADSTAT V$LOADSTAT V$LOCK V$LOG V$LOGHIST V$LOG_HISTORY V$LOGFILE V$NLS_PARAMETERS V$OPEN_CURSOR V$PARAMETER V$PROCESS V$QUEUES V$RECOVERY_LOG V$RECOVER_FILE V$REQDIST V$RESOURCE V$ROLLNAME V$ROLLSTAT

V$ROWCACHE V$SECONDARY V$SESSION V$SESSTAT V$SESSION_WAIT V$SESS_IO

72

Document Templates

Table V$SGA V$SGASTAT V$SHARED_SERVERS V$SQLAREA V$SQLTEXT V$STATNAME V$SYSLABEL V$SYSSTAT V$THREAD V$TIMER V$TRANSACTION V$TYPE_SIZE V$VERSION V$WAISTAT

Description Information about the System Global Area. Detailed statistics on the SGA. Information on shared server processes. Statistics on the shared cursor cache. Full text of cached SQL statements. Decoded statistic names for the statistics. Trusted ORACLE view of system labels. The current systemwide value for each statistic in table V$SESSTAT. Thread information from the control file. Current time in hundredths of seconds. Information about transactions. Sizes of database components. Versions of core library components. Block contention statistics.

Readers Comment Form


ORACLE7 Server SQL language Quick Reference
Part Np. 5421701292 December 1993 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. Did you find any erros? In the information clearly presented? Do you need more information? If so, where? Are the examples correnct? 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 topic, chapter and page number below:

73

Please mail or FAX your comments to: ORACLE7 Server Documentaiton Manager Oracle Corporation 500 Oracle Parkway Redwood Shores, CA 94065 (415) 5067000 FAX: (415) 5067200 If you would like a reply, please give your name, address, and telephone number below:

Thank you for helping us improve our documentation.

74

Document Templates

Вам также может понравиться