Sunteți pe pagina 1din 412

Copyright 2004, Oracle. All rights reserved.

Oracle SQL & PL/SQL

Huiyun Mao Yolanda.mao@oracle.com

Copyright 2004, Oracle. All rights reserved.

SQL Overview

Copyright 2004, Oracle. All rights reserved.

SQL Statements
SELECT INSERT UPDATE DELETE CREATE ALTER DROP RENAME TRUNCATE COMMIT ROLLBACK SAVEPOINT GRANT REVOKE
Copyright 2004, Oracle. All rights reserved.

Data retrieval language (DRL) Data manipulation language (DML)

Data definition language (DDL)

Transaction control

Data control language (DCL)

Tables Used in the Course


Three main tables are used in this course: Three main tables are used in this course:

EMP table EMP table DEPT table DEPT table

Copyright 2004, Oracle. All rights reserved.

The EMP Table


EMP
EMPNO --------7839 7698 7782 7566 7654 7499 7844 7900 7521 7902 7369 7788 7876 7934 ENAME ---------KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH SCOTT ADAMS MILLER JOB MGR HIREDATE SAL COMM DEPTNO --------- --------- --------- --------- --------- --------PRESIDENT 17-NOV-81 5000 10 MANAGER 7839 01-MAY-81 2850 30 MANAGER 7839 09-JUN-81 1500 10 MANAGER 7839 02-APR-81 2975 20 SALESMAN 7698 28-SEP-81 1250 1400 30 SALESMAN 7698 20-FEB-81 1600 300 30 SALESMAN 7698 08-SEP-81 1500 0 30 CLERK 7698 03-DEC-81 950 30 SALESMAN 7698 22-FEB-81 1250 500 30 ANALYST 7566 03-DEC-81 3000 20 CLERK 7902 17-DEC-80 800 20 ANALYST 7566 09-DEC-82 3000 20 CLERK 7788 12-JAN-83 1100 20 CLERK 7782 23-JAN-82 1300 10

Primary key
Copyright 2004, Oracle. All rights reserved.

Foreign key

Foreign key

DEPT Tables
DEPT
DEPTNO DNAME LOC --------- -------------- ---------10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS NEW YORK DALLAS CHICAGO BOSTON

Primary key

Copyright 2004, Oracle. All rights reserved.

Writing Basic SQL Statements

Copyright 2004, Oracle. All rights reserved.

Capabilities of SQL SELECT Statements


Restriction Projection

Table 1

Table 1

Join

Table 1
Copyright 2004, Oracle. All rights reserved.

Table 2

Basic SELECT Statement


SELECT FROM [WHERE [GROUP BY [ORDER BY

[DISTINCT] {*, column [alias],...} table condition(s)] group_by_expression] column];

SELECT identifies the columns to be displayed. SELECT identifies the columns to be displayed. FROM identifies the table that contains the columns. FROM identifies the table that contains the columns.

Copyright 2004, Oracle. All rights reserved.

Writing SQL Statements


SQL statements are not case sensitive. SQL statements are not case sensitive. SQL statements can be on one or SQL statements can be on one or more lines. more lines. Keywords cannot be abbreviated or split across lines. Keywords cannot be abbreviated or split across lines. Clauses are usually placed on Clauses are usually placed on separate lines. separate lines. Tabs and indents are used to enhance readability. Tabs and indents are used to enhance readability.

Copyright 2004, Oracle. All rights reserved.

Retrieving All Columns from a Table


DEPT
DEPTNO DNAME 10 20 30 40 ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON

Retrieve all columns from the DEPT table

DEPT
DEPTNO DNAME 10 20 30 40 ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON

All columns are displayed


Copyright 2004, Oracle. All rights reserved.

Selecting All Columns


SQL> SELECT * 2 FROM dept;

DEPTNO --------10 20 30 40

DNAME -------------ACCOUNTING RESEARCH SALES OPERATIONS

LOC ------------NEW YORK DALLAS CHICAGO BOSTON

Copyright 2004, Oracle. All rights reserved.

Creating a Projection on a Table


DEPT
DEPTNO DNAME 10 20 30 40 ACCOUNTING RESEARCH SALES OPERATIONS LOC NEW YORK DALLAS CHICAGO BOSTON

Retrieve DEPTNO and LOC columns from the DEPT table

DEPT
DEPTNO LOC 10 20 30 40 NEW YORK DALLAS CHICAGO BOSTON

Only two columns are displayed


Copyright 2004, Oracle. All rights reserved.

Selecting Specific Columns


SQL> SELECT deptno, loc 2 FROM dept; DEPTNO --------10 20 30 40 LOC ------------NEW YORK DALLAS CHICAGO BOSTON

Copyright 2004, Oracle. All rights reserved.

Default Column Justification


Character left justified Date left justified Number right justified

EMP ENAME HIREDATE SAL ---------- --------- --------KING 17-NOV-81 5000 BLAKE 01-MAY-81 2850 CLARK 09-JUN-81 2450 JONES 02-APR-81 2975 MARTIN 28-SEP-81 1250 ALLEN 20-FEB-81 1600 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Arithmetic Expressions
Create expressions on NUMBER and DATE data Create expressions on NUMBER and DATE data types by using arithmetic operators. types by using arithmetic operators.

Operator + * /

Description Add Subtract Multiply Divide

Copyright 2004, Oracle. All rights reserved.

Using Arithmetic Operators


SQL> SELECT ename, sal, sal+300 2 FROM emp; ENAME SAL SAL+300 ---------- --------- --------KING 5000 5300 BLAKE 2850 3150 CLARK 2450 2750 JONES 2975 3275 MARTIN 1250 1550 ALLEN 1600 1900 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Using Arithmetic Operators on Multiple Columns


SQL> SELECT grade, hisal-losal 2 FROM salgrade; GRADE HISAL-LOSAL --------- ----------1 500 2 199 3 599 4 999 5 6998

Copyright 2004, Oracle. All rights reserved.

Operator Precedence

/ +

Multiplication and division take priority over addition Multiplication and division take priority over addition and subtraction. and subtraction. Operators of the same priority are evaluated from left to Operators of the same priority are evaluated from left to right. right. Parentheses are used to force prioritized evaluation Parentheses are used to force prioritized evaluation and to clarify statements. and to clarify statements.

Copyright 2004, Oracle. All rights reserved.

Operator Precedence
SQL> SELECT ename, sal, 12*sal+100 2 FROM emp; ENAME SAL 12*SAL+100 ---------- --------- ---------KING 5000 60100 BLAKE 2850 34300 CLARK 2450 29500 JONES 2975 35800 MARTIN 1250 15100 ALLEN 1600 19300 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Using Parentheses
SQL> SELECT ename, sal, 12*(sal+100) 2 FROM emp; ENAME SAL 12*(SAL+100) ---------- --------- ----------KING 5000 61200 BLAKE 2850 35400 CLARK 2450 30600 JONES 2975 36900 MARTIN 1250 16200 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Defining a Column Alias


Renames a column heading Renames a column heading Is useful with calculations Is useful with calculations Immediately follows column name; optional AS Immediately follows column name; optional AS keyword between column name and alias keyword between column name and alias Requires double quotation marks if it is case sensitive Requires double quotation marks if it is case sensitive or contains spaces or special characters or contains spaces or special characters

Copyright 2004, Oracle. All rights reserved.

Using Column Aliases

SQL> SELECT ename AS name, sal salary 2 FROM emp; NAME SALARY ------------- --------KING 5000 BLAKE 2850 CLARK 2450 JONES 2975 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Using Column Aliases

SQL> SELECT ename "Name", 2 sal*12 "Annual Salary" 3 FROM emp; Name Annual Salary ------------- ------------KING 60000 BLAKE 34200 CLARK 29400 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Concatenation Operator

Concatenates columns or character strings to other Concatenates columns or character strings to other columns columns Is represented by two vertical bars || Is represented by two vertical bars || Creates a result column that is a character expression Creates a result column that is a character expression

Copyright 2004, Oracle. All rights reserved.

Using the Concatenation Operator

SQL> SELECT 2 FROM

ename||job AS "Employees" emp;

Employees ------------------KINGPRESIDENT BLAKEMANAGER CLARKMANAGER JONESMANAGER MARTINSALESMAN ALLENSALESMAN ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Literals

A literal is a constant value of character, expression, or A literal is a constant value of character, expression, or number that can be included in the SELECT list. number that can be included in the SELECT list. Date and character literal values must be enclosed in Date and character literal values must be enclosed in single quotation marks. single quotation marks. Each character string is output once for each row Each character string is output once for each row returned. returned.

Copyright 2004, Oracle. All rights reserved.

Using Literal Character Strings


SQL> SELECT ename||' is a '||job AS 2 "Employee Details" 3 FROM emp; Employee Details ------------------------KING is a PRESIDENT BLAKE is a MANAGER CLARK is a MANAGER JONES is a MANAGER MARTIN is a SALESMAN ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Duplicate Rows
The default display of queries is all rows, including The default display of queries is all rows, including duplicate rows. duplicate rows.
SQL> SELECT 2 FROM deptno emp;

DEPTNO --------10 30 10 20 .. 14 rows selected.


Copyright 2004, Oracle. All rights reserved.

Eliminating Duplicate Rows


Eliminate duplicate rows by using the DISTINCT Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause. keyword in the SELECT clause.
SQL> SELECT DISTINCT deptno 2 FROM emp;

DEPTNO --------10 20 30

Copyright 2004, Oracle. All rights reserved.

Restricting and Sorting Data

Copyright 2004, Oracle. All rights reserved.

Limiting Rows by Using a Restriction


EMP
EMPNO ENAME 7839 7698 7782 7566 ... KING BLAKE CLARK JONES JOB PRESIDENT MANAGER MANAGER MANAGER ... DEPTNO 10 30 10 20

Retrieve all employees in department 10

EMP
EMPNO ENAME JOB ... DEPTNO 10 10 10

7839 KING PRESIDENT 7782 CLARK MANAGER 7934 MILLER CLERK

Copyright 2004, Oracle. All rights reserved.

Using the WHERE Clause


SQL> SELECT ename, job, deptno 2 FROM emp 3 WHERE deptno=10;

ENAME ---------KING CLARK MILLER

JOB DEPTNO --------- --------PRESIDENT 10 MANAGER 10 CLERK 10

Copyright 2004, Oracle. All rights reserved.

Character Strings and Dates


Character strings and date values are enclosed in Character strings and date values are enclosed in single quotation marks. single quotation marks. Character values are case sensitive and date values Character values are case sensitive and date values are format sensitive. are format sensitive. Default date format is DD-MON-YY. Default date format is DD-MON-YY.

SQL> SELECT 2 FROM 3 WHERE

ename, job, deptno, hiredate emp ename = 'JAMES';

Copyright 2004, Oracle. All rights reserved.

Comparison Operators
Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to

Copyright 2004, Oracle. All rights reserved.

Using the Comparison Operators with Another Column

SQL> SELECT ename, sal, comm 2 FROM emp 3 WHERE sal<=comm;

ENAME SAL COMM ---------- --------- --------MARTIN 1250 1400

Copyright 2004, Oracle. All rights reserved.

Using the Comparison Operators with Characters

SQL> SELECT ename, mgr 2 FROM emp 3 WHERE ename='SMITH';

ENAME MGR ---------- --------SMITH 7902

Copyright 2004, Oracle. All rights reserved.

Other SQL Comparison Operators

Operator BETWEEN ...AND... IN(list) LIKE IS NULL

Meaning Between two values (inclusive)

Match any of a list of values Match a character pattern Is a null value

Copyright 2004, Oracle. All rights reserved.

Using the BETWEEN Operator


Use the BETWEEN operator to display rows based on Use the BETWEEN operator to display rows based on a range of values. a range of values.
SQL> SELECT 2 FROM 3 WHERE ename, sal emp sal BETWEEN 1000 AND 1500;

ENAME SAL ---------- --------MARTIN 1250 TURNER 1500 WARD 1250 ADAMS 1100 MILLER 1300

Lower limit

Higher limit

Copyright 2004, Oracle. All rights reserved.

Using the IN Operator


Use the IN operator to test for values in a list. Use the IN operator to test for values in a list.

SQL> SELECT 2 FROM 3 WHERE

empno, ename, sal, mgr emp mgr IN (7902, 7566, 7788);

EMPNO --------7902 7369 7788 7876

ENAME SAL MGR ---------- --------- --------FORD 3000 7566 SMITH 800 7902 SCOTT 3000 7566 ADAMS 1100 7788

Copyright 2004, Oracle. All rights reserved.

Using the IN Operator with Strings


Use the IN operator to test for values in a list of Use the IN operator to test for values in a list of strings. strings.
SQL> SELECT ename, deptno, hiredate 2 FROM emp 3 WHERE ename IN ('BLAKE','MARTIN');

ENAME DEPTNO HIREDATE ---------- --------- --------BLAKE 30 01-MAY-81 MARTIN 30 28-SEP-81

Copyright 2004, Oracle. All rights reserved.

Using the LIKE Operator


Use the LIKE operator to perform wildcard searches of Use the LIKE operator to perform wildcard searches of valid search string values. valid search string values. Search conditions can contain either literal characters Search conditions can contain either literal characters or numbers. or numbers.
% denotes zero or many characters % denotes zero or many characters _ denotes one character _ denotes one character

SQL> SELECT 2 FROM 3 WHERE


Copyright 2004, Oracle. All rights reserved.

ename emp ename LIKE 'S%';

Using the LIKE Operator


You can combine pattern matching You can combine pattern matching characters. characters.
SQL> SELECT 2 FROM 3 WHERE ename emp ename LIKE '_A%';

ENAME ---------MARTIN JAMES WARD

Use the ESCAPE identifier to search for Use the ESCAPE identifier to search for % or _. % or _.
Copyright 2004, Oracle. All rights reserved.

Using the IS NULL Operator


Test for null values with the IS NULL operator. Test for null values with the IS NULL operator.
SQL> SELECT 2 FROM 3 WHERE ename, mgr emp mgr IS NULL;

ENAME MGR ---------- --------KING

Copyright 2004, Oracle. All rights reserved.

Logical Operators

Operator AND OR

Meaning Returns TRUE if both component conditions are TRUE Returns TRUE if either component condition is TRUE Returns TRUE if the following condition is FALSE

NOT

Copyright 2004, Oracle. All rights reserved.

Using the AND Operator


AND requires both conditions to be TRUE. AND requires both conditions to be TRUE.
SQL> 2 3 4 SELECT FROM WHERE AND empno, ename, job, sal emp sal>=1100 job='CLERK';

EMPNO --------7876 7934

ENAME ---------ADAMS MILLER

JOB SAL --------- --------CLERK 1100 CLERK 1300

Copyright 2004, Oracle. All rights reserved.

Using the AND Operator


AND requires both conditions to be TRUE. AND requires both conditions to be TRUE.
SQL> 2 3 4 SELECT FROM WHERE AND ename, mgr, sal,deptno emp sal>1000 deptno = 10;

ENAME MGR SAL DEPTNO ---------- --------- --------- --------KING 5000 10 CLARK 7839 2450 10 MILLER 7782 1300 10

Copyright 2004, Oracle. All rights reserved.

Using the OR Operator


OR requires either condition to be TRUE. OR requires either condition to be TRUE.
SQL> 2 3 4 SELECT FROM WHERE OR empno, ename, job, sal emp sal>=2000 job='CLERK'; JOB SAL --------- --------PRESIDENT 5000 MANAGER 2850 MANAGER 2450 MANAGER 2975 CLERK 950 ANALYST 3000

EMPNO ENAME --------- ---------7839 KING 7698 BLAKE 7782 CLARK 7566 JONES 7900 JAMES 7902 FORD ... 10 rows selected.
Copyright 2004, Oracle. All rights reserved.

Using the OR Operator


OR requires either condition to be TRUE. OR requires either condition to be TRUE.

SQL> 2 3 4

SELECT FROM WHERE OR

ename, deptno, mgr emp deptno = 10 mgr = 7839;

ENAME ---------KING BLAKE CLARK JONES MILLER

DEPTNO -------10 30 10 20 10

MGR --------7839 7839 7839 7782

Copyright 2004, Oracle. All rights reserved.

Using the NOT Operator


SQL> SELECT ename, job 2 FROM emp 3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');

ENAME ---------KING MARTIN ALLEN TURNER WARD

JOB --------PRESIDENT SALESMAN SALESMAN SALESMAN SALESMAN

Copyright 2004, Oracle. All rights reserved.

Using the NOT Operator


SQL> SELECT empno,ename,deptno,mgr 2 FROM emp 3 WHERE mgr NOT LIKE '78%';

EMPNO ENAME DEPTNO MGR --------- ---------- --------- --------7654 MARTIN 30 7698 7499 ALLEN 30 7698 ... ... 7902 FORD 20 7566 7369 SMITH 20 7902 ... 10 rows selected.

Copyright 2004, Oracle. All rights reserved.

Using the NOT Operator


SQL> SELECT empno, sal, mgr 2 FROM emp 3 WHERE sal NOT BETWEEN 1000 AND 1500; EMPNO SAL MGR --------- --------- --------7839 5000 7698 2850 7839 7782 2450 7839 7566 2975 7839 7499 1600 7698 7900 950 7698 7902 3000 7566 7369 800 7902 7788 3000 7566 9 rows selected.
Copyright 2004, Oracle. All rights reserved.

Using the NOT Operator


SQL> 2 3 4 SELECT ename, sal AS "Salary Before Commission", comm FROM emp WHERE comm IS NOT NULL;

ENAME Salary Before Commission COMM ---------- ------------------------ --------MARTIN 1250 1400 ALLEN 1600 300 TURNER 1500 0 WARD 1250 500

Copyright 2004, Oracle. All rights reserved.

Rules of Precedence
Order Evaluated 1 2 3 4 Operator All comparison operators NOT AND OR

Use parentheses to override rules of precedence. Use parentheses to override rules of precedence.

Copyright 2004, Oracle. All rights reserved.

Rules of Precedence
SQL> 2 3 4 5 SELECT FROM WHERE OR AND ename, job, sal emp job='SALESMAN' job='PRESIDENT' sal>1500;

ENAME ---------KING MARTIN ALLEN TURNER WARD

JOB ------PRESIDENT SALESMAN SALESMAN SALESMAN SALESMAN

SAL --------5000 1250 1600 1500 1250

Copyright 2004, Oracle. All rights reserved.

Rules of Precedence
Use parentheses to force priority. Use parentheses to force priority.
SQL> 2 3 4 5 SELECT FROM WHERE OR AND ename, job, sal emp (job='SALESMAN' job='PRESIDENT') sal>1500;

ENAME ---------KING ALLEN

JOB --------PRESIDENT SALESMAN

SAL --------5000 1600

Copyright 2004, Oracle. All rights reserved.

ORDER BY Clause

Sort rows with the ORDER BY clause: Sort rows with the ORDER BY clause:
ASC: ascending order, default ASC: ascending order, default DESC: descending order DESC: descending order

The ORDER BY clause comes last in the SELECT The ORDER BY clause comes last in the SELECT statement. statement.

SQL> SELECT ename, job, deptno 2 FROM emp 3 ORDER BY deptno; ENAME JOB DEPTNO ---------- --------- --------KING PRESIDENT 10 CLARK MANAGER 10 ... JONES MANAGER 20 SCOTT ANALYST 20 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.

Sorting in Descending Order


SQL> SELECT ename, job, deptno, sal 2 FROM emp 3 ORDER BY sal DESC;

ENAME JOB DEPTNO SAL ---------- --------- --------- --------KING PRESIDENT 10 5000 FORD ANALYST 20 3000 SCOTT ANALYST 20 3000 JONES MANAGER 20 2975 BLAKE MANAGER 30 2850 CLARK MANAGER 10 2450 ALLEN SALESMAN 30 1600 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.

Sorting by Column Alias


SQL> SELECT empno, ename, sal*12 annsal 2 FROM emp 3 ORDER BY annsal;

EMPNO ENAME ANNSAL --------- ---------- --------7369 SMITH 9600 7900 JAMES 11400 7876 ADAMS 13200 7654 MARTIN 15000 7521 WARD 15000 7934 MILLER 15600 7844 TURNER 18000 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.

Sorting by Multiple Columns


The order of an ORDER BY list is the order of the The order of an ORDER BY list is the order of the sort. sort.
SQL> SELECT ename, deptno, sal 2 FROM emp 3 ORDER BY deptno, sal DESC; ENAME DEPTNO SAL ---------- --------- --------KING 10 5000 CLARK 10 2450 MILLER 10 1300 FORD 20 3000 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.

Sorting by a Column Not in the SELECT List


SQL> SELECT ename, deptno 2 FROM emp 3 ORDER BY sal; ENAME DEPTNO ---------- --------SMITH 20 JAMES 30 ADAMS 20 MARTIN 30 WARD 30 MILLER 10 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Single-Row Number and Character Functions

Copyright 2004, Oracle. All rights reserved.

How a Function Works

Input

Function Performs operation

Output

Copyright 2004, Oracle. All rights reserved.

Two Types of SQL Functions

Functions

Single-row functions

Multiple-row functions

Copyright 2004, Oracle. All rights reserved.

Single-Row Functions

Manipulate data items Manipulate data items Accept arguments and return one value Accept arguments and return one value Act on each row returned Act on each row returned Return one result per row Return one result per row Can modify the data type Can modify the data type Can be nested Can be nested

Copyright 2004, Oracle. All rights reserved.

Single-Row Functions
Character Number

Single-row functions

Conversion

Date

Copyright 2004, Oracle. All rights reserved.

Character Functions
Character functions

Case conversion functions LOWER UPPER INITCAP

Character manipulation functions

Copyright 2004, Oracle. All rights reserved.

Case Conversion Functions


Convert the case for character strings Convert the case for character strings Function LOWER('SQL Course') UPPER('SQL Course') INITCAP('SQL Course') Result sql course SQL COURSE Sql Course

Copyright 2004, Oracle. All rights reserved.

Using Case Conversion Functions


Display the employee number, name, and department Display the employee number, name, and department number for employee Blake. number for employee Blake.
SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = 'blake'; no rows selected SQL> SELECT 2 FROM 3 WHERE empno, ename, deptno emp ename = UPPER('blake');

EMPNO ENAME DEPTNO --------- ---------- --------7698 BLAKE 30


Copyright 2004, Oracle. All rights reserved.

Using Case Conversion Functions


Display the employee name for all employees with an Display the employee name for all employees with an initial capital. initial capital.
SQL> SELECT INITCAP(ename) as EMPLOYEE 2 FROM emp; EMPLOYEE ---------King Blake Clark Jones Martin ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.

Number Functions

ROUND: Rounds value to specified decimal ROUND: Rounds value to specified decimal ROUND(45.926, 2) ROUND(45.926, 2) 45.93 45.93 TRUNC: Truncates value to specified decimal TRUNC: Truncates value to specified decimal TRUNC(45.926, 2) TRUNC(45.926, 2) 45.92 45.92 MOD: Returns remainder of division MOD: Returns remainder of division MOD(1600, 300) MOD(1600, 300) 100 100

Copyright 2004, Oracle. All rights reserved.

Defining a Null Value


A null is a value that is unavailable, unassigned, A null is a value that is unavailable, unassigned, unknown, or inapplicable. unknown, or inapplicable. A null is not the same as zero or a blank space. A null is not the same as zero or a blank space.

SQL> SELECT 2 FROM

ename, job, comm emp;

ENAME JOB COMM ---------- --------- --------KING PRESIDENT BLAKE MANAGER ... TURNER SALESMAN 0 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.

Null Values in Arithmetic Expressions


Arithmetic expressions that contain a null value Arithmetic expressions that contain a null value evaluate to null. evaluate to null.
SQL> SELECT ename NAME, 12*sal+comm 2 FROM emp; NAME 12*SAL+COMM ---------- ----------KING BLAKE CLARK JONES MARTIN 16400 ... 14 rows selected.
Copyright 2004, Oracle. All rights reserved.

Using the NVL Function


NVL (expr1, expr2)

Use the NVL function to force a value where a null Use the NVL function to force a value where a null would otherwise appear: would otherwise appear:

NVL can be used with date, character, and number NVL can be used with date, character, and number data types. data types. Data types must match. For example: Data types must match. For example:
NVL(comm,0) NVL(comm,0) NVL(hiredate,'01-JAN-97') NVL(hiredate,'01-JAN-97') NVL(job,'no job yet') NVL(job,'no job yet' yet')

Copyright 2004, Oracle. All rights reserved.

Using the NVL Function to Handle Null Values


SQL> SELECT ename, job, sal * 12 + NVL(comm,0) 2 FROM emp; ENAME JOB SAL*12+NVL(COMM,0) ---------- --------- -----------------KING PRESIDENT 60000 BLAKE MANAGER 34200 CLARK MANAGER 29400 JONES MANAGER 35700 MARTIN SALESMAN 16400 ALLEN SALESMAN 19500 TURNER SALESMAN 18000 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Single-Row Date and Conversion Functions

Copyright 2004, Oracle. All rights reserved.

Single-Row Functions
Character Number

Single-row functions

Conversion

Date

Copyright 2004, Oracle. All rights reserved.

Working with Dates


Oracle stores dates in an internal 7 byte numeric format: Oracle stores dates in an internal 7 byte numeric format: century, year, month, day, hours, minutes, seconds. century, year, month, day, hours, minutes, seconds. The default date format is DD-MON-YY. The default date format is DD-MON-YY.

Copyright 2004, Oracle. All rights reserved.

SYSDATE

Use SYSDATE to display the current date and time. Use SYSDATE to display the current date and time. DUAL is a one-column, one-row table that is used as a DUAL is a one-column, one-row table that is used as a dummy table. dummy table.

SQL> SELECT SYSDATE 2 FROM DUAL; SYSDATE --------26-JAN-98

Copyright 2004, Oracle. All rights reserved.

Default Date Formats


Columns that are defined as DATE are Columns that are defined as DATE are displayed as DD-MON-YY by default. displayed as DD-MON-YY by default.
SQL> SELECT ename, hiredate 2 FROM emp 3 WHERE ename='SMITH';

ENAME HIREDATE ---------- --------SMITH 17-DEC-80

Copyright 2004, Oracle. All rights reserved.

Arithmetic with Dates


Add or subtract a number to or from a date to obtain a date Add or subtract a number to or from a date to obtain a date value value Subtract two dates to find the number of days between Subtract two dates to find the number of days between those dates those dates

Copyright 2004, Oracle. All rights reserved.

Using Arithmetic Operators with Dates


SQL> SELECT ename, hiredate, hiredate+30 "NEW DATE" 2 FROM emp 3 WHERE ename='SMITH';

ENAME HIREDATE NEW DATE ---------- --------- --------SMITH 17-DEC-80 16-JAN-81

Copyright 2004, Oracle. All rights reserved.

Using SYSDATE in Calculations


Determine for how many weeks employees have Determine for how many weeks employees have worked worked
SQL> SELECT ename, (SYSDATE-hiredate)/7 2 "WEEKS AT WORK" 3 FROM emp 4 WHERE deptno=10; ENAME WEEKS AT WORK ---------- ------------KING 844.94617 CLARK 867.94617 MILLER 835.37474

Copyright 2004, Oracle. All rights reserved.

Explicit Data Type Conversion


TO_NUMBER TO_DATE

NUMBER

CHARACTER

DATE

TO_CHAR

TO_CHAR

Copyright 2004, Oracle. All rights reserved.

Modifying the Display Format of Dates

Tuesday the 27th of January, 1998 27-JAN-98 January 27, 1998 01/27/98

Copyright 2004, Oracle. All rights reserved.

TO_CHAR Function with Dates


TO_CHAR(date, 'fmfmt')

The format model: The format model:


Is case sensitive and must be enclosed in single Is case sensitive and must be enclosed in single quotation marks quotation marks Can include any valid date format element Can include any valid date format element Has an fm element to remove padded blanks or Has an fm element to remove padded blanks or suppress leading zeros suppress leading zeros Is separated from the date value by a comma Is separated from the date value by a comma

Copyright 2004, Oracle. All rights reserved.

Date Format Model Elements


YYYY YEAR MM MONTH DY DAY Full year in numbers Year spelled out 2-digit value for month Full name of the month 3-letter abbreviation of the day of the week Full name of the day

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Dates


SQL> SELECT ename, TO_CHAR(hiredate, 'Month DDth, YYYY') 2 3 4 ENAME BLAKE CLARK JONES AS HIREDATE FROM emp WHERE job='MANAGER'; HIREDATE May June April 01st, 1981 09th, 1981 02nd, 1981

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

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Dates


SQL> SELECT 2 FROM 3 WHERE empno, TO_CHAR(hiredate, 'MM/YY') AS MONTH emp ename='BLAKE';

EMPNO MONTH --------- ----7698 05/81

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Dates


SQL> SELECT ename, 2 TO_CHAR(hiredate, 'fmDD Month YYYY') AS HIREDATE 3 FROM emp;

ENAME HIREDATE ---------- ----------------KING 17 November 1981 BLAKE 1 May 1981 CLARK 9 June 1981 JONES 2 April 1981 MARTIN 28 September 1981 ALLEN 20 February 1981 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Dates


SQL> 2 3 4 5 SELECT ename, mgr, sal,TO_CHAR(hiredate,'YYYY-MON-DD') AS HIREDATE FROM emp WHERE sal<1000 AND hiredate like '%80';

ENAME MGR SAL HIREDATE ---------- --------- --------- ----------SMITH 7902 800 1980-DEC-17

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Dates


SQL> 2 3 4 SELECT empno,ename,deptno,TO_CHAR(hiredate,'MM-DD-YYYY') AS HIREDATE FROM emp WHERE hiredate NOT LIKE '%81';

EMPNO -------7369 7788 7876 7934

ENAME DEPTNO HIREDATE ---------- --------- ----------SMITH 20 12-17-1980 SCOTT 20 12-09-1982 ADAMS 20 01-12-1983 MILLER 10 01-23-1982

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Dates


SQL> 2 3 4 SELECT ename, job, deptno, TO_CHAR(hiredate,'DD-MON-YYYY') AS HIRE_DATE FROM emp ORDER BY hiredate DESC;

ENAME JOB DEPTNO HIRE_DATE ---------- --------- --------- ----------ADAMS CLERK 20 12-JAN-1983 SCOTT ANALYST 20 09-DEC-1982 MILLER CLERK 10 23-JAN-1982 JAMES CLERK 30 03-DEC-1981 FORD ANALYST 20 03-DEC-1981 KING PRESIDENT 10 17-NOV-1981 MARTIN SALESMAN 30 28-SEP-1981 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Date Format Model Elements



Time elements format the time portion of the date. Time elements format the time portion of the date. 15:45:32 PM

HH24:MI:SS AM

DD "of" MONTH

12 of OCTOBER

ddspth

fourteenth

Copyright 2004, Oracle. All rights reserved.

Using Format Models to Display Time

SQL> SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') TIME 2 FROM DUAL;

TIME -------13:55:46

Copyright 2004, Oracle. All rights reserved.

TO_CHAR Function with Numbers


TO_CHAR(n,'fmt') Use these formats with the TO_CHAR function to Use these formats with the TO_CHAR function to display a number value as a character: display a number value as a character:

9 0 $ L . ,

Represents a number Forces a zero to be displayed Places a floating dollar sign Uses the floating local currency symbol Prints a decimal point Places a thousand indicator

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with Numbers

SQL> SELECT 2 FROM 3 WHERE

TO_CHAR(sal,'$99,999') SALARY emp ename = 'SCOTT';

SALARY -------$3,000

Thousand indicator Dollar sign

Copyright 2004, Oracle. All rights reserved.

Using the TO_NUMBER and TO_DATE Functions


Convert a character string to a number data type using the Convert a character string to a number data type using the TO_NUMBER function TO_NUMBER function

TO_NUMBER(char)

Convert a character string to a date data Convert a character string to a date data type using the TO_DATE function type using the TO_DATE function
TO_DATE(char[, 'fmt'])

Copyright 2004, Oracle. All rights reserved.

Using the TO_NUMBER Function

SQL> SELECT 2 FROM 3 WHERE

TO_NUMBER('1000')+sal AS NEW_SALARY emp ename = 'SCOTT';

NEW_SALARY ---------4000

Copyright 2004, Oracle. All rights reserved.

Date Functions
FUNCTION MONTHS_BETWEEN ADD_MONTHS NEXT_DAY LAST_DAY ROUND TRUNC DESCRIPTION Number of months between two dates Adds calendar months to date Next day following the date specified Last day of the month Round off date Truncate date

Copyright 2004, Oracle. All rights reserved.

Using Date Functions


Use the ADD_MONTHS function to add months to Use the ADD_MONTHS function to add months to a date. a date.
SQL> 2 3 4 SELECT ename, hiredate, ADD_MONTHS(hiredate, 6) AS "+6 MONTHS" FROM emp WHERE ename='BLAKE';

ENAME HIREDATE +6 MONTHS ---------- --------- --------BLAKE 01-MAY-81 01-NOV-81

Copyright 2004, Oracle. All rights reserved.

Nesting Functions

Single-row functions can be nested to any level. Single-row functions can be nested to any level. Nested functions are evaluated from the innermost level to Nested functions are evaluated from the innermost level to the outermost level. the outermost level.

F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1 Step 2 = Result 2 Step 3 = Result 3

Copyright 2004, Oracle. All rights reserved.

Nesting Functions
Result 1
SQL> SELECT 2 3 FROM 4 WHERE

Result 2

ename, NVL(TO_CHAR(mgr),'No Manager') emp mgr IS NULL;

ENAME NVL(TO_CHAR(MGR),'NOMANAGER') ---------- ----------------------------KING No Manager

Copyright 2004, Oracle. All rights reserved.

Nesting Functions
SQL> SELECT MONTHS_BETWEEN 2 (TO_DATE('02-02-1995','MM-DD-YYYY'), 3 TO_DATE('01-01-1995','MM-DD-YYYY')) 4 "Months" 5 FROM DUAL;

Months ---------1.03225806

Copyright 2004, Oracle. All rights reserved.

Displaying Data from Multiple Tables

Copyright 2004, Oracle. All rights reserved.

Obtaining Data from Multiple Tables Obtaining Data from Multiple Tables
EMP
EMPNO -----7839 7698 ... 7934 ENAME ----KING BLAKE ... DEPTNO ... -----... 10 ... 30 10

DEPT
DEPTNO -----10 20 30 40 DNAME ---------ACCOUNTING RESEARCH SALES OPERATIONS LOC -------NEW YORK DALLAS CHICAGO BOSTON

MILLER ...

EMPNO ----7839 7698 7782 7566 7654 7499

DEPTNO ------10 30 10 20 30 30

LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO

Copyright 2004, Oracle. All rights reserved.

Joining Tables
Use a join to query data from more than one table: Use a join to query data from more than one table:

SELECT table1.column1, table2.column2 FROM table1, table2 WHERE Write the join condition in the WHERE clause. table1.column1 = table2.column2; Write the join condition in the WHERE clause.

Prefix the column name with the table name when the Prefix the column name with the table name when the same column name appears in more than one table. same column name appears in more than one table.

Copyright 2004, Oracle. All rights reserved.

Types of Joins
Equijoin Nonequijoin Self join Equijoin Nonequijoin Self join

Copyright 2004, Oracle. All rights reserved.

What Is an Equijoin?
EMP
EMPNO ENAME DEPTNO ------ ------- ------... 7782 CLARK 10

DEPT
DEPTNO DNAME LOC ------- ---------- -------... 10 ACCOUNTING NEW YORK ...

Links rows that satisfy a specified condition

WHERE emp.deptno=dept.deptno

Copyright 2004, Oracle. All rights reserved.

Equijoin
EMP
EMPNO ENAME DEPTNO ------ ------- ------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 ... 14 rows selected. Foreign key
Copyright 2004, Oracle. All rights reserved.

DEPT
DEPTNO ------10 30 10 20 30 30 30 30 30 20 20 ... 14 rows DNAME ---------ACCOUNTING SALES ACCOUNTING RESEARCH SALES SALES SALES SALES SALES RESEARCH RESEARCH selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO CHICAGO DALLAS DALLAS

Primary key

Retrieving Records with an Equijoin


SQL> SELECT 2 3 FROM 4 WHERE emp.empno, emp.ename, emp.deptno, dept.deptno, dept.loc emp, dept emp.deptno=dept.deptno;

EMPNO ENAME DEPTNO DEPTNO LOC ----- ------ ------ ------ --------7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Qualifying Ambiguous Column Names


Use table prefixes to qualify column names that are in Use table prefixes to qualify column names that are in multiple tables. multiple tables. Use table prefixes to improve performance. Use table prefixes to improve performance.

Copyright 2004, Oracle. All rights reserved.

Additional Search Conditions Using the AND Operator


EMP
EMPNO ENAME DEPTNO ------ ------- ------7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 ... 14 rows selected.

DEPT
DEPTNO DNAME ------ --------10 ACCOUNTING 30 SALES 10 ACCOUNTING 20 RESEARCH 30 SALES 30 SALES 30 SALES 30 SALES ... 14 rows selected. LOC -------NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO CHICAGO CHICAGO

WHERE emp.deptno=dept.deptno AND ename='KING'

Copyright 2004, Oracle. All rights reserved.

Using Additional Search Conditions with a Join


SQL> 2 3 4 SELECT FROM WHERE AND emp.empno, emp.ename, emp.deptno, dept.loc emp, dept; emp.deptno = dept.deptno emp.ename = 'KING';

EMPNO ENAME DEPTNO LOC --------- ---------- --------- ------------7839 KING 10 NEW YORK

Copyright 2004, Oracle. All rights reserved.

Using Additional Search Conditions with a Join


SQL> SELECT emp.ename, emp.job, dept.deptno, dept.dname
2 3 4 FROM WHERE AND emp, dept emp.deptno=dept.deptno emp.job IN ('MANAGER','PRESIDENT');

ENAME ---------KING BLAKE CLARK JONES

JOB DEPTNO DNAME --------- --------- -------------PRESIDENT 10 ACCOUNTING MANAGER 30 SALES MANAGER 10 ACCOUNTING MANAGER 20 RESEARCH

Copyright 2004, Oracle. All rights reserved.

Table Aliases
Simplify queries by using table aliases. Simplify queries by using table aliases.
SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno;

can be written as ... can be written as ...


SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno;

Copyright 2004, Oracle. All rights reserved.

Using Table Aliases


SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno; EMPNO --------7839 7698 7782 7566 7654 7499 ... ENAME DEPTNO DEPTNO LOC ---------- --------- --------- ----------KING 10 10 NEW YORK BLAKE 30 30 CHICAGO CLARK 10 10 NEW YORK JONES 20 20 DALLAS MARTIN 30 30 CHICAGO ALLEN 30 30 CHICAGO

14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Nonequijoins
EMP
EMPNO ENAME SAL ------ ------- -----7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 ... 14 rows selected.

SALGRADE
GRADE LOSAL HISAL ----- ----- -----1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999

Salary in the EMP table is between low salary and high salary in the SALGRADE table.

Copyright 2004, Oracle. All rights reserved.

Retrieving Records with Nonequijoins


SQL> 2 3 4 SELECT FROM WHERE BETWEEN e.ename, e.sal, s.grade emp e, salgrade s e.sal s.losal AND s.hisal;

ENAME SAL GRADE ---------- --------- --------JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Joining More Than Two Tables


EMP
ENAME SAL DEPTNO ---------- --------- --------JAMES 950 30 SMITH 800 20 ADAMS 1100 20 MARTIN 1250 30 WARD 1250 30 MILLER 1300 10 14 rows selected.

DEPT
DEPTNO DNAME --------- ---------10 ACCOUNTING 20 RESEARCH 30 SALES 40 OPERATIONS

SALGRADE

LOSAL HISAL GRADE --------- --------- --------700 1200 1 WHERE emp.sal BETWEEN 1201 1400 2 salgrade.losal AND 1401 2000 3 2001 3000 4 salgrade.hisal 3001 9999 5 AND emp.deptno = dept.deptno
Copyright 2004, Oracle. All rights reserved.

Using Multiple Joins


SQL> 2 3 4 SELECT FROM WHERE AND e.ename, e.deptno, d.dname, e.sal, s.grade emp e, dept d, salgrade s e.deptno=d.deptno e.sal BETWEEN s.losal and s.hisal; DNAME SAL GRADE -------------- --------- --------SALES 950 1 RESEARCH 800 1 RESEARCH 1100 1 SALES 1250 2 SALES 1250 2 ACCOUNTING 1300 2 SALES 1600 3

ENAME DEPTNO ---------- --------JAMES 30 SMITH 20 ADAMS 20 MARTIN 30 WARD 30 MILLER 10 ALLEN 30 ... 14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Selfjoins
EMP (WORKER)
EMPNO ----7839 7698 7782 7566 7654 7499 ENAME -----KING BLAKE CLARK JONES MARTIN ALLEN MGR ---7839 7839 7839 7698 7698

EMP (MANAGER)
EMPNO ENAME ----- -------7839 7839 7839 7698 7698 KING KING KING BLAKE BLAKE

MGR in the WORKER table is equal to EMPNO in the MANAGER table.

Copyright 2004, Oracle. All rights reserved.

Joining a Table to Itself


SQL> 2 3 4 SELECT AS FROM WHERE worker.ename||' works for '||manager.ename WHO_WORKS_FOR_WHOM emp worker, emp manager worker.mgr = manager.empno;

WHO_WORKS_FOR_WHOM ------------------------------BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected.

Copyright 2004, Oracle. All rights reserved.

Aggregating Data by Using Group Functions

Copyright 2004, Oracle. All rights reserved.

What Are Group Functions?


Group functions operate on sets of rows to give one result Group functions operate on sets of rows to give one result per group. per group. EMP
DEPTNO SAL --------- --------10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250
Copyright 2004, Oracle. All rights reserved.

maximum salary in the EMP table

MAX(SAL) --------5000

Types of Group Functions


AVG AVG COUNT COUNT MAX MAX MIN MIN SUM SUM

Copyright 2004, Oracle. All rights reserved.

Guidelines for Using Group Functions


Many aggregate functions accept these Many aggregate functions accept these options: options: DISTINCT DISTINCT ALL ALL NVL NVL

Copyright 2004, Oracle. All rights reserved.

Using the AVG and SUM Functions


You can use AVG and SUM for numeric data. You can use AVG and SUM for numeric data.

SQL> SELECT 2 FROM 3 WHERE

AVG(sal), SUM(sal) emp job LIKE 'SALES%';

AVG(SAL) SUM(SAL) -------- --------1400 5600

Copyright 2004, Oracle. All rights reserved.

Using the MIN and MAX Functions


You can use MIN and MAX for any data type. You can use MIN and MAX for any data type.

SQL> SELECT 2 3 FROM

TO_CHAR(MIN(hiredate),'DD-MON-YYYY'), TO_CHAR(MAX(hiredate),'DD-MON-YYYY') emp;

T0_CHAR(MIN TO_CHAR(MAX ----------------17-DEC-1980 12-JAN-1983

Copyright 2004, Oracle. All rights reserved.

Using the MIN and MAX Functions


You can use MIN and MAX for any data type. You can use MIN and MAX for any data type.

SQL> SELECT MIN(sal) AS "Lowest Salary", 2 MAX(sal) AS "Highest Salary" 3 FROM emp; Lowest Salary Highest Salary ------------- -------------800 5000

Copyright 2004, Oracle. All rights reserved.

Using the COUNT Function


COUNT(*) returns the number of rows in a query. COUNT(*) returns the number of rows in a query.

SQL> SELECT 2 FROM 3 WHERE COUNT(*) --------6

COUNT(*) emp deptno = 30;

Copyright 2004, Oracle. All rights reserved.

Using the COUNT Function


COUNT(expr) returns the number of nonnull rows. COUNT(expr) returns the number of nonnull rows.

SQL> SELECT 2 FROM 3 WHERE COUNT(COMM) ----------4

COUNT(comm) emp deptno = 30;

Copyright 2004, Oracle. All rights reserved.

Group Functions and Null Values


Group functions ignore null values in the column. Group functions ignore null values in the column.

SQL> SELECT AVG(comm) 2 FROM emp;

AVG(COMM) --------550

Copyright 2004, Oracle. All rights reserved.

Using the NVL Function with Group Functions


The NVL function forces group functions to include The NVL function forces group functions to include null values. null values.
SQL> SELECT AVG(NVL(comm,0)) 2 FROM emp;

AVG(NVL(COMM,0)) ---------------157.14286

Copyright 2004, Oracle. All rights reserved.

Using the NVL Function with Group Functions


Average commission for all people hired in 1981 Average commission for all people hired in 1981

SQL> 2 3 4 5

SELECT FROM WHERE BETWEEN AND

AVG(NVL(comm,0)) emp hiredate TO_DATE('01-JAN-1981','DD-MON-YYYY') TO_DATE('31-DEC-1981','DD-MON-YYYY');

AVG(NVL(COMM,0)) ---------------220

Copyright 2004, Oracle. All rights reserved.

Creating Groups of Data


EMP
DEPTNO SAL --------- --------10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250

2916.6667

average salary in EMP 2175 table for each department


1566.6667

DEPTNO AVG(SAL) ------- --------10 2916.6667 20 2175 30 1566.6667

Copyright 2004, Oracle. All rights reserved.

Creating Groups of Data: GROUP BY Clause


Use the GROUP BY clause to divide rows in a table Use the GROUP BY clause to divide rows in a table into smaller groups. into smaller groups.
SELECT FROM [WHERE [GROUP BY [ORDER BY column, group_function table condition] group_by_expression] column];

Copyright 2004, Oracle. All rights reserved.

Using the GROUP BY Clause


All columns in the SELECT list that are not in group All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. functions must be in the GROUP BY clause.

SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno;

DEPTNO AVG(SAL) --------- --------10 2916.6667 20 2175 30 1566.6667


Copyright 2004, Oracle. All rights reserved.

Using the GROUP BY Clause


The GROUP BY column does not have to be in the The GROUP BY column does not have to be in the SELECT list. SELECT list.
SQL> SELECT AVG(sal) 2 FROM emp 3 GROUP BY deptno;

AVG(SAL) --------2916.6667 2175 1566.6667

Copyright 2004, Oracle. All rights reserved.

Using the GROUP BY Clause


Display the number of people in each department. Display the number of people in each department.

SQL> SELECT deptno, COUNT(*) AS "Dept Employees" 2 FROM emp 3 GROUP BY deptno;

DEPTNO Dept Employees --------- -------------10 3 20 5 30 6

Copyright 2004, Oracle. All rights reserved.

Using a Group Function in the ORDER BY Clause


SQL> 2 3 4 SELECT FROM GROUP BY ORDER BY deptno, AVG(sal) emp deptno AVG(sal);

DEPTNO AVG(SAL) ---------- -----------30 1566.6667 20 2175 10 2916.6667

Copyright 2004, Oracle. All rights reserved.

Illegal Queries Using Group Functions


Any column or expression in the SELECT list that is Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY not an aggregate function must be in the GROUP BY e se clause. clause. us lla u ca Yc BY PB SQL> SELECT deptno, COUNT(ename) UP SQL> SELECT deptno, COUNT(ename) OU RO 2 FROM emp; 2 FROM emp; GR eG h tth e n in SELECT deptno, COUNT(ename) g i SELECT deptno, COUNT(ename) g * siin sn * s iis ERROR at line 1: m ERROR at line 1: nm n ORA-00937: not a single-group group function ORA-00937: not a single-group group function um llu m Co Co
Copyright 2004, Oracle. All rights reserved.

Using Set Operators

Copyright 2004, Oracle. All rights reserved.

The Set Operators


A B

Intersect
A B A B

Union / Union All


A B

Minus
Copyright 2004, Oracle. All rights reserved.

Tables Used in This Lesson


EMP
EMPNO ENAME JOB MGR HIREDATE SAL EMPNO ENAME JOB MGR HIREDATE SAL DEPTNO DEPTNO --------- ---------- --------- --------- --------- ----------------- ---------- --------- --------- --------- --------7839 KING PRESIDENT 17-NOV-81 5000 7839 KING PRESIDENT 17-NOV-81 5000 10 10 7698 BLAKE MANAGER 7839 01-MAY-81 2850 7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 30 7782 CLARK MANAGER 7839 09-JUN-81 1500 7782 CLARK MANAGER 7839 09-JUN-81 1500 10 10 7566 JONES MANAGER 7839 02-APR-81 2975 7566 JONES MANAGER 7839 02-APR-81 2975 20 EMPID NAME 20 EMPID NAME 7654 MARTIN SALESMAN DEPTID 7698 28-SEP-81 1250 7654 MARTIN SALESMAN DEPTID 7698 28-SEP-81 1250 30 --------- -------------------30 --------- -------------------7499 ALLEN SALESMAN 7698 20-FEB-81 1600 7499 ALLEN SALESMAN 7698 20-FEB-81 1600 30 6087 SPENCER 30 6087 SPENCER 7844 TURNER SALESMAN 20 7698 08-SEP-81 1500 7844 TURNER SALESMAN 20 7698 08-SEP-81 1500 30 6185 VANDYKE 30 6185 VANDYKE EMP_HISTORY 10 7900 JAMES CLERK 7698 03-DEC-81 950 7900 JAMES CLERK 7698 03-DEC-81 950 10 30 6235 BALFORD 30 6235 BALFORD 7521 WARD SALESMAN 20 7698 22-FEB-81 1250 7521 WARD SALESMAN 20 7698 22-FEB-81 1250 30 7788 SCOTT 30 7788 SCOTT 7902 FORD ANALYST 20 7566 03-DEC-81 3000 7902 FORD ANALYST 20 7566 03-DEC-81 3000 20 7001 JEWELL 20 7001 JEWELL 7369 SMITH All rights reserved. CLERK 7902 17-DEC-80 800 30 7369 Oracle. CLERK 7902 17-DEC-80 800 30 Copyright 2004, SMITH 20 7499 ALLEN 20 7499 ALLEN COMM COMM --------- ---------------- --------

TITLE TITLE 1400 1400 ----------------300 300 OPERATOR OPERATOR 0 0 MANAGER MANAGER CLERK CLERK

DATE_OUT DATE_OUT --------- ---------------- -------27-NOV-81 27-NOV-81 17-JAN-81 17-JAN-81 22-FEB-80 22-FEB-80

500 500 ANALYST 05-MAY-81 ANALYST 05-MAY-81 ANALYST ANALYST 10-JUN-81 10-JUN-81

SALESMAN 01-AUG-80 SALESMAN 01-AUG-80

UNION A B

Copyright 2004, Oracle. All rights reserved.

Using the UNION Operator


Display the name, employee number, and job title of Display the name, employee number, and job title of all employees. Display each employee only once. all employees. Display each employee only once.
SQL> 2 3 4 5 SELECT FROM UNION SELECT FROM ename, empno, job emp name, empid, title emp_history; JOB --------CLERK SALESMAN CLERK

ENAME EMPNO ---------- --------ADAMS 7876 ALLEN 7499 BALFORD 6235 ... 20 rows selected.
Copyright 2004, Oracle. All rights reserved.

Using the UNION Operator


Display the name, job title, and salary of all Display the name, job title, and salary of all employees. employees.
SQL> 2 3 4 5 SELECT FROM UNION SELECT FROM ename, job, sal emp name, title, 0 emp_history;

ENAME JOB SAL ---------- --------- --------ADAMS CLERK 1100 ALLEN SALESMAN 0 ALLEN SALESMAN 1600 BALFORD CLERK 0 ... 23 rows selected.
Copyright 2004, Oracle. All rights reserved.

UNION ALL A B

Copyright 2004, Oracle. All rights reserved.

Using the UNION ALL Operator


Display the names, employee numbers, and job Display the names, employee numbers, and job titles of all employees. titles of all employees.
SQL> 2 3 4 5 SELECT ename, empno, job FROM emp UNION ALL SELECT name, empid, title FROM emp_history; JOB --------PRESIDENT MANAGER MANAGER MANAGER

ENAME EMPNO ---------- --------KING 7839 BLAKE 7698 CLARK 7782 CLARK 7782 ... 23 rows selected.
Copyright 2004, Oracle. All rights reserved.

INTERSECT A B

Copyright 2004, Oracle. All rights reserved.

Using the INTERSECT Operator


Display the distinct names, employee numbers, and Display the distinct names, employee numbers, and job titles of employees found in both the EMP and job titles of employees found in both the EMP and EMP_HISTORY tables. EMP_HISTORY tables.
SQL> 2 3 4 5 SELECT ename, empno, job FROM emp INTERSECT SELECT name, empid, title FROM emp_history;

ENAME EMPNO JOB ENAME EMPNO JOB ---------- --------- ------------------ --------- --------ALLEN 7499 SALESMAN ALLEN 7499 SALESMAN CLARK 7782 MANAGER CLARK 7782 MANAGER SCOTT 7788 ANALYST SCOTT 7788 ANALYST
Copyright 2004, Oracle. All rights reserved.

MINUS A B

Copyright 2004, Oracle. All rights reserved.

MINUS
Display the names, employee numbers, and Display the names, employee numbers, and job titles for all employees who have left the job titles for all employees who have left the company. company.
SQL> 2 3 4 5 SELECT FROM MINUS SELECT FROM name, empid, title emp_history ename, empno, job emp; TITLE TITLE ----------------CLERK CLERK PAY CLERK PAY CLERK

NAME EMPID NAME EMPID ---------- ------------------ --------BALFORD 6235 BALFORD 6235 BRIGGS 7225 BRIGGS 7225 ... ... 6 rows selected. 6 rows selected.
Copyright 2004, Oracle. All rights reserved.

SET Operator Rules


The expressions in the SELECT lists must match in The expressions in the SELECT lists must match in number and datatype. number and datatype. Duplicate rows are automatically eliminated except in Duplicate rows are automatically eliminated except in UNION ALL. UNION ALL. Column names from the first query appear in the result. Column names from the first query appear in the result. The output is sorted in ascending order by default The output is sorted in ascending order by default except in UNION ALL. except in UNION ALL. Parentheses can be used to alter the sequence of Parentheses can be used to alter the sequence of execution. execution.

Copyright 2004, Oracle. All rights reserved.

Matching the SELECT Statement


Display the department numbers, Display the department numbers, locations, and hiredates for all employees. locations, and hiredates for all employees.
SQL> 2 3 4 5 SELECT FROM UNION SELECT FROM deptno, null location, hiredate emp deptno, loc, TO_DATE(null) dept;

Copyright 2004, Oracle. All rights reserved.

Controlling the Order of Rows


Produce an English sentence using two Produce an English sentence using two UNION operators. UNION operators.
SQL> SQL> SQL> SQL> 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 COLUMN a_dummy NOPRINT COLUMN a_dummy NOPRINT SELECT 'sing' "My dream", 3 a_dummy SELECT 'sing' "My dream", 3 a_dummy FROM dual FROM dual UNION UNION SELECT 'I''d like to teach', 1 SELECT 'I''d like to teach', 1 FROM dual FROM dual UNION UNION SELECT 'the world to', 2 SELECT 'the world to', 2 FROM dual FROM dual ORDER BY 2; ORDER BY 2;

My dream My dream ------------------------------------------------I'd like to teach I'd like to teach the world to the world to sing sing
Copyright 2004, Oracle. All rights reserved.

Writing Subqueries

Copyright 2004, Oracle. All rights reserved.

Using a Subquery to Solve a Problem


Who has a salary greater than Joness? Who has a salary greater than Joness?
Main Query

Which employees have a salary greater than Joness salary?


Subquery

What is Joness salary?

Copyright 2004, Oracle. All rights reserved.

Subqueries
SELECT FROM WHERE select_list table expr operator (SELECT FROM

select_list table);

The subquery (inner query) executes once before the main The subquery (inner query) executes once before the main query. query. The result of the subquery is used by the main query (outer The result of the subquery is used by the main query (outer query). query).

Copyright 2004, Oracle. All rights reserved.

Using a Subquery
Who has a salary greater than Jones?
SQL> SELECT ename 2 FROM emp 2975 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE ename='JONES');

ENAME ---------KING FORD SCOTT

Copyright 2004, Oracle. All rights reserved.

Guidelines for Using Subqueries


Enclose subqueries in parentheses. Enclose subqueries in parentheses. Place subqueries on the right side of the comparison Place subqueries on the right side of the comparison operator. operator. Do not add an ORDER BY clause to a subquery. Do not add an ORDER BY clause to a subquery. Use single-row operators with single-row subqueries. Use single-row operators with single-row subqueries.

Copyright 2004, Oracle. All rights reserved.

Types of Subqueries

Single-row subquery Single-row subquery


Main query returns

Multiple-row subquery Multiple-row subquery

Subquery

CLERK

Main query Subquery returns

CLERK MANAGER

Copyright 2004, Oracle. All rights reserved.

Single-Row Subqueries

Return only one row Return only one row Use single-row comparison operators Use single-row comparison operators

Operator = > >= < <= <>


Copyright 2004, Oracle. All rights reserved.

Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to

Executing Single-Row Subqueries


Who works in the same department as King?
SQL> SELECT ename, deptno 2 FROM emp 10 3 WHERE deptno = 4 (SELECT deptno 5 FROM emp 6 WHERE ename='KING');

ENAME DEPTNO ---------- --------KING 10 CLARK 10 MILLER 10

Copyright 2004, Oracle. All rights reserved.

Executing Single-Row Subqueries


Who has the same manager as Blake?
SQL> SELECT ename, mgr 7839 2 FROM emp 3 WHERE mgr = 4 (SELECT mgr 5 FROM emp 6 WHERE ename='BLAKE');

ENAME MGR ---------- --------BLAKE 7839 CLARK 7839 JONES 7839

Copyright 2004, Oracle. All rights reserved.

Executing Single-Row Subqueries


Who has the same job as employee 7369 and earns a higher salary than employee 7876?
SQL> 2 3 4 5 6 7 8 9 10 SELECT FROM WHERE ename, job emp job = (SELECT FROM WHERE sal > (SELECT FROM WHERE CLERK job emp empno = 7369) 1100 sal emp empno = 7876);

AND

ENAME JOB ---------- --------MILLER CLERK

Copyright 2004, Oracle. All rights reserved.

Using Group Functions in a Subquery


Display all employees who earn the minimum salary.
SQL> SELECT 2 FROM 3 WHERE 4 5 ename, job, sal emp sal = (SELECT FROM 800 MIN(sal) emp);

ENAME JOB SAL ---------- --------- --------SMITH CLERK 800

Copyright 2004, Oracle. All rights reserved.

What Is Wrong with This Statement?


SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT 5 FROM 6 GROUP BY

ERROR: ORA-01427: single-row one row no rows selected

ow -r le g in S

ith rw to returns subquery ra pe o

ow MIN(sal) -r e emp ipl lt deptno); u m

ry ue bq su

more than

Copyright 2004, Oracle. All rights reserved.

Will This Statement Work?

SQL> SELECT ename, 2 FROM emp 3 WHERE job = 4 5 6

job (SELECT job es lu FROM emp va WHERE ename='SMYTHE'); o

no rows selected

ry ue bq Su

ns ur et r

Copyright 2004, Oracle. All rights reserved.

Multiple-Row Subqueries

Return more than one row Return more than one row Use the IN multiple-row comparison operator to Use the IN multiple-row comparison operator to compare an expression to any member in the list that a compare an expression to any member in the list that a subquery returns subquery returns

Copyright 2004, Oracle. All rights reserved.

Using Group Functions in a Multiple-Row Subquery


Display all employees who earn the same salary as the minimum salary for each department.
SQL> SELECT 2 FROM 3 WHERE 4 5 6 ename, sal, deptno emp 800, 950, 1300 sal IN (SELECT MIN(sal) FROM emp GROUP BY deptno);

ENAME SAL DEPTNO ---------- --------- --------SMITH 800 20 JAMES 950 30 MILLER 1300 10

Copyright 2004, Oracle. All rights reserved.

Using Group Functions in a Multiple-Row Subquery


Display the employees who were hired on the same date as the longest serving employee in any department.
SQL> 2 3 4 5 6 7 SELECT ename, sal, deptno, TO_CHAR(hiredate,'DD-MON-YYYY')HIREDATE FROM emp WHERE hiredate IN (SELECT MIN(hiredate) FROM emp GROUP BY deptno); ENAME SAL DEPTNO HIREDATE ---------- --------- --------- ----------SMITH 800 20 17-DEC-1980 ALLEN 1600 30 20-FEB-1981 CLARK 2450 10 09-JUN-1981
Copyright 2004, Oracle. All rights reserved.

Controlling Transactions

Copyright 2004, Oracle. All rights reserved.

Data Manipulation Language


A DML statement is executed when you: A DML statement is executed when you:
Add new rows to a table (INSERT) Add new rows to a table (INSERT) Modify existing rows in a table (UPDATE) Modify existing rows in a table (UPDATE) Remove existing rows from a table (DELETE) Remove existing rows from a table (DELETE)

A transaction consists of a collection of DML statements A transaction consists of a collection of DML statements that form a logical unit of work. that form a logical unit of work.

Copyright 2004, Oracle. All rights reserved.

Database Transactions
Database transactions can consist of: Database transactions can consist of:

DML statements that make up one consistent change to the DML statements that make up one consistent change to the data data
Example: UPDATE Example: UPDATE

One DDL statement One DDL statement


Example: CREATE Example: CREATE

One DCL statement One DCL statement


Example: GRANT and REVOKE Example: GRANT and REVOKE

Copyright 2004, Oracle. All rights reserved.

Database Transactions

Begin when the first executable SQL statement is Begin when the first executable SQL statement is executed executed End with one of the following events: End with one of the following events:
COMMIT or ROLLBACK COMMIT or ROLLBACK DDL or DCL statement executes (automatic commit) DDL or DCL statement executes (automatic commit) User exits User exits System crashes System crashes

Copyright 2004, Oracle. All rights reserved.

Advantages of COMMIT and ROLLBACK


COMMIT and ROLLBACK ensure data consistency. COMMIT and ROLLBACK ensure data consistency. Users can preview data changes before making Users can preview data changes before making changes permanent. changes permanent. Users can group logically related operations. Users can group logically related operations.

Copyright 2004, Oracle. All rights reserved.

Controlling Transactions
Transaction Transaction

INSERT
COMMIT

UPDATE

INSERT

DELETE

Savepoint A

Savepoint B

ROLLBACK to Savepoint B

ROLLBACK to Savepoint A

ROLLBACK
Copyright 2004, Oracle. All rights reserved.

Implicit Transaction Processing


An automatic commit occurs under the following An automatic commit occurs under the following circumstances: circumstances:
A DDL statement is issued, such as CREATE A DDL statement is issued, such as CREATE A DCL statement is issued, such as GRANT A DCL statement is issued, such as GRANT A normal exit from SQL*Plus occurs without an explicitly A normal exit from SQL*Plus occurs without an explicitly issued COMMIT or ROLLBACK statement issued COMMIT or ROLLBACK statement

An automatic rollback occurs under an abnormal An automatic rollback occurs under an abnormal termination of SQL*Plus or a system failure. termination of SQL*Plus or a system failure.

Copyright 2004, Oracle. All rights reserved.

State of the Data Before COMMIT or ROLLBACK


The previous state of the data can be recovered. The previous state of the data can be recovered. The current user can review the results of the DML operations The current user can review the results of the DML operations by using the SELECT statement. by using the SELECT statement. Other users cannot view the results of the DML statements by Other users cannot view the results of the DML statements by the current user. the current user. The affected rows are locked; other users cannot change the The affected rows are locked; other users cannot change the data within the affected rows. data within the affected rows.

Copyright 2004, Oracle. All rights reserved.

Committing Data
Change the department number of an employee Change the department number of an employee (Clark) identified by a employee number. (Clark) identified by a employee number.

Make the changes. Make the changes.

SQL> UPDATE emp SQL> UPDATE emp 2 SET deptno = 10 2 SET deptno = 10 3 WHERE empno = 7782; 3 WHERE empno = 7782; 1 row updated. 1 row updated.

Commit the changes. Commit the changes.


SQL> COMMIT; Commit complete.

Copyright 2004, Oracle. All rights reserved.

State of the Data After COMMIT


Data changes are made permanent in the Data changes are made permanent in the database. database. The previous state of the data is The previous state of the data is permanently lost. permanently lost. All users can view the results. All users can view the results. Locks on the affected rows are released; Locks on the affected rows are released; those rows are available for other users to those rows are available for other users to manipulate. manipulate. All savepoints are erased. All savepoints are erased.
Copyright 2004, Oracle. All rights reserved.

State of the Data After ROLLBACK


Discard all pending changes by using the Discard all pending changes by using the ROLLBACK statement. Following a ROLLBACK: ROLLBACK statement. Following a ROLLBACK:

Data changes are undone. Data changes are undone. The previous state of the data is restored. The previous state of the data is restored. Locks on the affected rows are released. Locks on the affected rows are released.

SQL> DELETE FROM employee; 14 rows deleted. SQL> ROLLBACK; Rollback complete.
Copyright 2004, Oracle. All rights reserved.

Rolling Back Changes to a Marker


Create a marker within a current transaction by using Create a marker within a current transaction by using the SAVEPOINT statement. the SAVEPOINT statement. Roll back to that marker by using the ROLLBACK TO Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. SAVEPOINT statement.

SQL> UPDATE... SQL> SAVEPOINT update_done; Savepoint created. SQL> INSERT... SQL> ROLLBACK TO update_done; Rollback complete.

Copyright 2004, Oracle. All rights reserved.

Statement-Level Rollback

If a single DML statement fails during execution, only If a single DML statement fails during execution, only that statement is rolled back. that statement is rolled back. Oracle implements an implicit savepoint. Oracle implements an implicit savepoint. All other changes are retained. All other changes are retained. The user should terminate transactions explicitly by The user should terminate transactions explicitly by executing a COMMIT or ROLLBACK statement. executing a COMMIT or ROLLBACK statement.

Copyright 2004, Oracle. All rights reserved.

Read Consistency

Read consistency guarantees a consistent view of the Read consistency guarantees a consistent view of the data at all times. data at all times. Changes made by one user do not conflict with Changes made by one user do not conflict with changes made by another user. changes made by another user. Read consistency ensures that on the same data: Read consistency ensures that on the same data:
Readers do not wait for writers or other readers Readers do not wait for writers or other readers Writers do not wait for readers Writers do not wait for readers

Copyright 2004, Oracle. All rights reserved.

Implementation of Read Consistency

UPDATE emp SET sal = 2000 WHERE ename = 'SCOTT';

Data blocks Rollback segments


Changed and unchanged data Before change old data

User A
SELECT * FROM emp;

Read consistent image

User B
Copyright 2004, Oracle. All rights reserved.

Locking
The Oracle Server locks: The Oracle Server locks:

Prevent destructive interaction between concurrent Prevent destructive interaction between concurrent transactions transactions Require no user action Require no user action Automatically use the lowest level of restrictiveness Automatically use the lowest level of restrictiveness Are held for the duration of the transaction Are held for the duration of the transaction Have two basic modes: Have two basic modes:
Exclusive Exclusive Share Share

Copyright 2004, Oracle. All rights reserved.

Locking Modes
Lock Mode Exclusive lock Description Prevents a resource from being shared. The first transaction to lock a resource exclusively is the only transaction that can alter the resource until the exclusive lock is released. Share Allows the resource to be shared. Multiple users reading data can share the data, holding share locks to prevent concurrent access by a writer (who needs an exclusive lock). Several transactions can acquire share locks on the same resource.
Copyright 2004, Oracle. All rights reserved.

Implicit Locking
User Action SELECT ... FROM table ... INSERT INTO table ... UPDATE table ... DELETE FROM table ... DDL Operation Row-Level Lock Table-Level Lock None X X X None None RX RX RX X

Copyright 2004, Oracle. All rights reserved.

Explicit Locking
User Action SELECT FOR UPDATE LOCK TABLE IN option Row-Level lock X None Table-Level lock RS [NOWAIT] Depends on the MODE restrictiveness used

Override the default lock mechanism: Override the default lock mechanism:

For a consistent view of data when reading across For a consistent view of data when reading across multiple tables multiple tables When a transaction may change data based on other When a transaction may change data based on other data that must not change until the whole transaction is data that must not change until the whole transaction is complete complete

Copyright 2004, Oracle. All rights reserved.

Overview of PL/SQL

Copyright 2004, Oracle. All rights reserved.

About PL/SQL

PL/SQL is an extension to SQL with design features of PL/SQL is an extension to SQL with design features of programming languages. programming languages. Data manipulation and query statements of SQL are Data manipulation and query statements of SQL are included within procedural units of code. included within procedural units of code.

Copyright 2004, Oracle. All rights reserved.

PL/SQL Environment
PL/SQL engine PL/SQL block PL/SQL block PL/SQL SQL Procedural Statement Executor

SQL Statement Executor Oracle Server

Copyright 2004, Oracle. All rights reserved.

Benefits of PL/SQL
Integration Integration

Application

Shared library

Oracle Server

Copyright 2004, Oracle. All rights reserved.

Benefits of PL/SQL
Improve Performance Improve Performance
SQL

Application Application

SQL SQL SQL

Other DBMSs Other DBMSs

Application Application

SQL IF...THEN SQL ELSE SQL END IF; SQL

Oracle with Oracle with PL/SQL PL/SQL

Copyright 2004, Oracle. All rights reserved.

Benefits of PL/SQL
Modularize program development Modularize program development
DECLARE

BEGIN

EXCEPTION

END;

Copyright 2004, Oracle. All rights reserved.

Benefits of PL/SQL

It is portable. It is portable. You can declare identifiers. You can declare identifiers.

Copyright 2004, Oracle. All rights reserved.

Benefits of PL/SQL

You can program with procedural language control You can program with procedural language control structures. structures. It can handle errors. It can handle errors.

Copyright 2004, Oracle. All rights reserved.

Declaring Variables

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Structure



DECLARE Optional DECLARE Optional BEGIN Mandatory BEGIN Mandatory

Variables, cursors, user-defined exceptions Variables, cursors, user-defined exceptions SQL statements SQL statements PL/SQL statements PL/SQL statements Actions to perform when Actions to perform when
errors occur errors occur

EXCEPTION Optional EXCEPTION Optional END; Mandatory END; Mandatory

DECLARE BEGIN EXCEPTION END;

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Structure


DECLARE DECLARE v_variable VARCHAR2(5); v_variable VARCHAR2(5); BEGIN BEGIN SELECT column_name SELECT column_name INTO v_variable INTO v_variable FROM table_name; FROM table_name; EXCEPTION EXCEPTION WHEN exception_name THEN WHEN exception_name THEN ... ... END; END;

DECLARE BEGIN EXCEPTION END;

Copyright 2004, Oracle. All rights reserved.

Block Types
Anonymous
[DECLARE] [DECLARE]

Procedure
PROCEDURE name PROCEDURE name IS IS BEGIN BEGIN --statements --statements [EXCEPTION] [EXCEPTION] END; END;

Function
FUNCTION name FUNCTION name RETURN datatype RETURN datatype IS IS BEGIN BEGIN --statements --statements RETURN value; RETURN value; [EXCEPTION] [EXCEPTION] END; END;

BEGIN BEGIN --statements --statements [EXCEPTION] [EXCEPTION] END; END;

Copyright 2004, Oracle. All rights reserved.

Program Constructs
Anonymous Anonymous block block Stored Stored procedure/ procedure/ function function Application Application procedure/ procedure/ function function

DECLARE BEGIN EXCEPTION

Application Application trigger trigger

Database Database trigger trigger

END;

Packaged Packaged procedure/ procedure/ function function

Copyright 2004, Oracle. All rights reserved.

Use of Variables
Use variables for: Use variables for:

Temporary storage of data Temporary storage of data Manipulation of stored values Manipulation of stored values Reusability Reusability Ease of maintenance Ease of maintenance

Copyright 2004, Oracle. All rights reserved.

Handling Variables in PL/SQL


Declare and initialize variables in the declaration Declare and initialize variables in the declaration section. section. Assign new values to variables in the executable Assign new values to variables in the executable section. section. Pass values into PL/SQL blocks through parameters. Pass values into PL/SQL blocks through parameters. View results through output variables. View results through output variables.

Copyright 2004, Oracle. All rights reserved.

Types of Variables

PL/SQL variables: PL/SQL variables:


Scalar Scalar Composite Composite Reference Reference LOB (large objects) LOB (large objects)

Non-PL/SQL variables: Bind and host variables Non-PL/SQL variables: Bind and host variables

Copyright 2004, Oracle. All rights reserved.

Types of Variables

PL/SQL variables: PL/SQL variables:


Scalar Scalar Composite Composite Reference Reference LOB (large objects) LOB (large objects)

Non-PL/SQL variables: Bind and host variables Non-PL/SQL variables: Bind and host variables

Copyright 2004, Oracle. All rights reserved.

Types of Variables

TRUE

25-OCT-99
Four score and seven years ago our fathers brought forth upon this continent, a new nation, conceived in LIBERTY, and dedicated

256120.08

to the proposition that all men are created equal.

Atlanta
Copyright 2004, Oracle. All rights reserved.

Declaring PL/SQL Variables


Syntax Syntax
identifier [CONSTANT] datatype [NOT NULL] identifier [CONSTANT] datatype [NOT NULL] [:= | DEFAULT expr]; [:= | DEFAULT expr];

Examples Examples
Declare Declare v_hiredate v_hiredate v_deptno v_deptno v_location v_location c_comm c_comm DATE; DATE; NUMBER(2) NOT NULL := 10; NUMBER(2) NOT NULL := 10; VARCHAR2(13) := 'Atlanta'; VARCHAR2(13) := 'Atlanta'; CONSTANT NUMBER := 1400; CONSTANT NUMBER := 1400;

Copyright 2004, Oracle. All rights reserved.

Declaring PL/SQL Variables


Guidelines Guidelines

Follow naming conventions. Follow naming conventions. Initialize variables designated as NOT NULL. Initialize variables designated as NOT NULL. Initialize identifiers by using the assignment operator Initialize identifiers by using the assignment operator (:=) or the DEFAULT reserved word. (:=) or the DEFAULT reserved word. Declare at most one identifier per line. Declare at most one identifier per line.

Copyright 2004, Oracle. All rights reserved.

Naming Rules

Two variables can have the same name, provided they Two variables can have the same name, provided they are in different blocks. are in different blocks. The variable name (identifier) should not be the same The variable name (identifier) should not be the same as the name of table columns used in the block. as the name of table columns used in the block.

ffor or n ttiion n o ven nve s:: co n er g c o tiiffiier s o ng n DECLARE DECLARE miin den t mpn o na m L iide _e mpn empno NUMBER(4); a na Q L empno NUMBER(4); ptt a //S Q lle,, v _e BEGIN BEGIN do p PL S mp e v A do PL a mp SELECT empno A SELECT empno ex a r ex INTO empno INTO empno ffo r o FROM emp
FROM WHERE WHERE END; END; emp ename = 'SMITH'; ename = 'SMITH';

Copyright 2004, Oracle. All rights reserved.

Assigning Values to Variables


Syntax Syntax
identifier := expr; identifier := expr;

Example Example Set a predefined hiredate for new Set a predefined hiredate for new employees. employees.
v_hiredate := '31-DEC-98'; v_hiredate := '31-DEC-98';

Set the employee name to Maduro. Set the employee name to Maduro.
v_ename := 'Maduro'; v_ename := 'Maduro';

Copyright 2004, Oracle. All rights reserved.

Variable Initialization and Keywords


Using: Using:

Assignment operator (:=) Assignment operator (:=) DEFAULT keyword DEFAULT keyword NOT NULL constraint NOT NULL constraint

Copyright 2004, Oracle. All rights reserved.

Scalar Datatypes
Hold a single value Hold a single value Have no internal components Have no internal components

25-OCT-99 and seven years Four score


ago our fathers brought new nation, conceived in

forth upon this continent, a

TRUE

256120.08
Copyright 2004, Oracle. All rights reserved.

LIBERTY, and dedicated to the proposition that all men are created equal.

Atlanta

Base Scalar Datatypes


VARCHAR2 (maximum_length) VARCHAR2 (maximum_length) NUMBER [(precision, scale)] NUMBER [(precision, scale)] DATE DATE CHAR [(maximum_length)] CHAR [(maximum_length)] LONG LONG LONG RAW LONG RAW BOOLEAN BOOLEAN BINARY_INTEGER BINARY_INTEGER PLS_INTEGER PLS_INTEGER

Copyright 2004, Oracle. All rights reserved.

Base Scalar Datatypes


DATE DATE TIMESTAMP TIMESTAMP TIMESTAMP WITH TIMEZHONE TIMESTAMP WITH TIMEZHONE TIMESTAMP WITH LOCAL TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE INTERVAL YEAR TO MONTH INTERVAL YEAR TO MONTH INVERTAL YEAR TO SECOND INVERTAL YEAR TO SECOND

Copyright 2004, Oracle. All rights reserved.

Scalar Variable Declarations


Example Example
v_job v_job v_count v_count v_total_sal v_total_sal v_orderdate v_orderdate c_tax_rate c_tax_rate v_valid v_valid VARCHAR2(9); VARCHAR2(9); BINARY_INTEGER := 0; BINARY_INTEGER := 0; NUMBER(9,2) := 0; NUMBER(9,2) := 0; DATE := SYSDATE + 7; DATE := SYSDATE + 7; CONSTANT NUMBER(3,2) := 8.25; CONSTANT NUMBER(3,2) := 8.25; BOOLEAN NOT NULL := TRUE; BOOLEAN NOT NULL := TRUE;

Copyright 2004, Oracle. All rights reserved.

The %TYPE Attribute


Declare a variable according to: Declare a variable according to:


A database column definition A database column definition Another previously declared variable Another previously declared variable

Prefix %TYPE with: Prefix %TYPE with:


The database table and column The database table and column The previously declared variable name The previously declared variable name

Copyright 2004, Oracle. All rights reserved.

Declaring Variables with the %TYPE Attribute


Example Example

... ... v_ename v_ename v_balance v_balance v_min_balance v_min_balance ... ...

emp.ename%TYPE; emp.ename%TYPE; NUMBER(7,2); NUMBER(7,2); v_balance%TYPE := 10; v_balance%TYPE := 10;

Copyright 2004, Oracle. All rights reserved.

Declaring Boolean Variables


Only the values TRUE, FALSE, and NULL can be Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable. assigned to a Boolean variable. The variables are connected by the logical operators The variables are connected by the logical operators AND, OR, and NOT. AND, OR, and NOT. The variables always yield TRUE, FALSE, or NULL. The variables always yield TRUE, FALSE, or NULL. Arithmetic, character, and date expressions can be Arithmetic, character, and date expressions can be used to return a Boolean value. used to return a Boolean value.

Copyright 2004, Oracle. All rights reserved.

Composite Datatypes

PL/SQL TABLES PL/SQL TABLES PL/SQL RECORDS PL/SQL RECORDS

Copyright 2004, Oracle. All rights reserved.

LOB Datatype Variables


Recipe (CLOB) Photo (BLOB) Movie (BFILE) NCLOB

Copyright 2004, Oracle. All rights reserved.

Bind Variables

O/S Bind Variable Server

Copyright 2004, Oracle. All rights reserved.

Referencing Non-PL/SQL Variables

Store the annual salary into a SQL*Plus host Store the annual salary into a SQL*Plus host variable. variable.
:g_monthly_sal := v_sal / 12; :g_monthly_sal := v_sal / 12;

Reference non-PL/SQL variables as host variables. Reference non-PL/SQL variables as host variables. Prefix the references with a colon (:). Prefix the references with a colon (:).

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

DBMS_OUTPUT.PUT_LINE

An Oracle-supplied packaged procedure An Oracle-supplied packaged procedure An alternative for displaying data from a PL/SQL block An alternative for displaying data from a PL/SQL block Must be enabled in SQL*Plus with Must be enabled in SQL*Plus with SET SERVEROUTPUT ON SET SERVEROUTPUT ON

Copyright 2004, Oracle. All rights reserved.

Writing Executable Statements

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Syntax and Guidelines


Statements can continue over several lines. Statements can continue over several lines. Lexical units can be separated by: Lexical units can be separated by:
Spaces Spaces Delimiters Delimiters Identifiers Identifiers Literals Literals Comments Comments

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Syntax and Guidelines


Identifiers Identifiers

Can contain up to 30 characters Can contain up to 30 characters Cannot contain reserved words unless enclosed in Cannot contain reserved words unless enclosed in double quotation marks double quotation marks Must begin with an alphabetic character Must begin with an alphabetic character Should not have the same name as a database table Should not have the same name as a database table column name column name

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Syntax and Guidelines


Literals Literals

Character and date literals must be enclosed in single Character and date literals must be enclosed in single quotation marks. quotation marks.

v_ename := 'Henderson'; values or scientific notation. Numbers can be simple Numbers can be simple v_ename := 'Henderson'; values or scientific notation.

Copyright 2004, Oracle. All rights reserved.

Commenting Code

Prefix single-line comments with two dashes (--). Prefix single-line comments with two dashes (--). Place multi-line comments between the symbols /* and Place multi-line comments between the symbols /* and */. */.

Example Example

... ... v_sal NUMBER (9,2); v_sal NUMBER (9,2); BEGIN BEGIN /* Compute the annual salary based on the /* Compute the annual salary based on the monthly salary input from the user */ monthly salary input from the user */ v_sal := &p_monthly_sal * 12; v_sal := &p_monthly_sal * 12; END; -- This is the end of the transaction END; -- This is the end of the transaction

Copyright 2004, Oracle. All rights reserved.

SQL Functions in PL/SQL


Available: Available:
Single-row number Single-row number Single-row character Single-row character Datatype conversion Datatype conversion Date Date

Not available: Not available:


DECODE DECODE Group functions Group functions

Same as in SQL

Copyright 2004, Oracle. All rights reserved.

PL/SQL Functions
Example Example

Build the mailing list for a company. Build the mailing list for a company.

v_mailing_address := v_name||CHR(10)|| v_mailing_address := v_name||CHR(10)|| v_address||CHR(10)||v_state|| v_address||CHR(10)||v_state|| CHR(10)||v_zip; CHR(10)||v_zip;


Convert the employee name to lowercase. Convert the employee name to lowercase.

v_ename v_ename

:= LOWER(v_ename); := LOWER(v_ename);

Copyright 2004, Oracle. All rights reserved.

Datatype Conversion

Convert data to comparable datatypes. Convert data to comparable datatypes. Mixed datatypes can result in an error and affect Mixed datatypes can result in an error and affect performance. performance. Conversion functions: Conversion functions:
TO_CHAR TO_CHAR TO_DATE TO_DATE TO_NUMBER TO_NUMBER DECLARE DECLARE v_date v_date BEGIN BEGIN SELECT SELECT

VARCHAR2(15); VARCHAR2(15);

TO_CHAR(hiredate, TO_CHAR(hiredate, 'MON. DD, YYYY') 'MON. DD, YYYY') INTO v_date INTO v_date FROM emp FROM emp WHERE empno = 7839; WHERE empno = 7839; END; END;
Copyright 2004, Oracle. All rights reserved.

Datatype Conversion
This statement produces a compilation This statement produces a compilation error if the variable v_date is declared as error if the variable v_date is declared as datatype DATE. datatype DATE.
v_date := 'January 13, 1998'; v_date := 'January 13, 1998';

To correct the error, use the TO_DATE To correct the error, use the TO_DATE conversion function. conversion function.
v_date := TO_DATE ('January 13, 1998', v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY'); 'Month DD, YYYY');

Copyright 2004, Oracle. All rights reserved.

Nested Blocks and Variable Scope


Statements can be nested wherever an executable Statements can be nested wherever an executable statement is allowed. statement is allowed. A nested block becomes a statement. A nested block becomes a statement. An exception section can contain nested blocks. An exception section can contain nested blocks. The scope of an object is the region of the program that The scope of an object is the region of the program that can refer to the object. can refer to the object.

Copyright 2004, Oracle. All rights reserved.

Nested Blocks and Variable Scope


An identifier is visible in the regions in which you An identifier is visible in the regions in which you can reference the unqualified identifier: can reference the unqualified identifier:

A block can look up to the enclosing block. A block can look up to the enclosing block. A block cannot look down to enclosed blocks. A block cannot look down to enclosed blocks.

Copyright 2004, Oracle. All rights reserved.

Nested Blocks and Variable Scope


Example Example
... ... x BINARY_INTEGER; x BINARY_INTEGER; BEGIN BEGIN ... ... DECLARE DECLARE y NUMBER; y NUMBER; BEGIN BEGIN ... ... END; END; ... ... END; END;

Scope of x

Scope of y

Copyright 2004, Oracle. All rights reserved.

Operators in PL/SQL

Logical Logical Arithmetic Arithmetic Concatenation Concatenation Parentheses to control order of Parentheses to control order of operations operations Exponential operator (**) Exponential operator (**)

Same as in SQL

Copyright 2004, Oracle. All rights reserved.

Operators in PL/SQL
Example Example

Increment the index for a loop. Increment the index for a loop.
:= v_count + 1; := v_count + 1;

v_count v_count

Set the value of a Boolean flag. Set the value of a Boolean flag.

v_equal := (v_n1 = v_n2); v_equal := (v_n1 = v_n2); Validate an employee number if it contains a value. Validate an employee number if it contains a value.

v_valid v_valid

:= (v_empno IS NOT NULL); := (v_empno IS NOT NULL);

Copyright 2004, Oracle. All rights reserved.

Using Bind Variables


To reference a bind variable in PL/SQL, you must To reference a bind variable in PL/SQL, you must prefix its name with a colon (:). prefix its name with a colon (:). Example Example
VARIABLE g_salary NUMBER VARIABLE g_salary NUMBER DECLARE DECLARE v_sal emp.sal%TYPE; v_sal emp.sal%TYPE; BEGIN BEGIN SELECT sal SELECT sal INTO v_sal INTO v_sal FROM emp FROM emp WHERE empno = 7369; WHERE empno = 7369; :g_salary := v_sal; :g_salary := v_sal; END; END; / /
Copyright 2004, Oracle. All rights reserved.

Programming Guidelines
Make code maintenance easier by: Make code maintenance easier by:

Documenting code with comments Documenting code with comments Developing a case convention for the code Developing a case convention for the code Developing naming conventions for identifiers and Developing naming conventions for identifiers and other objects other objects Enhancing readability by indenting Enhancing readability by indenting

Copyright 2004, Oracle. All rights reserved.

Code Naming Conventions


Avoid ambiguity: Avoid ambiguity:

The names of local variables and formal parameters The names of local variables and formal parameters take precedence over the names of database tables. take precedence over the names of database tables. The names of columns take precedence over the The names of columns take precedence over the names of local variables. names of local variables.

Copyright 2004, Oracle. All rights reserved.

Indenting Code
For clarity, indent each level of code. For clarity, indent each level of code. Example Example
BEGIN BEGIN IF x=0 THEN IF x=0 THEN y:=1; y:=1; END IF; END IF; END; END; DECLARE DECLARE v_deptno NUMBER(2); v_deptno NUMBER(2); v_location VARCHAR2(13); v_location VARCHAR2(13); BEGIN BEGIN SELECT deptno, SELECT deptno, loc loc INTO v_deptno, INTO v_deptno, v_location v_location FROM dept FROM dept WHERE dname = 'SALES'; WHERE dname = 'SALES'; ... ... END; END;

Copyright 2004, Oracle. All rights reserved.

Determining Variable Scope


Class Exercise Class Exercise
... ... DECLARE DECLARE V_SAL V_SAL V_COMM V_COMM V_MESSAGE V_MESSAGE BEGIN ... BEGIN ... NUMBER(7,2) := 60000; NUMBER(7,2) := 60000; NUMBER(7,2) := V_SAL * .20; NUMBER(7,2) := V_SAL * .20; VARCHAR2(255) := ' eligible for commission'; VARCHAR2(255) := ' eligible for commission';

DECLARE DECLARE V_SAL NUMBER(7,2) := 50000; V_SAL NUMBER(7,2) := 50000; V_COMM NUMBER(7,2) := 0; V_COMM NUMBER(7,2) := 0; V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM; V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM; BEGIN ... BEGIN ... V_MESSAGE := 'CLERK not'||V_MESSAGE; V_MESSAGE := 'CLERK not'||V_MESSAGE; END; END; V_MESSAGE := 'SALESMAN'||V_MESSAGE; V_MESSAGE := 'SALESMAN'||V_MESSAGE; END; END;
Copyright 2004, Oracle. All rights reserved.

Writing Control Structures

Copyright 2004, Oracle. All rights reserved.

Controlling PL/SQL Flow of Execution


You can change the logical flow of statements You can change the logical flow of statements using conditional IF statements and loop control using conditional IF statements and loop control structures. structures. Conditional IF statements: Conditional IF statements:

IF-THEN-END IF IF-THEN-END IF IF-THEN-ELSE-END IF IF-THEN-ELSE-END IF IF-THEN-ELSIF-END IF IF-THEN-ELSIF-END IF

Copyright 2004, Oracle. All rights reserved.

IF Statements
Syntax Syntax
IF condition THEN IF condition THEN statements; statements; [ELSIF condition THEN [ELSIF condition THEN statements;] statements;] [ELSE [ELSE statements;] statements;] END IF; END IF;

Simple IF statement: Simple IF statement: Set the manager ID to 22 if the employee Set the manager ID to 22 if the employee name is Osborne. name is Osborne.
IF v_ename IF v_ename v_mgr := v_mgr := END IF; END IF; = 'OSBORNE' THEN = 'OSBORNE' THEN 22; 22;

Copyright 2004, Oracle. All rights reserved.

Simple IF Statements
Set the job title to Salesman, the department number to 35, Set the job title to Salesman, the department number to 35, and the commission to 20% of the current salary if the last and the commission to 20% of the current salary if the last name is Miller. name is Miller. Example Example

. . . . . . IF v_ename = 'MILLER' THEN IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_job := 'SALESMAN'; v_deptno := 35; v_deptno := 35; v_new_comm := sal * 0.20; v_new_comm := sal * 0.20; END IF; END IF; . . . . . .

Copyright 2004, Oracle. All rights reserved.

IF-THEN-ELSE Statement Execution Flow


TRUE IF condition FALSE

THEN actions THEN actions (including further IFs) (including further IFs)

ELSE actions ELSE actions (including further IFs) (including further IFs)

Copyright 2004, Oracle. All rights reserved.

IF-THEN-ELSE Statements
Set a flag for orders where there are fewer than Set a flag for orders where there are fewer than five days between order date and ship date. five days between order date and ship date. Example Example

... ... IF v_shipdate IF v_shipdate v_ship_flag v_ship_flag ELSE ELSE v_ship_flag v_ship_flag END IF; END IF; ... ...

- v_orderdate < 5 THEN - v_orderdate < 5 THEN := 'Acceptable'; := 'Acceptable'; := 'Unacceptable'; := 'Unacceptable';

Copyright 2004, Oracle. All rights reserved.

IF-THEN-ELSIF Statement Execution Flow


IF condition IF condition TRUE FALSE ELSIF ELSIF condition condition TRUE FALSE ELSE ELSE actions actions

THEN actions THEN actions

THEN actions THEN actions

Copyright 2004, Oracle. All rights reserved.

IF-THEN-ELSIF Statements
For a given value, calculate a percentage of that For a given value, calculate a percentage of that value based on a condition. value based on a condition. Example Example
. . . . . . IF v_start > 100 THEN IF v_start > 100 THEN v_start := 2 * v_start; v_start := 2 * v_start; ELSIF v_start >= 50 THEN ELSIF v_start >= 50 THEN v_start := .5 * v_start; v_start := .5 * v_start; ELSE ELSE v_start := .1 * v_start; v_start := .1 * v_start; END IF; END IF; . . . . . .

Copyright 2004, Oracle. All rights reserved.

Building Logical Conditions


You can handle null values with the IS NULL operator. You can handle null values with the IS NULL operator. Any arithmetic expression containing a null value Any arithmetic expression containing a null value evaluates to NULL. evaluates to NULL. Concatenated expressions with null values treat null Concatenated expressions with null values treat null values as an empty string. values as an empty string.

Copyright 2004, Oracle. All rights reserved.

Logic Tables
Build a simple Boolean condition with a Build a simple Boolean condition with a comparison operator. comparison operator.
AND TRUE FALSE NULL OR TRUE FALSE NULL NOT

TRUE

TRUE

FALSE

NULL

TRUE

TRUE

TRUE

TRUE

TRUE

FALSE

FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL

FALSE

TRUE

NULL

NULL

FALSE

NULL

NULL

TRUE

NULL

NULL

NULL

NULL

Copyright 2004, Oracle. All rights reserved.

Boolean Conditions
What is the value of V_FLAG in each case? What is the value of V_FLAG in each case?
v_flag := v_reorder_flag AND v_available_flag; v_flag := v_reorder_flag AND v_available_flag;

V_REORDER_FLAG TRUE TRUE NULL NULL

V_AVAILABLE_FLAG TRUE FALSE TRUE FALSE

V_FLAG TRUE FALSE NULL FALSE

Copyright 2004, Oracle. All rights reserved.

Iterative Control: LOOP Statements

Loops repeat a statement or sequence of statements Loops repeat a statement or sequence of statements multiple times. multiple times. There are three loop types: There are three loop types:
Basic loop Basic loop FOR loop FOR loop WHILE loop WHILE loop

Copyright 2004, Oracle. All rights reserved.

Basic Loop
Syntax Syntax
LOOP LOOP statement1; statement1; . . . . . . EXIT [WHEN condition]; EXIT [WHEN condition]; END LOOP; END LOOP; -- delimiter -- statements -- EXIT statement -- delimiter

where: where:

condition condition

is a Boolean variable or is a Boolean variable or expression (TRUE, FALSE, expression (TRUE, FALSE, or NULL); or NULL);

Copyright 2004, Oracle. All rights reserved.

Basic Loop
Example Example
DECLARE DECLARE v_ordid item.ordid%TYPE := 601; v_ordid item.ordid%TYPE := 601; v_counter NUMBER(2) := 1; v_counter NUMBER(2) := 1; BEGIN BEGIN LOOP LOOP INSERT INTO item(ordid, itemid) INSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter); VALUES(v_ordid, v_counter); v_counter := v_counter + 1; v_counter := v_counter + 1; EXIT WHEN v_counter > 10; EXIT WHEN v_counter > 10; END LOOP; END LOOP; END; END;

Copyright 2004, Oracle. All rights reserved.

FOR Loop
FOR counter in [REVERSE] FOR counter in [REVERSE] lower_bound..upper_bound LOOP lower_bound..upper_bound LOOP Syntax Syntax statement1; statement1; statement2; statement2; . . . . . . END LOOP; END LOOP;

Use a FOR loop to shortcut the test for the number of Use a FOR loop to shortcut the test for the number of iterations. iterations. Do not declare the index; it is declared implicitly. Do not declare the index; it is declared implicitly.

Copyright 2004, Oracle. All rights reserved.

FOR Loop
Guidelines Guidelines

Reference the counter within the loop only; it is undefined Reference the counter within the loop only; it is undefined outside the loop. outside the loop. Use an expression to reference the existing value of a Use an expression to reference the existing value of a counter. counter. Do not reference the counter as the target of an Do not reference the counter as the target of an assignment. assignment.

Copyright 2004, Oracle. All rights reserved.

FOR Loop
Insert the first 10 new line items for order number Insert the first 10 new line items for order number 601. 601. Example Example
DECLARE DECLARE v_ordid item.ordid%TYPE := 601; v_ordid item.ordid%TYPE := 601; BEGIN BEGIN FOR i IN 1..10 LOOP FOR i IN 1..10 LOOP INSERT INTO item(ordid, itemid) INSERT INTO item(ordid, itemid) VALUES(v_ordid, i); VALUES(v_ordid, i); END LOOP; END LOOP; END; END;

Copyright 2004, Oracle. All rights reserved.

WHILE Loop
Syntax Syntax
WHILE condition LOOP WHILE condition LOOP statement1; statement1; statement2; statement2; . . . . . . END LOOP; END LOOP; Condition is evaluated at the beginning of each iteration.

Use the WHILE loop to repeat statements while a Use the WHILE loop to repeat statements while a condition is TRUE. condition is TRUE.

Copyright 2004, Oracle. All rights reserved.

WHILE Loop
Example Example
ACCEPT p_new_order PROMPT 'Enter the order number: ACCEPT p_new_order PROMPT 'Enter the order number: ACCEPT p_items ACCEPT p_items PROMPT 'Enter the number of items in this order: PROMPT 'Enter the number of items in this order: DECLARE DECLARE v_count NUMBER(2) := 1; v_count NUMBER(2) := 1; BEGIN BEGIN WHILE v_count <= &p_items LOOP WHILE v_count <= &p_items LOOP INSERT INTO item (ordid, itemid) INSERT INTO item (ordid, itemid) VALUES (&p_new_order, v_count); VALUES (&p_new_order, v_count); v_count := v_count + 1; v_count := v_count + 1; END LOOP; END LOOP; COMMIT; COMMIT; END; END; / / ' ' ' '

Copyright 2004, Oracle. All rights reserved.

Nested Loops and Labels


Nest loops to multiple levels. Nest loops to multiple levels. Use labels to distinguish between blocks and loops. Use labels to distinguish between blocks and loops. Exit the outer loop with the EXIT statement referencing Exit the outer loop with the EXIT statement referencing the label. the label.

Copyright 2004, Oracle. All rights reserved.

Nested Loops and Labels


... ... BEGIN BEGIN <<Outer_loop>> <<Outer_loop>> LOOP LOOP v_counter := v_counter+1; v_counter := v_counter+1; EXIT WHEN v_counter>10; EXIT WHEN v_counter>10; <<Inner_loop>> <<Inner_loop>> LOOP LOOP ... ... EXIT Outer_loop WHEN total_done = 'YES'; EXIT Outer_loop WHEN total_done = 'YES'; -- Leave both loops -- Leave both loops EXIT WHEN inner_done = 'YES'; EXIT WHEN inner_done = 'YES'; -- Leave inner loop only -- Leave inner loop only ... ... END LOOP Inner_loop; END LOOP Inner_loop; ... ... END LOOP Outer_loop; END LOOP Outer_loop; END; END;
Copyright 2004, Oracle. All rights reserved.

Writing Explicit Cursors

Copyright 2004, Oracle. All rights reserved.

About Cursors
Every SQL statement executed by the Oracle Every SQL statement executed by the Oracle Server has an individual cursor associated with it: Server has an individual cursor associated with it:

Implicit cursors: Declared for all DML and PL/SQL Implicit cursors: Declared for all DML and PL/SQL SELECT statements SELECT statements Explicit cursors: Declared and named by the Explicit cursors: Declared and named by the programmer programmer

Copyright 2004, Oracle. All rights reserved.

Explicit Cursor Functions

Active set 7369 SMITH 7566 JONES Cursor 7788 SCOTT 7876 ADAMS 7902 FORD CLERK MANAGER ANALYST CLERK ANALYST Current row

Copyright 2004, Oracle. All rights reserved.

Controlling Explicit Cursors


No Yes DECLARE DECLARE OPEN OPEN FETCH FETCH EMPTY? CLOSE CLOSE

Create a
named SQL area

Identify
the active set

Load the
current row into variables

Test for
existing rows

Release
the active set

Return to
FETCH if rows found

Copyright 2004, Oracle. All rights reserved.

Controlling Explicit Cursors


Open the cursor. Pointer
Cursor

Fetch a row from the cursor. Pointer


Cursor

Continue until empty. Pointer


Cursor

Close the cursor.

Cursor
Copyright 2004, Oracle. All rights reserved.

Declaring the Cursor


Syntax Syntax
CURSOR cursor_name IS CURSOR cursor_name IS select_statement; select_statement;

Do not include the INTO clause in the cursor declaration. Do not include the INTO clause in the cursor declaration. If processing rows in a specific sequence is required, use the If processing rows in a specific sequence is required, use the ORDER BY clause in the query. ORDER BY clause in the query.

Copyright 2004, Oracle. All rights reserved.

Declaring the Cursor


Example Example
DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT empno, ename SELECT empno, ename FROM FROM emp; emp; CURSOR dept_cursor IS CURSOR dept_cursor IS SELECT * SELECT * FROM FROM dept dept WHERE deptno = 10; WHERE deptno = 10; BEGIN BEGIN ... ...

Copyright 2004, Oracle. All rights reserved.

Opening the Cursor


Syntax Syntax
OPEN cursor_name; OPEN cursor_name;

Open the cursor to execute the query and identify the Open the cursor to execute the query and identify the active set. active set. If the query returns no rows, no exception is raised. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch. Use cursor attributes to test the outcome after a fetch.

Copyright 2004, Oracle. All rights reserved.

Fetching Data from the Cursor


Syntax Syntax
FETCH cursor_name INTO [variable1, variable2, ...] FETCH cursor_name INTO [variable1, variable2, ...] | record_name]; | record_name];

Retrieve the current row values into output variables. Retrieve the current row values into output variables. Include the same number of variables. Include the same number of variables. Match each variable to correspond to the columns Match each variable to correspond to the columns positionally. positionally. Test to see if the cursor contains rows. Test to see if the cursor contains rows.

Copyright 2004, Oracle. All rights reserved.

Fetching Data from the Cursor


Example Example

FETCH emp_cursor INTO v_empno, v_ename; FETCH emp_cursor INTO v_empno, v_ename; ... ... OPEN defined_cursor; OPEN defined_cursor; LOOP LOOP FETCH defined_cursor INTO defined_variables FETCH defined_cursor INTO defined_variables EXIT WHEN ...; EXIT WHEN ...; ... ... -- Process the retrieved data -- Process the retrieved data ... ... END; END;

Copyright 2004, Oracle. All rights reserved.

Closing the Cursor


Syntax Syntax
CLOSE CLOSE

cursor_name; cursor_name;

Close the cursor after completing the processing of the Close the cursor after completing the processing of the rows. rows. Reopen the cursor, if required. Reopen the cursor, if required. Do not attempt to fetch data from a cursor once it has Do not attempt to fetch data from a cursor once it has been closed. been closed.

Copyright 2004, Oracle. All rights reserved.

Explicit Cursor Attributes


Obtain status information about a cursor. Obtain status information about a cursor.
Attribute %ISOPEN %NOTFOUND %FOUND Type Boolean Boolean Boolean Description Evaluates to TRUE if the cursor is open Evaluates to TRUE if the most recent fetch does not return a row Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND Evaluates to the total number of rows returned so far

%ROWCOUNT

Number

Copyright 2004, Oracle. All rights reserved.

The %ISOPEN Attribute


Fetch rows only when the cursor is open. Fetch rows only when the cursor is open. Use the %ISOPEN cursor attribute before performing a Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. fetch to test whether the cursor is open.

Example Example

IF NOT emp_cursor%ISOPEN THEN IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; OPEN emp_cursor; END IF; END IF; LOOP LOOP FETCH emp_cursor... FETCH emp_cursor...

Copyright 2004, Oracle. All rights reserved.

Controlling Multiple Fetches


Process several rows from an explicit cursor using a Process several rows from an explicit cursor using a loop. loop. Fetch a row with each iteration. Fetch a row with each iteration. Use the %NOTFOUND attribute to write a test for an Use the %NOTFOUND attribute to write a test for an unsuccessful fetch. unsuccessful fetch. Use explicit cursor attributes to test the success of Use explicit cursor attributes to test the success of each fetch. each fetch.

Copyright 2004, Oracle. All rights reserved.

The %NOTFOUND and %ROWCOUNT Attributes


Use the %ROWCOUNT cursor attribute to retrieve an Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows. exact number of rows. Use the %NOTFOUND cursor attribute to determine Use the %NOTFOUND cursor attribute to determine when to exit the loop. when to exit the loop.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Cursors and Records


Process the rows of the active set conveniently by Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. fetching values into a PL/SQL RECORD. Example Example

DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT empno, ename SELECT empno, ename FROM emp; FROM emp; emp_record emp_record emp_cursor%ROWTYPE; emp_cursor%ROWTYPE; BEGIN BEGIN OPEN emp_cursor; OPEN emp_cursor; LOOP LOOP FETCH emp_cursor INTO emp_record; FETCH emp_cursor INTO emp_record; ... ...

Copyright 2004, Oracle. All rights reserved.

Cursor FOR Loops


Syntax Syntax
FOR record_name IN cursor_name LOOP FOR record_name IN cursor_name LOOP statement1; statement1; statement2; statement2; . . . . . . END LOOP; END LOOP; FOR loop is a shortcut to process explicit The cursor FOR loop is a shortcut to process explicit The cursor

cursors. cursors. Implicit open, fetch, and close occur. Implicit open, fetch, and close occur. The record is implicitly declared. The record is implicitly declared.

Copyright 2004, Oracle. All rights reserved.

Cursor FOR Loops


Retrieve employees one by one until no more are Retrieve employees one by one until no more are left. left. Example Example
DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT ename, deptno SELECT ename, deptno FROM FROM emp; emp; BEGIN BEGIN FOR emp_record IN emp_cursor LOOP FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN IF emp_record.deptno = 30 THEN ... ... END LOOP; -- implicit close occurs END LOOP; -- implicit close occurs END; END;

Copyright 2004, Oracle. All rights reserved.

Cursor FOR Loops Using Subqueries


No need to declare the cursor. No need to declare the cursor. Example Example

BEGIN BEGIN FOR emp_record IN ( SELECT ename, deptno FOR emp_record IN ( SELECT ename, deptno FROM emp) LOOP FROM emp) LOOP -- implicit open and implicit fetch occur -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN IF emp_record.deptno = 30 THEN ... ... END LOOP; -- implicit close occurs END LOOP; -- implicit close occurs END; END;

Copyright 2004, Oracle. All rights reserved.

Advanced Explicit Cursor Concepts

Copyright 2004, Oracle. All rights reserved.

Cursors with Parameters


Syntax
CURSOR cursor_name CURSOR cursor_name [(parameter_name datatype, ...)] [(parameter_name datatype, ...)] IS IS select_statement; select_statement;

Pass parameter values to a cursor when the cursor is opened and the query is executed. Open an explicit cursor several times with a different active set each time.

Copyright 2004, Oracle. All rights reserved.

Cursors with Parameters


Pass the department number and job title to the Pass the department number and job title to the WHERE clause. WHERE clause. Example Example
DECLARE DECLARE CURSOR emp_cursor CURSOR emp_cursor (v_deptno NUMBER, v_job VARCHAR2) IS (v_deptno NUMBER, v_job VARCHAR2) IS SELECT empno, ename SELECT empno, ename FROM emp FROM emp WHERE deptno = v_deptno WHERE deptno = v_deptno AND job = v_job; AND job = v_job; BEGIN BEGIN OPEN emp_cursor(10, 'CLERK'); OPEN emp_cursor(10, 'CLERK'); ... ...

Copyright 2004, Oracle. All rights reserved.

The FOR UPDATE Clause


Syntax Syntax
SELECT ... SELECT ... FROM ... FROM ... FOR UPDATE [OF column_reference][NOWAIT] FOR UPDATE [OF column_reference][NOWAIT]

Explicit locking lets you deny access for the duration of Explicit locking lets you deny access for the duration of a transaction. a transaction. Lock the rows before the update or delete. Lock the rows before the update or delete.

Copyright 2004, Oracle. All rights reserved.

The FOR UPDATE Clause


Retrieve the employees who work in department 30. Retrieve the employees who work in department 30. Example Example

DECLARE DECLARE CURSOR emp_cursor IS CURSOR emp_cursor IS SELECT empno, ename, sal SELECT empno, ename, sal FROM FROM emp emp WHERE deptno = 30 WHERE deptno = 30 FOR UPDATE NOWAIT; FOR UPDATE NOWAIT;

Copyright 2004, Oracle. All rights reserved.

The WHERE CURRENT OF Clause


Syntax
WHERE CURRENT OF cursor WHERE CURRENT OF cursor

Use cursors to update or delete the current row. Include the FOR UPDATE clause in the cursor query to lock the rows first. Use the WHERE CURRENT OF clause to reference the current row from an explicit cursor.

Copyright 2004, Oracle. All rights reserved.

The WHERE CURRENT OF Clause


Example Example
DECLARE DECLARE CURSOR sal_cursor IS CURSOR sal_cursor IS SELECT sal SELECT sal FROM emp FROM emp WHERE deptno = 30 WHERE deptno = 30 FOR UPDATE NOWAIT; FOR UPDATE NOWAIT; BEGIN BEGIN FOR emp_record IN sal_cursor LOOP FOR emp_record IN sal_cursor LOOP UPDATE emp UPDATE emp SET sal = emp_record.sal * 1.10 SET sal = emp_record.sal * 1.10 WHERE CURRENT OF sal_cursor; WHERE CURRENT OF sal_cursor; END LOOP; END LOOP; COMMIT; COMMIT; END; END;

Copyright 2004, Oracle. All rights reserved.

Cursors with Subqueries


Example Example
DECLARE DECLARE CURSOR my_cursor IS CURSOR my_cursor IS SELECT t1.deptno, dname, STAFF SELECT t1.deptno, dname, STAFF FROM FROM dept t1, (SELECT deptno, dept t1, (SELECT deptno, count(*) STAFF count(*) STAFF FROM emp FROM emp GROUP BY deptno) t2 GROUP BY deptno) t2 WHERE t1.deptno = t2.deptno WHERE t1.deptno = t2.deptno AND STAFF >= 5; AND STAFF >= 5;

Copyright 2004, Oracle. All rights reserved.

Handling Exceptions

Copyright 2004, Oracle. All rights reserved.

Handling Exceptions with PL/SQL


What is an exception? What is an exception?


Identifier in PL/SQL that is raised during execution Identifier in PL/SQL that is raised during execution

How is it raised? How is it raised?


An Oracle error occurs. An Oracle error occurs. You raise it explicitly. You raise it explicitly.

How do you handle it? How do you handle it?


Trap it with a handler. Trap it with a handler. Propagate it to the calling environment. Propagate it to the calling environment.

Copyright 2004, Oracle. All rights reserved.

Handling Exceptions
Trap the exception DECLARE BEGIN
Exception is raised

Propagate the exception


DECLARE BEGIN EXCEPTION END;

EXCEPTION

Exception is raised Exception is not trapped

Exception is trapped END;

Exception propagates to calling environment

Copyright 2004, Oracle. All rights reserved.

Exception Types

Predefined Oracle Server Predefined Oracle Server Non-predefined Oracle Server Non-predefined Oracle Server User-defined User-defined

Implicitly raised

Explicitly raised

Copyright 2004, Oracle. All rights reserved.

Trapping Exceptions
Syntax Syntax
EXCEPTION EXCEPTION WHEN exception1 [OR exception2 . . .] THEN WHEN exception1 [OR exception2 . . .] THEN statement1; statement1; statement2; statement2; . . . . . . [WHEN exception3 [OR exception4 . . .] THEN [WHEN exception3 [OR exception4 . . .] THEN statement1; statement1; statement2; statement2; . . .] . . .] [WHEN OTHERS THEN [WHEN OTHERS THEN statement1; statement1; statement2; statement2; . . .] . . .]

Copyright 2004, Oracle. All rights reserved.

Trapping Exceptions Guidelines


WHEN OTHERS is the last clause. WHEN OTHERS is the last clause. EXCEPTION keyword starts exception-handling EXCEPTION keyword starts exception-handling section. section. Several exception handlers are allowed. Several exception handlers are allowed. Only one handler is processed before leaving the Only one handler is processed before leaving the block. block.

Copyright 2004, Oracle. All rights reserved.

Trapping Predefined Oracle Server Errors


Reference the standard name in the exceptionReference the standard name in the exceptionhandling routine. handling routine. Sample predefined exceptions: Sample predefined exceptions:
NO_DATA_FOUND NO_DATA_FOUND TOO_MANY_ROWS TOO_MANY_ROWS INVALID_CURSOR INVALID_CURSOR ZERO_DIVIDE ZERO_DIVIDE DUP_VAL_ON_INDEX DUP_VAL_ON_INDEX

Copyright 2004, Oracle. All rights reserved.

Predefined Exception
Syntax Syntax
BEGIN SELECT ... COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; WHEN OTHERS THEN statement1; statement2; statement3; END;

Copyright 2004, Oracle. All rights reserved.

Trapping Non-Predefined Oracle Server Errors

Declare

Associate

Reference
Exception-handling section

Declarative section

Name the
exception

Code the PRAGMA Handle the


EXCEPTION_INIT raised exception

Copyright 2004, Oracle. All rights reserved.

Non-Predefined Error
Trap for Oracle Server error number Trap for Oracle Server error number 2292, an integrity constraint violation. 2292, an integrity constraint violation.
DECLARE DECLARE e_emps_remaining EXCEPTION; EXCEPTION; e_emps_remaining EXCEPTION; e_emps_remaining PRAGMA EXCEPTION_INIT ( PRAGMA EXCEPTION_INIT ( PRAGMA EXCEPTION_INIT ( e_emps_remaining, -2292); e_emps_remaining, -2292); e_emps_remaining, -2292); v_deptno dept.deptno%TYPE := &p_deptno; v_deptno dept.deptno%TYPE := &p_deptno; BEGIN BEGIN DELETE FROM dept DELETE FROM dept WHERE deptno = v_deptno; WHERE deptno = v_deptno; COMMIT; COMMIT; EXCEPTION EXCEPTION WHEN e_emps_remaining THEN WHEN e_emps_remaining THEN DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. '); TO_CHAR(v_deptno) || '. Employees exist. '); END; END;
Copyright 2004, Oracle. All rights reserved.

1 2

Trapping User-Defined Exceptions

Declare
Declarative section

Raise
Executable section

Reference
Exception-handling section

Name the
exception

Explicitly raise
the exception by using the RAISE statement

Handle the
raised exception

Copyright 2004, Oracle. All rights reserved.

User-Defined Exception
Example Example
DECLARE DECLARE EXCEPTION; e_invalid_product EXCEPTION; e_invalid_product EXCEPTION; BEGIN BEGIN UPDATE product UPDATE product SET descrip = '&product_description' SET descrip = '&product_description' WHERE prodid = &product_number; WHERE prodid = &product_number; IF SQL%NOTFOUND THEN IF SQL%NOTFOUND THEN RAISE e_invalid_product; RAISE e_invalid_product; END IF; END IF; COMMIT; COMMIT; EXCEPTION EXCEPTION e_invalid_product WHEN e_invalid_product THEN WHEN e_invalid_product THEN DBMS_OUTPUT.PUT_LINE('Invalid product number.'); DBMS_OUTPUT.PUT_LINE('Invalid product number.'); END; END; 1

Copyright 2004, Oracle. All rights reserved.

Functions for Trapping Exceptions


SQLCODE SQLCODE
Returns the numeric value for the error code Returns the numeric value for the error code

SQLERRM SQLERRM
Returns the message associated with the error number Returns the message associated with the error number

Copyright 2004, Oracle. All rights reserved.

Functions for Trapping Exceptions


Example Example
DECLARE v_error_code v_error_message BEGIN ... EXCEPTION ... WHEN OTHERS THEN ROLLBACK; v_error_code := v_error_message NUMBER; VARCHAR2(255);

SQLCODE ; := SQLERRM ;

INSERT INTO errors VALUES(v_error_code, v_error_message); END;

Copyright 2004, Oracle. All rights reserved.

Calling Environments
SQL*Plus Procedure Builder Oracle Developer Forms Precompiler application An enclosing PL/SQL block
Copyright 2004, Oracle. All rights reserved.

Displays error number and message to screen Displays error number and message to screen Accesses error number and message in a trigger by means of the ERROR_CODE and ERROR_TEXT packaged functions Accesses exception number through the SQLCA data structure Traps exception in exceptionhandling routine of enclosing block

Copyright 2004, Oracle. All rights reserved.

RAISE_APPLICATION_ERROR Procedure
Syntax Syntax
raise_application_error (error_number, raise_application_error (error_number, message[, {TRUE | FALSE}]); message[, {TRUE | FALSE}]);

A procedure that lets you issue user-defined error A procedure that lets you issue user-defined error messages from stored subprograms messages from stored subprograms Called only from an executing stored subprogram Called only from an executing stored subprogram

Copyright 2004, Oracle. All rights reserved.

RAISE_APPLICATION_ERROR Procedure

Used in two different places: Used in two different places:


Executable section Executable section Exception section Exception section

Returns error conditions to the user in a manner Returns error conditions to the user in a manner consistent with other Oracle Server errors consistent with other Oracle Server errors

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Procedure and Function

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Package

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Trigger

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Managing Dependencies

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Q U E S T I O N S A N S W E R S

Copyright 2004, Oracle. All rights reserved.

S-ar putea să vă placă și