oracle sql & plsql

412
Copyright © 2004, Oracle. All rights reserved.

Upload: sid-xing

Post on 10-May-2015

8.036 views

Category:

Technology


20 download

DESCRIPTION

Oracle SQL & PLSQL fundamental

TRANSCRIPT

Page 1: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 2: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Oracle SQL & PL/SQL

Huiyun [email protected]

Page 3: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

SQL OverviewSQL Overview

Page 4: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Data retrieval language (DRL)Data retrieval language (DRL)

Data manipulation language (DML)Data manipulation language (DML)

Data definition language (DDL)Data definition language (DDL)

Transaction controlTransaction control

Data control language (DCL)Data control language (DCL)

SELECTSELECT

INSERTINSERTUPDATEUPDATEDELETEDELETECREATECREATEALTERALTERDROPDROPRENAMERENAMETRUNCATETRUNCATE

COMMITCOMMITROLLBACKROLLBACKSAVEPOINTSAVEPOINT

GRANTGRANTREVOKEREVOKE

SQL StatementsSQL Statements

Page 5: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Tables Used in the CourseTables Used in the Course

Three main tables are used in this course:– EMP table– DEPT table

Three main tables are used in this course:– EMP table– DEPT table

Page 6: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The EMP TableThe EMP TableEMPEMP

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

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

7839 KING PRESIDENT 17-NOV-81 5000 10

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7782 CLARK MANAGER 7839 09-JUN-81 1500 10

7566 JONES MANAGER 7839 02-APR-81 2975 20

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

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

7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30

7900 JAMES CLERK 7698 03-DEC-81 950 30

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

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7369 SMITH CLERK 7902 17-DEC-80 800 20

7788 SCOTT ANALYST 7566 09-DEC-82 3000 20

7876 ADAMS CLERK 7788 12-JAN-83 1100 20

7934 MILLER CLERK 7782 23-JAN-82 1300 10

Foreign keyForeign keyPrimary keyPrimary key Foreign keyForeign key

Page 7: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

DEPT TablesDEPT Tables

DEPTDEPTDEPTNO DNAME LOC

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

10 ACCOUNTING NEW YORK

20 RESEARCH DALLAS

30 SALES CHICAGO

40 OPERATIONS BOSTON

Primary keyPrimary key

Page 8: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Writing Basic SQL StatementsWriting Basic SQL Statements

Page 9: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Capabilities of SQL SELECT StatementsCapabilities of SQL SELECT Statements

ProjectionProjectionRestrictionRestriction

Table 1Table 1 Table 2Table 2

Table 1Table 1 Table 1Table 1JoinJoin

Page 10: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Basic SELECT StatementBasic SELECT Statement

SELECT [DISTINCT] {*, column [alias],...}FROM table[WHERE condition(s)][GROUP BY group_by_expression][ORDER BY column];

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

Page 11: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Writing SQL StatementsWriting SQL Statements

– SQL statements are not case sensitive. – SQL statements can be on one or

more lines.– Keywords cannot be abbreviated or split across lines.– Clauses are usually placed on

separate lines.– Tabs and indents are used to enhance readability.

– SQL statements are not case sensitive. – SQL statements can be on one or

more lines.– Keywords cannot be abbreviated or split across lines.– Clauses are usually placed on

separate lines.– Tabs and indents are used to enhance readability.

Page 12: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Retrieving All Columns from a TableRetrieving All Columns from a Table

DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON

DEPTDEPT Retrieve allRetrieve allcolumns from the columns from the

DEPT tableDEPT table

DEPTDEPTDEPTNO DNAME LOC

10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON

All columns are displayedAll columns are displayed

Page 13: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Selecting All ColumnsSelecting All Columns

DEPTNO DNAME LOC--------- -------------- -------------

10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON

SQL> SELECT *2 FROM dept;

Page 14: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Creating a Projection on a TableCreating a Projection on a Table

Retrieve DEPTNO Retrieve DEPTNO and LOC columns and LOC columns

from the DEPT from the DEPT tabletable

DEPTDEPTDEPTNO LOC

10 NEW YORK20 DALLAS30 CHICAGO40 BOSTON

DEPTNO DNAME LOC

10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON

DEPTDEPT

OnlyOnly two columns are displayedtwo columns are displayed

Page 15: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Selecting Specific ColumnsSelecting Specific Columns

DEPTNO LOC--------- -------------

10 NEW YORK20 DALLAS30 CHICAGO40 BOSTON

SQL> SELECT deptno, loc2 FROM dept;

Page 16: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Default Column JustificationDefault Column Justification

EMPEMP

Character Character left justifiedleft justified

Date Date left justifiedleft justified

Number Number right justifiedright justified

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

Page 17: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Arithmetic ExpressionsArithmetic Expressions

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

Operator

+

-

*

/

Description

Add

Subtract

Multiply

Divide

Page 18: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Arithmetic OperatorsUsing Arithmetic Operators

SQL> SELECT ename, sal, sal+3002 FROM emp;

ENAME SAL SAL+300---------- --------- ---------KING 5000 5300BLAKE 2850 3150CLARK 2450 2750JONES 2975 3275MARTIN 1250 1550ALLEN 1600 1900...14 rows selected.

Page 19: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Arithmetic Operators on Multiple ColumnsUsing Arithmetic Operators on Multiple Columns

SQL> SELECT grade, hisal-losal2 FROM salgrade;

GRADE HISAL-LOSAL--------- -----------

1 5002 1993 5994 9995 6998

Page 20: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Operator PrecedenceOperator Precedence

– Multiplication and division take priority over addition and subtraction.

– Operators of the same priority are evaluated from left to right.

– Parentheses are used to force prioritized evaluation and to clarify statements.

– Multiplication and division take priority over addition and subtraction.

– Operators of the same priority are evaluated from left to right.

– Parentheses are used to force prioritized evaluation and to clarify statements.

** // ++ __

Page 21: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Operator PrecedenceOperator Precedence

SQL> SELECT ename, sal, 12*sal+1002 FROM emp;

ME SAL 12*SAL+100------- --------- ----------G 5000 60100KE 2850 34300RK 2450 29500ES 2975 35800TIN 1250 15100EN 1600 19300

14 rows selected.

ENA---KINBLACLAJONMARALL...

Page 22: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using ParenthesesUsing Parentheses

SQL> SELECT ename, sal, 12*(sal+100)2 FROM emp;

ME SAL 12*(SAL+100)------- --------- -----------G 5000 61200KE 2850 35400RK 2450 30600ES 2975 36900TIN 1250 16200

14 rows selected.

ENA---KINBLACLAJONMAR...

Page 23: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Defining a Column AliasDefining a Column Alias

– Renames a column heading– Is useful with calculations– Immediately follows column name; optional AS

keyword between column name and alias– Requires double quotation marks if it is case sensitive

or contains spaces or special characters

– Renames a column heading– Is useful with calculations– Immediately follows column name; optional AS

keyword between column name and alias– Requires double quotation marks if it is case sensitive

or contains spaces or special characters

Page 24: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Column AliasesUsing Column Aliases

SQL> SELECT ename AS name, sal salary2 FROM emp;

NAME SALARY

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

KING 5000

BLAKE 2850

CLARK 2450

JONES 2975

...

14 rows selected.

Page 25: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Column AliasesUsing 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.

Page 26: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Concatenation OperatorConcatenation Operator

– Concatenates columns or character strings to other columns

– Is represented by two vertical bars ||– Creates a result column that is a character expression

– Concatenates columns or character strings to other columns

– Is represented by two vertical bars ||– Creates a result column that is a character expression

Page 27: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the Concatenation OperatorUsing the Concatenation Operator

SQL> SELECT ename||job AS "Employees"2 FROM emp;

Employees-------------------KINGPRESIDENTBLAKEMANAGERCLARKMANAGERJONESMANAGERMARTINSALESMANALLENSALESMAN...14 rows selected.

Page 28: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

LiteralsLiterals

– A literal is a constant value of character, expression, or number that can be included in the SELECT list.

– Date and character literal values must be enclosed in single quotation marks.

– Each character string is output once for each row returned.

– A literal is a constant value of character, expression, or number that can be included in the SELECT list.

– Date and character literal values must be enclosed in single quotation marks.

– Each character string is output once for each row returned.

Page 29: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Literal Character StringsUsing Literal Character Strings

SQL> SELECT ename||' is a '||job AS 2 "Employee Details"3 FROM emp;

Employee Details-------------------------KING is a PRESIDENTBLAKE is a MANAGERCLARK is a MANAGERJONES is a MANAGERMARTIN is a SALESMAN...14 rows selected.

Page 30: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Duplicate RowsDuplicate Rows

The default display of queries is all rows, including duplicate rows.The default display of queries is all rows, including duplicate rows.

SQL> SELECT2 FROM emp;

deptno

DEPTNO---------

10301020..

14 rows selected.

Page 31: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Eliminating Duplicate RowsEliminating Duplicate Rows

Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.Eliminate duplicate rows by using the DISTINCT keyword in the SELECT clause.

SQL> SELECT DISTINCT deptno2 FROM emp;

DEPTNO---------

102030

Page 32: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Restricting and Sorting DataRestricting and Sorting Data

Page 33: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Limiting Rows by Using a RestrictionLimiting Rows by Using a Restriction

EMPNO ENAME JOB ... DEPTNO

7839 KING PRESIDENT 107698 BLAKE MANAGER 307782 CLARK MANAGER 107566 JONES MANAGER 20...

EMPNO ENAME JOB ... DEPTNO

7839 KING PRESIDENT 107782 CLARK MANAGER 107934 MILLER CLERK 10

Retrieve allRetrieve allemployeesemployees

in department 10in department 10

EMPEMP

EMPEMP

Page 34: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the WHERE ClauseUsing the WHERE Clause

SQL> SELECT ename, job, deptno2 FROM emp3 WHERE deptno=10;

ENAME JOB DEPTNO---------- --------- ---------KING PRESIDENT 10CLARK MANAGER 10MILLER CLERK 10

Page 35: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Character Strings and DatesCharacter Strings and Dates

– Character strings and date values are enclosed in single quotation marks.

– Character values are case sensitive and date values are format sensitive.

– Default date format is DD-MON-YY.

– Character strings and date values are enclosed in single quotation marks.

– Character values are case sensitive and date values are format sensitive.

– Default date format is DD-MON-YY.

SQL> SELECT ename, job, deptno, hiredate2 FROM emp3 WHERE ename = 'JAMES';

Page 36: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Comparison OperatorsComparison Operators

Operator

=

>

>=

<

<=

<>

Meaning

Equal to

Greater than

Greater than or equal to

Less than

Less than or equal to

Not equal to

Page 37: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the Comparison Operators with Another ColumnUsing the Comparison Operators with Another Column

SQL> SELECT ename, sal, comm2 FROM emp3 WHERE sal<=comm;

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

Page 38: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the Comparison Operators with CharactersUsing the Comparison Operators with Characters

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

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

Page 39: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Other SQL Comparison OperatorsOther 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

Page 40: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the BETWEEN OperatorUsing the BETWEEN Operator

Use the BETWEEN operator to display rows based on a range of values.Use the BETWEEN operator to display rows based on a range of values.

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

SQL> SELECT ename, sal2 FROM emp3 WHERE sal BETWEEN 1000 AND 1500;

Lowerlimit

Higherlimit

Page 41: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the IN OperatorUsing 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 empno, ename, sal, mgr2 FROM emp3 WHERE mgr IN (7902, 7566, 7788);

EMPNO ENAME SAL MGR--------- ---------- --------- ---------

7902 FORD 3000 75667369 SMITH 800 79027788 SCOTT 3000 75667876 ADAMS 1100 7788

Page 42: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the IN Operator with StringsUsing the IN Operator with Strings

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

SQL> SELECT ename, deptno, hiredate 2 FROM emp3 WHERE ename IN ('BLAKE','MARTIN');

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

Page 43: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the LIKE OperatorUsing the LIKE Operator

– Use the LIKE operator to perform wildcard searches of valid search string values.

– Search conditions can contain either literal characters or numbers.

% denotes zero or many characters_ denotes one character

– Use the LIKE operator to perform wildcard searches of valid search string values.

– Search conditions can contain either literal characters or numbers.

% denotes zero or many characters_ denotes one character

SQL> SELECT ename2 FROM emp3 WHERE ename LIKE 'S%';

Page 44: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the LIKE OperatorUsing the LIKE Operator

SQL> SELECT ename2 FROM emp3 WHERE ename LIKE '_A%';

ENAME----------MARTINJAMES WARD

• You can combine pattern matching characters.

• Use the ESCAPE identifier to search for % or _.

• You can combine pattern matching characters.

• Use the ESCAPE identifier to search for % or _.

Page 45: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the IS NULL OperatorUsing the IS NULL Operator

Test for null values with the IS NULL operator.Test for null values with the IS NULL operator.

SQL> SELECT ename, mgr2 FROM emp3 WHERE mgr IS NULL;

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

Page 46: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Logical OperatorsLogical Operators

Operator

AND

OR

NOT

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

Page 47: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the AND OperatorUsing the AND Operator

AND requires both conditions to be TRUE.AND requires both conditions to be TRUE.

SQL> SELECT empno, ename, job, sal2 FROM emp3 WHERE sal>=11004 AND job='CLERK';

EMPNO ENAME JOB SAL------ ---------- --------- ---------7876 ADAMS CLERK 11007934 MILLER CLERK 1300

---

Page 48: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the AND OperatorUsing the AND Operator

AND requires both conditions to be TRUE.AND requires both conditions to be TRUE.

SQL> SELECT ename, mgr, sal,deptno2 FROM emp3 WHERE sal>10004 AND deptno = 10;

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

Page 49: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the OR OperatorUsing the OR Operator

OR requires either condition to be TRUE.OR requires either condition to be TRUE.OR requires either condition to be TRUE.SQL> SELECT empno, ename, job, sal2 FROM emp3 WHERE sal>=20004 OR job='CLERK';

EMPNO ENAME JOB SAL--------- ---------- --------- ---------

7839 KING PRESIDENT 50007698 BLAKE MANAGER 28507782 CLARK MANAGER 24507566 JONES MANAGER 29757900 JAMES CLERK 9507902 FORD ANALYST 3000...

10 rows selected.

Page 50: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the OR OperatorUsing the OR Operator

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

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

SQL> SELECT ename, deptno, mgr2 FROM emp3 4

WHERE deptno = 10OR mgr = 7839;

DEPTNO--------1030 10 20 10

MGR---------

7839783978397782

Page 51: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the NOT OperatorUsing the NOT Operator

SQL> SELECT ename, job2 FROM emp3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');

ENAME JOB---------- ---------KING PRESIDENTMARTIN SALESMANALLEN SALESMANTURNER SALESMANWARD SALESMAN

Page 52: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the NOT OperatorUsing the NOT Operator

> SELECT empno,ename,deptno,mgr2 FROM emp3 WHERE mgr NOT LIKE '78%';

SQL

EMPNO ENAME DEPTNO MGR--------- ---------- --------- ---------

7654 MARTIN 30 76987499 ALLEN 30 7698... ... 7902 FORD 20 75667369 SMITH 20 7902...

10 rows selected.

Page 53: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the NOT OperatorUsing the NOT Operator

SQL> SELECT empno, sal, mgr 2 FROM emp3 WHERE sal NOT BETWEEN 1000 AND 1500;

EMPNO SAL MGR--------- --------- ---------

7839 50007698 2850 78397782 2450 78397566 2975 78397499 1600 76987900 950 76987902 3000 75667369 800 79027788 3000 7566

9 rows selected.

Page 54: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the NOT OperatorUsing the NOT Operator

SQL> SELECT ename, sal AS "Salary Before Commission", 2 comm3 FROM emp4 WHERE comm IS NOT NULL;

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

Page 55: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Rules of PrecedenceRules of Precedence

Order Evaluated Operator1 All comparison

operators2 NOT3 AND4 OR

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

Page 56: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Rules of PrecedenceRules of Precedence

SQL> SELECT ename, job, sal2 FROM emp3 WHERE job='SALESMAN'4 OR job='PRESIDENT'5 AND sal>1500;

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

SAL---------50001250160015001250

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

Page 57: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Rules of PrecedenceRules of Precedence

Use parentheses to force priority.Use parentheses to force priority.Use parentheses to force priority.

SQL> SELECT ename, job, sal2 FROM emp3 WHERE (job='SALESMAN'4 OR job='PRESIDENT')5 AND sal>1500;

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

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

SAL---------

50001600

Page 58: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

ORDER BY ClauseORDER BY Clause– Sort rows with the ORDER BY clause:

ASC: ascending order, defaultDESC: descending order

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

– Sort rows with the ORDER BY clause:ASC: ascending order, defaultDESC: descending order

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

SQL> SELECT ename, job, deptno2 FROM emp3 ORDER BY deptno;

ENAME JOB DEPTNO---------- --------- ---------KING PRESIDENT 10CLARK MANAGER 10...JONES MANAGER 20SCOTT ANALYST 20...14 rows selected.

Page 59: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Sorting in Descending OrderSorting in Descending Order

SQL> SELECT ename, job, deptno, sal2 FROM emp3 ORDER BY sal DESC;

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

Page 60: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Sorting by Column AliasSorting by Column Alias

SQL> SELECT empno, ename, sal*12 annsal2 FROM emp3 ORDER BY annsal;

EMPNO ENAME ANNSAL--------- ---------- ---------

7369 SMITH 96007900 JAMES 114007876 ADAMS 132007654 MARTIN 150007521 WARD 150007934 MILLER 156007844 TURNER 18000...

14 rows selected.

Page 61: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Sorting by Multiple ColumnsSorting by Multiple Columns

The order of an ORDER BY list is the order of the sort.The order of an ORDER BY list is the order of the sort.

SQL> SELECT ename, deptno, sal2 FROM emp3 ORDER BY deptno, sal DESC;

ENAME DEPTNO SAL---------- --------- ---------KING 10 5000CLARK 10 2450MILLER 10 1300FORD 20 3000...14 rows selected.

Page 62: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Sorting by a Column Not in the SELECT ListSorting by a Column Not in the SELECT ListSQL> SELECT ename, deptno 2 FROM emp 3 ORDER BY sal;

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

Page 63: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Single-Row Number and Character FunctionsSingle-Row Number and Character Functions

Page 64: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

How a Function WorksHow a Function Works

OutputOutputFunctionFunctionInputInput

PerformsPerformsoperationoperation

Page 65: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Two Types of SQL Functions

SingleSingle--row row functionsfunctions

MultipleMultiple--rowrowfunctionsfunctions

Two Types of SQL Functions

FunctionsFunctions

Page 66: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Single-Row FunctionsSingle-Row Functions

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

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

Page 67: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

ConversionConversion

NumberNumber

DateDate

SingleSingle--row row functionsfunctions

CharacterCharacter

Single-Row FunctionsSingle-Row Functions

Page 68: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Character FunctionsCharacter Functions

Case conversion Case conversion functionsfunctions

Character manipulationCharacter manipulationfunctionsfunctions

CharacterCharacterfunctionsfunctions

LOWERLOWERUPPERUPPERINITCAPINITCAP

Page 69: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Case Conversion FunctionsCase Conversion Functions

Convert the case for character strings

Function Result

Convert the case for character strings

sql courseSQL COURSESql Course

LOWER('SQL Course')UPPER('SQL Course')INITCAP('SQL Course')

Page 70: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Case Conversion FunctionsUsing Case Conversion Functions

Display the employee number, name, and department number for employee Blake.Display the employee number, name, and department number for employee Blake.

SQL> SELECT empno, ename, deptno 2 FROM emp3 WHERE ename = 'blake';

no rows selectedno rows selected

SQL> SELECT empno, ename, deptno2 FROM emp3 WHERE ename = UPPER('blake');

EMPNO ENAME DEPTNO--------- ---------- ---------

7698 BLAKE 30

Page 71: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Case Conversion FunctionsUsing Case Conversion Functions

Display the employee name for all employees with an initial capital.Display the employee name for all employees with an initial capital.

SQL> SELECT INITCAP(ename) as EMPLOYEE2 FROM emp;

EMPLOYEE----------KingBlakeClarkJonesMartin...14 rows selected.

Page 72: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Number FunctionsNumber Functions

– ROUND: Rounds value to specified decimalROUND(45.926, 2)

45.93– TRUNC: Truncates value to specified decimal

TRUNC(45.926, 2)45.92

– MOD: Returns remainder of divisionMOD(1600, 300)

100

– ROUND: Rounds value to specified decimalROUND(45.926, 2)

45.93– TRUNC: Truncates value to specified decimal

TRUNC(45.926, 2)45.92

– MOD: Returns remainder of divisionMOD(1600, 300)

100

Page 73: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Defining a Null ValueDefining a Null Value

– A null is a value that is unavailable, unassigned, unknown, or inapplicable.

– A null is not the same as zero or a blank space.

– A null is a value that is unavailable, unassigned, unknown, or inapplicable.

– A null is not the same as zero or a blank space.

SQL> SELECT ename, job, comm2 FROM emp;

ENAME JOB COMM---------- --------- ---------KING PRESIDENTBLAKE MANAGER...TURNER SALESMAN 0...14 rows selected.

Page 74: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Null Values in Arithmetic ExpressionsNull Values in Arithmetic Expressions

Arithmetic expressions that contain a null value evaluate to null.Arithmetic expressions that contain a null value evaluate to null.

SQL> SELECT ename NAME, 12*sal+comm2 FROM emp;

NAME 12*SAL+COMM---------- -----------KINGBLAKECLARKJONESMARTIN 16400...14 rows selected.

Page 75: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the NVL FunctionUsing the NVL Function

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

– NVL can be used with date, character, and number data types.

– Data types must match. For example:NVL(comm,0)NVL(hiredate,'01-JAN-97')NVL(job,'no job yet')

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

– NVL can be used with date, character, and number data types.

– Data types must match. For example:NVL(comm,0)NVL(hiredate,'01-JAN-97')NVL(job,'no job yet''no job yet')

NVL (expr1, expr2)

Page 76: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the NVL Function to Handle Null ValuesUsing 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 60000BLAKE MANAGER 34200CLARK MANAGER 29400JONES MANAGER 35700MARTIN SALESMAN 16400ALLEN SALESMAN 19500TURNER SALESMAN 18000...14 rows selected.

Page 77: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Single-Row Date and Conversion FunctionsSingle-Row Date and Conversion Functions

Page 78: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

ConversionConversion DateDate

SingleSingle--row row functionsfunctions

CharacterCharacter

Single-Row FunctionsSingle-Row Functions

NumberNumber

Page 79: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Working with DatesWorking with Dates

– Oracle stores dates in an internal 7 byte numeric format: century, year, month, day, hours, minutes, seconds.

– The default date format is DD-MON-YY.

– Oracle stores dates in an internal 7 byte numeric format: century, year, month, day, hours, minutes, seconds.

– The default date format is DD-MON-YY.

Page 80: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

SYSDATESYSDATE

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

dummy table.

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

dummy table.

SQL> SELECT SYSDATE2 FROM DUAL;

SYSDATE---------26-JAN-98

Page 81: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Default Date FormatsDefault Date Formats

Columns that are defined as DATE aredisplayed as DD-MON-YY by default.Columns that are defined as DATE aredisplayed as DD-MON-YY by default.

SQL> SELECT ename, hiredate2 FROM emp3 WHERE ename='SMITH';

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

Page 82: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Arithmetic with DatesArithmetic with Dates

– Add or subtract a number to or from a date to obtain a datevalue

– Subtract two dates to find the number of days between those dates

– Add or subtract a number to or from a date to obtain a datevalue

– Subtract two dates to find the number of days between those dates

Page 83: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Arithmetic Operatorswith DatesUsing Arithmetic Operatorswith Dates

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

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

Page 84: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using SYSDATE in Calculations Using SYSDATE in Calculations

Determine for how many weeks employees have workedDetermine for how many weeks employees have worked

SQL> SELECT ename, (SYSDATE-hiredate)/7 2 "WEEKS AT WORK"3 FROM emp4 WHERE deptno=10;

ENAME WEEKS AT WORK---------- -------------KING 844.94617CLARK 867.94617MILLER 835.37474

Page 85: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Explicit Data Type ConversionExplicit Data Type Conversion

NUMBERNUMBER CHARACTERCHARACTER

TO_CHARTO_CHAR TO_CHARTO_CHAR

TO_NUMBERTO_NUMBER

DATEDATE

TO_DATETO_DATE

Page 86: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Modifying the Display Format of DatesModifying the Display Format of Dates

2727--JANJAN--9898

Tuesday the 27th of January, 1998Tuesday the 27th of January, 1998

January 27, 1998January 27, 1998

01/27/9801/27/98

Page 87: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

TO_CHAR Function with DatesTO_CHAR Function with Dates

The format model:– Is case sensitive and must be enclosed in single

quotation marks – Can include any valid date format element– Has an fm element to remove padded blanks or

suppress leading zeros– Is separated from the date value by a comma

The format model:– Is case sensitive and must be enclosed in single

quotation marks – Can include any valid date format element– Has an fm element to remove padded blanks or

suppress leading zeros– Is separated from the date value by a comma

TO_CHAR(date, 'fmfmt')

Page 88: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Date Format Model ElementsDate Format Model Elements

YYYY

YEAR

MM

MONTH

DY

DAY

Full year in numbers

Year spelled out

2-digit value for month

3-letter abbreviation of the day of the weekFull name of the day

Full name of the month

Page 89: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with DatesUsing the TO_CHAR Function with Dates

SQL> SELECT ename, TO_CHAR(hiredate, 'Month DDth, YYYY')

2 AS HIREDATE

3 FROM emp

4 WHERE job='MANAGER';

ENAME HIREDATE

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

BLAKE May 01st, 1981

CLARK June 09th, 1981

JONES April 02nd, 1981

Page 90: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with DatesUsing the TO_CHAR Function with Dates

SQL> SELECT empno, TO_CHAR(hiredate, 'MM/YY') AS MONTH2 FROM emp3 WHERE ename='BLAKE';

EMPNO MONTH--------- -----

7698 05/81

Page 91: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with DatesUsing the TO_CHAR Function with Dates

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

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

Page 92: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with DatesUsing the TO_CHAR Function with Dates

SQL> SELECT ename, mgr, sal,TO_CHAR(hiredate,'YYYY-MON-DD')2 AS HIREDATE3 FROM emp4 WHERE sal<10005 AND hiredate like '%80';

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

Page 93: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with DatesUsing the TO_CHAR Function with Dates

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

EMPNO ENAME DEPTNO HIREDATE-------- ---------- --------- -----------

7369 SMITH 20 12-17-19807788 SCOTT 20 12-09-19827876 ADAMS 20 01-12-19837934 MILLER 10 01-23-1982

Page 94: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with DatesUsing the TO_CHAR Function with Dates

SQL> SELECT ename, job, deptno,2 TO_CHAR(hiredate,'DD-MON-YYYY') AS HIRE_DATE3 FROM emp4 ORDER BY hiredate DESC;

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

Page 95: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Date Format Model ElementsDate Format Model Elements

• Time elements format the time portion of the date.• Time elements format the time portion of the date.

HH24:MI:SS AM 15:45:32 PM

DD "of" MONTH 12 of OCTOBER

ddspth fourteenth

Page 96: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Format Models to Display TimeUsing Format Models to Display Time

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

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

Page 97: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

TO_CHAR Function with NumbersTO_CHAR Function with Numbers

Use these formats with the TO_CHAR function to display a number value as a character:Use these formats with the TO_CHAR function to display a number value as a character:

TO_CHAR(n,'fmt')

90$L.,

Represents a numberForces a zero to be displayedPlaces a floating dollar signUses the floating local currency symbolPrints a decimal pointPlaces a thousand indicator

Page 98: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with NumbersUsing the TO_CHAR Function with Numbers

SQL> SELECT TO_CHAR(sal,'$99,999') SALARY2 FROM emp3 WHERE ename = 'SCOTT';

SALARY--------

$3,000

Dollar signDollar signThousand indicatorThousand indicator

Page 99: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_NUMBER and TO_DATE Functions Using the TO_NUMBER and TO_DATE Functions

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

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

TO_NUMBER(char)

• Convert a character string to a date data type using the TO_DATE function

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

Page 100: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the TO_NUMBER FunctionUsing the TO_NUMBER Function

SQL> SELECT TO_NUMBER('1000')+sal AS NEW_SALARY2 FROM emp3 WHERE ename = 'SCOTT';

NEW_SALARY----------

4000

Page 101: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Date FunctionsDate Functions

Number of monthsbetween two dates

MONTHS_BETWEEN

ADD_MONTHS

NEXT_DAY

LAST_DAY

ROUND

TRUNC

Adds calendar months to dateNext day following the date specified

Last day of the month

Round off date

Truncate date

FUNCTION DESCRIPTION

Page 102: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Date FunctionsUsing Date Functions

Use the ADD_MONTHS function to add months to a date.Use the ADD_MONTHS function to add months to a date.

SQL> SELECT ename, hiredate, ADD_MONTHS(hiredate, 6)2 AS "+6 MONTHS"3 FROM emp4 WHERE ename='BLAKE';

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

Page 103: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Nesting FunctionsNesting Functions

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

the outermost level.

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

the outermost level.

F3(F2(F1(col,arg1),arg2),arg3)

Step 1 = Result 1

Step 2 = Result 2

Step 3 = Result 3

Page 104: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Nesting FunctionsNesting Functions

Result 1 Result 2

SQL> SELECT ename,2 NVL(TO_CHAR(mgr),'No Manager')3 FROM emp4 WHERE mgr IS NULL;

ME NVL(TO_CHAR(MGR),'NOMANAGER')------- -----------------------------

KING No Manager

ENA---

Page 105: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Nesting FunctionsNesting FunctionsSQL> 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

Page 106: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Displaying Data from Multiple TablesDisplaying Data from Multiple Tables

Page 107: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Obtaining Data from Multiple TablesObtaining Data from Multiple TablesEMP EMP EMPNO ENAME ... DEPTNO

------ ----- ... ------7839 KING ... 107698 BLAKE ... 30...7934 MILLER ... 10

DEPTNO DNAME LOC ------ ---------- --------

10 ACCOUNTING NEW YORK20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON

EMPNO -----7839 7698 7782 75667654 7499

DEPTNO -------

10 30 10 20 30 30

LOC--------NEW YORKCHICAGONEW YORKDALLASCHICAGOCHICAGO

DEPT DEPT

Page 108: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Joining TablesJoining Tables

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

– Write the join condition in the WHERE clause.– Prefix the column name with the table name when the

same column name appears in more than one table.

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

– Write the join condition in the WHERE clause.– Prefix the column name with the table name when the

same column name appears in more than one table.

SELECT table1.column1, table2.column2FROM table1, table2WHERE table1.column1 = table2.column2;

Page 109: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Types of JoinsTypes of Joins

EquijoinEquijoin NonequijoinNonequijoin Self joinSelf join

Page 110: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

What Is an Equijoin?What Is an Equijoin?

EMPNO ENAME DEPTNO------ ------- -------...7782 CLARK 10

EMP EMP

DEPTNO DNAME LOC ------- ---------- --------

...10 ACCOUNTING NEW YORK...

DEPT DEPT

Links rows that satisfy a specified conditionLinks rows that satisfy a specified condition

WHEREWHERE empemp..deptnodeptno=dept.=dept.deptnodeptno

Page 111: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

EquijoinEquijoin

EMPNO ENAME DEPTNO------ ------- -------7839 KING 107698 BLAKE 307782 CLARK 107566 JONES 207654 MARTIN 307499 ALLEN 307844 TURNER 307900 JAMES 307521 WARD 307902 FORD 207369 SMITH 20

...14 rows selected.

DEPTNO DNAME LOC ------- ---------- --------

10 ACCOUNTING NEW YORK30 SALES CHICAGO10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS30 SALES CHICAGO30 SALES CHICAGO30 SALES CHICAGO30 SALES CHICAGO30 SALES CHICAGO20 RESEARCH DALLAS20 RESEARCH DALLAS

...14 rows selected.

EMP EMP DEPT DEPT

Primary keyPrimary keyForeign keyForeign key

Page 112: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Retrieving Records with an EquijoinRetrieving Records with an Equijoin

SQL> SELECT emp.empno, emp.ename, emp.deptno,2 dept.deptno, dept.loc3 FROM emp, dept4 WHERE emp.deptno=dept.deptno;

EMP---78767775

...

NO ENAME DEPTNO DEPTNO LOC-- ------ ------ ------ ---------39 KING 10 10 NEW YORK98 BLAKE 30 30 CHICAGO82 CLARK 10 10 NEW YORK66 JONES 20 20 DALLAS

14 rows selected.

Page 113: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Qualifying Ambiguous Column NamesQualifying Ambiguous Column Names

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

– Use table prefixes to improve performance.

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

– Use table prefixes to improve performance.

Page 114: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Additional Search ConditionsUsing the AND Operator Additional Search ConditionsUsing the AND Operator

EMP EMP DEPT DEPT EMPNO ENAME DEPTNO

------ ------- -------7839 KING 107698 BLAKE 307782 CLARK 107566 JONES 207654 MARTIN 307499 ALLEN 307844 TURNER 307900 JAMES 30

...14 rows selected.

DEPTNO D------

10 A3010 A20 R30 SA30 SA30 SA30 SA

...14 rows se

NAME LOC --------- --------CCOUNTING NEW YORK

SALES CHICAGOCCOUNTING NEW YORK ESEARCH DALLASLES CHICAGOLES CHICAGOLES CHICAGOLES CHICAGO

lected.

WHEREWHERE empemp..deptnodeptno=dept.=dept.deptnodeptno ANDAND enameename=='KINGKING'

Page 115: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Additional Search Conditions with a Join Using Additional Search Conditions with a Join

SQL> SELECT emp.empno, emp.ename, emp.deptno, dept.loc2 FROM emp, dept;3 WHERE emp.deptno = dept.deptno4 AND emp.ename = 'KING';

EMPNO ENAME DEPTNO LOC--------- ---------- --------- -------------

7839 KING 10 NEW YORK

Page 116: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Additional Search Conditions with a JoinUsing Additional Search Conditions with a Join

SQL> SELECT emp.ename, emp.job, dept.deptno, dept.dname2 FROM emp, dept3 WHERE emp.deptno=dept.deptno4 AND emp.job IN ('MANAGER','PRESIDENT');

ENAME JOB DEPTNO DNAME---------- --------- --------- --------------KING PRESIDENT 10 ACCOUNTINGBLAKE MANAGER 30 SALESCLARK MANAGER 10 ACCOUNTINGJONES MANAGER 20 RESEARCH

Page 117: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Table AliasesTable Aliases

Simplify queries by using table aliases.

… can be written as ...

Simplify queries by using table aliases.

… can be written as ...

SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc3 FROM emp, dept4 WHERE emp.deptno=dept.deptno;

SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc3 FROM emp e, dept d4 WHERE e.deptno=d.deptno;

Page 118: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Table AliasesUsing Table Aliases

SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc3 FROM emp e, dept d4 WHERE e.deptno=d.deptno;

EMPNO ENAME DEPTNO DEPTNO LOC--------- ---------- --------- --------- -----------

7839 KING 10 10 NEW YORK7698 BLAKE 30 30 CHICAGO7782 CLARK 10 10 NEW YORK7566 JONES 20 20 DALLAS7654 MARTIN 30 30 CHICAGO7499 ALLEN 30 30 CHICAGO

...

14 rows selected.

Page 119: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

NonequijoinsNonequijoins

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

EMPNO ENAME SAL------ ------- ------7839 KING 50007698 BLAKE 28507782 CLARK 24507566 JONES 29757654 MARTIN 12507499 ALLEN 16007844 TURNER 15007900 JAMES 950

...14 rows selected.

GRADE LOSAL HISAL----- ----- ------1 700 12002 1201 14003 1401 20004 2001 30005 3001 9999

EMPEMP SALGRADESALGRADE

Page 120: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Retrieving Records with NonequijoinsRetrieving Records with Nonequijoins

ME SAL GRADE------- --------- ---------ES 950 1TH 800 1MS 1100 1

14 rows selected.

SQL> SELECT e.ename, e.sal, s.grade2 FROM emp e, salgrade s3 WHERE e.sal4 BETWEEN s.losal AND s.hisal;

ENA---JAMSMIADA...

Page 121: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Joining More Than Two TablesJoining More Than Two Tables

SALGRADESALGRADE

WHEREWHERE empemp..salsal BETWEENBETWEENsalgradesalgrade..losallosal ANDANDsalgradesalgrade..hisal hisal ANDAND empemp..deptnodeptno = dept.= dept.deptnodeptno

DEPTNO DNAME--------- ----------

10 ACCOUNTING20 RESEARCH30 SALES40 OPERATIONS

LOSAL HISAL GRADE--------- --------- ---------

700 1200 11201 1400 21401 2000 32001 3000 43001 9999 5

ME SAL DEPTNO------- --------- ---------ES 950 30TH 800 20MS 1100 20TIN 1250 30D 1250 30LER 1300 10

14 rows selected.

EMPEMP DEPTDEPTENA---JAMSMIADAMARWARMIL…

Page 122: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Multiple JoinsUsing Multiple Joins

SQL> SELECT e.ename, e.deptno, d.dname, e.sal, s.grade2 FROM emp e, dept d, salgrade s3 WHERE e.deptno=d.deptno4 AND e.sal BETWEEN s.losal and s.hisal;

ENAME DEPTNO DNAME SAL GRADE---------- --------- -------------- --------- ---------JAMES 30 SALES 950 1SMITH 20 RESEARCH 800 1ADAMS 20 RESEARCH 1100 1MARTIN 30 SALES 1250 2WARD 30 SALES 1250 2MILLER 10 ACCOUNTING 1300 2ALLEN 30 SALES 1600 3...14 rows selected.

Page 123: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

SelfjoinsSelfjoins

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

NO ENAME MGR-- ------ ----39 KING98 BLAKE 783982 CLARK 783966 JONES 783954 MARTIN 7698

7499 ALLEN 7698

EMPNO ENAME----- --------

7839 KING7839 KING7839 KING7698 BLAKE7698 BLAKE

EMP (WORKER)EMP (WORKER) EMP (MANAGER)EMP (MANAGER)EMP---7876777576

Page 124: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Joining a Table to Itself

SQL> SELECT worker.ename||' works for '||manager.ename2 AS WHO_WORKS_FOR_WHOM3 FROM emp worker, emp manager4 WHERE worker.mgr = manager.empno;

Joining a Table to Itself

WHO_WORKS_FOR_WHOM-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGMARTIN works for BLAKE...13 rows selected.

Page 125: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Aggregating Data by Using Group FunctionsAggregating Data by Using Group Functions

Page 126: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

What Are Group Functions?What Are Group Functions?Group functions operate on sets of rows to give one result per group.Group functions operate on sets of rows to give one result per group.

EMPEMP

maximum maximum salary in salary in

the EMP tablethe EMP table

DEPTNO SAL--------- ---------

10 245010 500010 130020 80020 110020 300020 300020 297530 160030 285030 125030 95030 150030 1250

MAX(SAL)

---------

5000

Page 127: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Types of Group FunctionsTypes of Group Functions

– AVG – COUNT – MAX – MIN – SUM

– AVG – COUNT – MAX – MIN – SUM

Page 128: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Guidelines for Using Group FunctionsGuidelines for Using Group Functions

Many aggregate functions accept theseoptions: – DISTINCT– ALL– NVL

Many aggregate functions accept theseoptions: – DISTINCT– ALL– NVL

Page 129: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the AVG and SUM FunctionsUsing 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 AVG(sal), SUM(sal)2 FROM emp3 WHERE job LIKE 'SALES%';

AVG(SAL) SUM(SAL)-------- ---------

1400 5600

Page 130: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the MIN and MAX FunctionsUsing 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 TO_CHAR(MIN(hiredate),'DD-MON-YYYY'),2 TO_CHAR(MAX(hiredate),'DD-MON-YYYY')3 FROM emp;

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

Page 131: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the MIN and MAX Functions 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

Page 132: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the COUNT FunctionUsing the COUNT Function

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

SQL> SELECT COUNT(*)2 FROM emp3 WHERE deptno = 30;

COUNT(*)---------

6

Page 133: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the COUNT FunctionUsing the COUNT Function

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

SQL> SELECT COUNT(comm)2 FROM emp3 WHERE deptno = 30;

COUNT(COMM)-----------

4

Page 134: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Group Functions and Null ValuesGroup Functions and Null Values

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

> SELECT AVG(comm)2 FROM emp;

SQL

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

550

Page 135: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the NVL Function with Group FunctionsUsing the NVL Function with Group Functions

The NVL function forces group functions to include null values.The NVL function forces group functions to include null values.

> SELECT AVG(NVL(comm,0))2 FROM emp;

SQL

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

157.14286

Page 136: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the NVL Function with Group FunctionsUsing the NVL Function with Group Functions

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

SQL> SELECT AVG(NVL(comm,0))2 FROM emp3 WHERE hiredate 4 BETWEEN TO_DATE('01-JAN-1981','DD-MON-YYYY')5 AND TO_DATE('31-DEC-1981','DD-MON-YYYY');

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

220

Page 137: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Creating Groups of Data Creating Groups of Data

averageaveragesalary salary in EMPin EMPtable table

for each for each departmentdepartment

2916.6667

2175

1566.6667

DEPTNO SAL--------- ---------

10 245010 500010 130020 80020 110020 300020 300020 297530 160030 285030 125030 95030 150030 1250

DEPTNO AVG(SAL)

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

10 2916.6667

20 2175

30 1566.6667

EMPEMP

Page 138: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Creating Groups of Data: GROUP BY ClauseCreating Groups of Data: GROUP BY Clause

Use the GROUP BY clause to divide rows in a table into smaller groups.Use the GROUP BY clause to divide rows in a table into smaller groups.

SELECT column, group_functionM tableERE condition]

[GROUP BY group_by_expression][ORDER BY column];

FRO[WH

Page 139: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the GROUP BY Clause Using the GROUP BY Clause

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

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

DEPTNO AVG(SAL)--------- ---------

10 2916.666720 217530 1566.6667

Page 140: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the GROUP BY Clause Using the GROUP BY Clause

The GROUP BY column does not have to be in the SELECT list. The GROUP BY column does not have to be in the SELECT list.

SQL> SELECT AVG(sal)2 FROM emp3 GROUP BY deptno;

AVG(SAL)---------2916.6667

21751566.6667

Page 141: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the GROUP BY ClauseUsing 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 emp3 GROUP BY deptno;

DEPTNO Dept Employees--------- --------------

10 320 530 6

Page 142: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using a Group Function in the ORDER BY Clause Using a Group Function in the ORDER BY Clause

SQL> SELECT deptno, AVG(sal)2 FROM emp3 GROUP BY deptno4 ORDER BY AVG(sal);

DEPTNO AVG(SAL)---------- ------------

30 1566.6667 20 217510 2916.6667

Page 143: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Illegal Queries Using Group FunctionsIllegal Queries Using Group Functions

Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause. ause

Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.

SQL> SELECT deptno, COUNT(ename)2 FROM emp;

SQL> SELECT deptno, COUNT(ename)2 FROM emp;

e GROUP

e GROUP

e GROUP BY cl

SELECT deptno, COUNT(ename)*

ERROR at line 1:ORA-00937: not a single-group group function

SELECT deptno, COUNT(ename)*

ERROR at line 1:ORA-00937: not a single-group group function

Column missin

u

g in th

Col mn missing in th

BY clause

Column missing in th

BY clause

Page 144: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Set OperatorsUsing Set Operators

Page 145: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The Set OperatorsThe Set Operators

UnionUnion / Union All/ Union All

IntersectIntersect

AA BB

MinusMinus

AA BB AA BB

AA BB

Page 146: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Tables Used in This LessonTables Used in This LessonEMPNO ENAME JOB MGR HIREDATE SAL COMM

DEPTNO--------- ---------- --------- --------- --------- --------- --------- ---------

7839 KING PRESIDENT 17-NOV-81 5000 10

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7782 CLARK MANAGER 7839 09-JUN-81 1500 10

7566 JONES MANAGER 7839 02-APR-81 2975 20

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

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

7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30

7900 7698 03-DEC-81 950 30

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

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7369 SMITH CLERK 7902 17-DEC-80 800 20

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO--------- ---------- --------- --------- --------- --------- --------- ---------

7839 KING PRESIDENT 17-NOV-81 5000 10

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7782 CLARK MANAGER 7839 09-JUN-81 1500 10

7566 JONES MANAGER 7839 02-APR-81 2975 20

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

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

7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30

7900 7698 03-DEC-81 950 30

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

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7369 SMITH CLERK 7902 17-DEC-80 800 20

EMPEMP

EMPID NAME TITLE DATE_OUT DEPTID--------- -------------------- --------- --------- ---------

6087 SPENCER OPERATOR 27-NOV-81 20

6185 VANDYKE MANAGER 17-JAN-81 10

6235 BALFORD CLERK 22-FEB-80 20

7788 SCOTT ANALYST 05-MAY-81 20

7001 JEWELL ANALYST 10-JUN-81 30

7499 ALLEN SALESMAN 01-AUG-80

EMPID NAME TITLE DATE_OUT DEPTID--------- -------------------- --------- --------- ---------

6087 SPENCER OPERATOR 27-NOV-81 20

6185 VANDYKE MANAGER 17-JAN-81 10

6235 BALFORD CLERK 22-FEB-80 20

7788 SCOTT ANALYST 05-MAY-81 20

7001 JEWELL ANALYST 10-JUN-81 30

7499 ALLEN SALESMAN 01-AUG-80

JAMES CLERK EMP_HISTORYJAMES CLERK EMP_HISTORY

Page 147: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

UNIONUNION

AA BB

Page 148: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the UNION OperatorUsing the UNION OperatorDisplay the name, employee number, and job title of all employees. Display each employee only once.Display the name, employee number, and job title of all employees. Display each employee only once.

SQL> SELECT ename, empno, job2 FROM emp3 UNION4 SELECT name, empid, title5 FROM emp_history;

ENAME EMPNO JOB---------- --------- ---------ADAMS 7876 CLERKALLEN 7499 SALESMANBALFORD 6235 CLERK...20 rows selected.

Page 149: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the UNION OperatorUsing the UNION OperatorDisplay the name, job title, and salary of all employees.Display the name, job title, and salary of all employees.

ENAME JOB SAL---------- --------- ---------ADAMS CLERK 1100ALLEN SALESMAN 0ALLEN SALESMAN 1600BALFORD CLERK 0...23 rows selected.

SQL> SELECT ename, job, sal2 FROM emp3 UNION4 SELECT name, title, 05 FROM emp_history;

Page 150: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

UNION ALLUNION ALL

AA BB

Page 151: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the UNION ALL OperatorUsing the UNION ALL OperatorDisplay the names, employee numbers, and job titles of all employees. Display the names, employee numbers, and job titles of all employees.

SQL> SELECT ename, empno, job2 FROM emp3 UNION ALL4 SELECT name, empid, title5 FROM emp_history;

ENAME EMPNO JOB---------- --------- ---------KING 7839 PRESIDENTBLAKE 7698 MANAGERCLARK 7782 MANAGERCLARK 7782 MANAGER...23 rows selected.

Page 152: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

INTERSECTINTERSECT

AA BB

Page 153: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using the INTERSECT OperatorUsing the INTERSECT Operator

Display the distinct names, employee numbers, and job titles of employees found in both the EMP and EMP_HISTORY tables.

Display the distinct names, employee numbers, and job titles of employees found in both the EMP and EMP_HISTORY tables.

SQL> SELECT ename, empno, job2 FROM emp3 INTERSECT4 SELECT name, empid, title5 FROM emp_history;

ENAME EMPNO JOB---------- --------- ---------ALLEN 7499 SALESMANCLARK 7782 MANAGERSCOTT 7788 ANALYST

ENAME EMPNO JOB---------- --------- ---------ALLEN 7499 SALESMANCLARK 7782 MANAGERSCOTT 7788 ANALYST

Page 154: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

MINUSMINUS

AA BB

Page 155: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

MINUSMINUS

Display the names, employee numbers, and job titles for all employees who have left the company.

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> SELECT name, empid, title2 FROM emp_history3 MINUS4 SELECT ename, empno, job5 FROM emp;

NAME EMPID TITLE---------- --------- ---------BALFORD 6235 CLERKBRIGGS 7225 PAY CLERK...6 rows selected.

NAME EMPID TITLE---------- --------- ---------BALFORD 6235 CLERKBRIGGS 7225 PAY CLERK...6 rows selected.

Page 156: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

SET Operator RulesSET Operator Rules– The expressions in the SELECT lists must match in

number and datatype.– Duplicate rows are automatically eliminated except in

UNION ALL.– Column names from the first query appear in the result.– The output is sorted in ascending order by default

except in UNION ALL.– Parentheses can be used to alter the sequence of

execution.

– The expressions in the SELECT lists must match in number and datatype.

– Duplicate rows are automatically eliminated except in UNION ALL.

– Column names from the first query appear in the result.– The output is sorted in ascending order by default

except in UNION ALL.– Parentheses can be used to alter the sequence of

execution.

Page 157: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Matching the SELECTStatementMatching the SELECTStatement

Display the department numbers, locations, and hiredates for all employees.Display the department numbers, Display the department numbers, locations, andlocations, and hiredateshiredates for all employees.for all employees.

SQL> SELECT deptno, null location, hiredate2 FROM emp3 UNION4 SELECT deptno, loc, TO_DATE(null)5 FROM dept;

Page 158: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Controlling the Order of RowsControlling the Order of RowsProduce an English sentence using two UNION operators.Produce an English sentence using two Produce an English sentence using two UNION operators.UNION operators.

My dream-------------------------I'd like to teachthe world tosing

My dream-------------------------I'd like to teachthe world tosing

SQL> COLUMN a_dummy NOPRINTSQL> SELECT 'sing' "My dream", 3 a_dummy2 FROM dual3 UNION4 SELECT 'I''d like to teach', 15 FROM dual6 UNION7 SELECT 'the world to', 28 FROM dual9 ORDER BY 2;

SQL> COLUMN a_dummy NOPRINTSQL> SELECT 'sing' "My dream", 3 a_dummy2 FROM dual3 UNION4 SELECT 'I''d like to teach', 15 FROM dual6 UNION7 SELECT 'the world to', 28 FROM dual9 ORDER BY 2;

Page 159: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Writing SubqueriesWriting Subqueries

Page 160: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using a Subquery to Solve a ProblemUsing a Subquery to Solve a Problem

Who has a salary greater than Jones’s?Who has a salary greater than Jones’s?

Which employees have a salary greater than Jones’s salary?

Main Query

What is Jones’s salary?

Subquery

??

??

Page 161: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

SubqueriesSubqueries

SELECT select_listFROM tableWHERE expr operator

(SELECT select_listFROM table);

– The subquery (inner query) executes once before the main query.

– The result of the subquery is used by the main query (outer query).

– The subquery (inner query) executes once before the main query.

– The result of the subquery is used by the main query (outer query).

Page 162: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using a SubqueryUsing a Subquery

““Who has a salary greater than JonesWho has a salary greater than Jones’’??””

SQL> SELECT ename2 FROM emp3 WHERE sal >4 (SELECT sal5 FROM emp6 WHERE ename='JONES');

2975

ENAME----------KINGFORDSCOTT

Page 163: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Guidelines for Using SubqueriesGuidelines for Using Subqueries

– Enclose subqueries in parentheses. – Place subqueries on the right side of the comparison

operator.– Do not add an ORDER BY clause to a subquery.– Use single-row operators with single-row subqueries.

– Enclose subqueries in parentheses. – Place subqueries on the right side of the comparison

operator.– Do not add an ORDER BY clause to a subquery.– Use single-row operators with single-row subqueries.

Page 164: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Types of SubqueriesTypes of Subqueries

– Single-row subquery

– Multiple-row subquery

– Single-row subquery

– Multiple-row subquery

Main query

Subqueryreturnsreturns

CLERKCLERK

CLERKCLERKMANAGERMANAGER

Main query

Subqueryreturnsreturns

Page 165: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Single-Row SubqueriesSingle-Row Subqueries

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

Operator

=

>

>=

<

<=

<>

Meaning

Equal to

Greater than

Greater than or equal to

Less than

Less than or equal to

Not equal to

Page 166: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Executing Single-Row SubqueriesExecuting Single-Row Subqueries

Who works in the same department as King?Who works in the same department as King?SQL> SELECT ename, deptno2 FROM emp3 WHERE deptno = 4 (SELECT deptno5 FROM emp6 WHERE ename='KING');

10

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

Page 167: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Executing Single-Row SubqueriesExecuting Single-Row Subqueries

Who has the same manager as Blake?Who has the same manager as Blake?SQL> SELECT ename, mgr2 FROM emp3 WHERE mgr = 4 (SELECT mgr5 FROM emp6 WHERE ename='BLAKE');

7839

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

Page 168: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Executing Single-Row SubqueriesExecuting Single-Row SubqueriesWho has the same job as employee 7369 Who has the same job as employee 7369 andand

earns a higher salary than employee 7876?earns a higher salary than employee 7876?

CLERK

1100

SQL> SELECT ename, job2 FROM emp3 WHERE job = 4 (SELECT job5 FROM emp6 WHERE empno = 7369)7 AND sal > 8 (SELECT sal9 FROM emp10 WHERE empno = 7876);

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

Page 169: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Group Functions in a SubqueryUsing Group Functions in a Subquery

Display all employees who earn the minimum salary.Display all employees who earn the minimum salary.

800SQL> SELECT ename, job, sal2 FROM emp3 WHERE sal = 4 (SELECT MIN(sal)5 FROM emp);

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

Page 170: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

What Is Wrong with This Statement?What Is Wrong with This Statement?

SQL> SELECT empno, ename2 FROM emp3 WHERE sal = 4 (SELECT MIN(sal)5 FROM emp6 GROUP BY deptno);

ith m

ultiple

ith m

ultiple--ro

wrowsu

bqsu

bqueryuery

ERROR:ORA-01427: single-row subquery returns more thanone row

no rows selected

ra

SingleSingle--ro

w opetor w

row operator w

Page 171: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Will This Statement Work?Will This Statement Work?

SQL> SELECT ename, job2 FROM emp3 WHERE job = 4 (SELECT job5 FROM emp6 WHERE ename='SMYTHE');

no values

no values

no rows selected return

return

Subquery

Subquery

s s

Page 172: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Multiple-Row SubqueriesMultiple-Row Subqueries

– Return more than one row– Use the IN multiple-row comparison operator to

compare an expression to any member in the list that asubquery returns

– Return more than one row– Use the IN multiple-row comparison operator to

compare an expression to any member in the list that asubquery returns

Page 173: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Group Functions in a Multiple-Row SubqueryUsing Group Functions in a Multiple-Row Subquery

Display all employees who earn the same salary as Display all employees who earn the same salary as the minimum salary for each department.the minimum salary for each department.

SQL> SELECT ename, sal, deptno2 FROM emp3 WHERE sal 4 (SELECT MIN(sal)5 FROM emp6 GROUP BY deptno);

800, 950, 1300IN

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

Page 174: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Group Functions in a Multiple-Row SubqueryUsing Group Functions in a Multiple-Row Subquery

SQL> SELECT ename, sal, deptno,2 TO_CHAR(hiredate,'DD-MON-YYYY')HIREDATE3 FROM emp4 WHERE hiredate5 (SELECT MIN(hiredate)6 FROM emp7 GROUP BY deptno);

IN

Display the employees who were hired on the same Display the employees who were hired on the same date as the longest serving employee in any date as the longest serving employee in any department.department.

ENAME SAL DEPTNO HIREDATE---------- --------- --------- -----------SMITH 800 20 17-DEC-1980ALLEN 1600 30 20-FEB-1981CLARK 2450 10 09-JUN-1981

Page 175: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Controlling TransactionsControlling Transactions

Page 176: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Data Manipulation LanguageData Manipulation Language

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

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

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

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

Page 177: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Database TransactionsDatabase Transactions

Database transactions can consist of:– DML statements that make up one consistent change to the

dataExample: UPDATE

– One DDL statementExample: CREATE

– One DCL statementExample: GRANT and REVOKE

Database transactions can consist of:– DML statements that make up one consistent change to the

dataExample: UPDATE

– One DDL statementExample: CREATE

– One DCL statementExample: GRANT and REVOKE

Page 178: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Database TransactionsDatabase Transactions

– Begin when the first executable SQL statement is executed

– End with one of the following events:COMMIT or ROLLBACKDDL or DCL statement executes (automatic commit)User exitsSystem crashes

– Begin when the first executable SQL statement is executed

– End with one of the following events:COMMIT or ROLLBACKDDL or DCL statement executes (automatic commit)User exitsSystem crashes

Page 179: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Advantages of COMMIT and ROLLBACKAdvantages of COMMIT and ROLLBACK

– COMMIT and ROLLBACK ensure data consistency.– Users can preview data changes before making

changes permanent.– Users can group logically related operations.

– COMMIT and ROLLBACK ensure data consistency.– Users can preview data changes before making

changes permanent.– Users can group logically related operations.

Page 180: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Controlling TransactionsControlling Transactions

DELETEDELETE

SavepointSavepoint AA

ROLLBACK toROLLBACK to SavepointSavepoint BB

DELETEDELETE

SavepointSavepoint BBCOMMITCOMMIT

INSERTINSERTUPDATEUPDATE

ROLLBACK toROLLBACK to SavepointSavepoint AA

INSERTINSERTUPDATEUPDATEINSERTINSERT

ROLLBACKROLLBACK

INSERTINSERT

TransactionTransaction

Page 181: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Implicit Transaction ProcessingImplicit Transaction Processing– An automatic commit occurs under the following

circumstances:A DDL statement is issued, such as CREATEA DCL statement is issued, such as GRANTA normal exit from SQL*Plus occurs without an explicitly issued COMMIT or ROLLBACK statement

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

– An automatic commit occurs under the following circumstances:

A DDL statement is issued, such as CREATEA DCL statement is issued, such as GRANTA normal exit from SQL*Plus occurs without an explicitly issued COMMIT or ROLLBACK statement

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

Page 182: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

State of the Data Before COMMIT or ROLLBACKState of the Data Before COMMIT or ROLLBACK

– The previous state of the data can be recovered.– The current user can review the results of the DML operations

by using the SELECT statement.– Other users cannot view the results of the DML statements by

the current user.– The affected rows are locked; other users cannot change the

data within the affected rows.

– The previous state of the data can be recovered.– The current user can review the results of the DML operations

by using the SELECT statement.– Other users cannot view the results of the DML statements by

the current user.– The affected rows are locked; other users cannot change the

data within the affected rows.

Page 183: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Committing DataCommitting Data

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

– Make the changes.

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

– Make the changes.

SQL> UPDATE emp2 SET deptno = 103 WHERE empno = 7782;

1 row updated.

SQL> UPDATE emp2 SET deptno = 103 WHERE empno = 7782;

1 row updated.1 row updated.

SQL> COMMIT;Commit complete.Commit complete.

• Commit the changes.• Commit the changes.

Page 184: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

State of the Data After COMMITState of the Data After COMMIT

• Data changes are made permanent in the database.

• The previous state of the data is permanently lost.

• All users can view the results.• Locks on the affected rows are released;

those rows are available for other users to manipulate.

• All savepoints are erased.

• Data changes are made permanent in the database.

• The previous state of the data is permanently lost.

• All users can view the results.• Locks on the affected rows are released;

those rows are available for other users to manipulate.

• All savepoints are erased.

Page 185: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

State of the Data After ROLLBACKState of the Data After ROLLBACK

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

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

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

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

SQL> DELETE FROM employee;14 rows deleted.14 rows deleted.SQL> ROLLBACK;Rollback complete.Rollback complete.

Page 186: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Rolling Back Changes to a MarkerRolling Back Changes to a Marker

– Create a marker within a current transaction by using the SAVEPOINT statement.

– Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.

– Create a marker within a current transaction by using the SAVEPOINT statement.

– Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement.

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

Page 187: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Statement-Level RollbackStatement-Level Rollback

– If a single DML statement fails during execution, only that statement is rolled back.

– Oracle implements an implicit savepoint.– All other changes are retained.– The user should terminate transactions explicitly by

executing a COMMIT or ROLLBACK statement.

– If a single DML statement fails during execution, only that statement is rolled back.

– Oracle implements an implicit savepoint.– All other changes are retained.– The user should terminate transactions explicitly by

executing a COMMIT or ROLLBACK statement.

Page 188: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Read ConsistencyRead Consistency

– Read consistency guarantees a consistent view of the data at all times.

– Changes made by one user do not conflict with changes made by another user.

– Read consistency ensures that on the same data:Readers do not wait for writers or other readersWriters do not wait for readers

– Read consistency guarantees a consistent view of the data at all times.

– Changes made by one user do not conflict with changes made by another user.

– Read consistency ensures that on the same data:Readers do not wait for writers or other readersWriters do not wait for readers

Page 189: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Implementation of Read ConsistencyImplementation of Read Consistency

ChangedChangedand and unchanged unchanged datadata

Before Before changechange““oldold”” datadata

ReadReadconsistentconsistentimageimage

UPDATEUPDATE empempSETSET salsal = 2000= 2000

WHEREWHERE enameename = 'SCOTT';= 'SCOTT';

DataDatablocksblocks

RollbackRollbacksegmentssegments

User AUser A

SELECT *SELECT *FROMFROM empemp;;

User BUser B

Page 190: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

LockingLocking

The Oracle Server locks:– Prevent destructive interaction between concurrent

transactions– Require no user action– Automatically use the lowest level of restrictiveness– Are held for the duration of the transaction– Have two basic modes:

ExclusiveShare

The Oracle Server locks:– Prevent destructive interaction between concurrent

transactions– Require no user action– Automatically use the lowest level of restrictiveness– Are held for the duration of the transaction– Have two basic modes:

ExclusiveShare

Page 191: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Locking ModesLocking Modes

Lock Mode Description

Exclusive lock 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.

Page 192: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Implicit LockingImplicit Locking

User Action Row-Level Lock Table-Level Lock

SELECT ... FROM table ... None None

INSERT INTO table ... X RX

UPDATE table ... X RX

DELETE FROM table ... X RX

DDL Operation None X

Page 193: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Explicit LockingExplicit LockingUser Action Row-Level lock Table-Level lock

SELECT FOR UPDATE X RS [NOWAIT]

LOCK TABLE IN option None Depends on the MODErestrictiveness used

Override the default lock mechanism:– For a consistent view of data when reading across

multiple tables– When a transaction may change data based on other

data that must not change until the whole transaction is complete

Override the default lock mechanism:– For a consistent view of data when reading across

multiple tables– When a transaction may change data based on other

data that must not change until the whole transaction is complete

Page 194: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Overview of PL/SQLOverview of PL/SQL

Page 195: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

About PL/SQLAbout PL/SQL

– PL/SQL is an extension to SQL with design features of programming languages.

– Data manipulation and query statements of SQL are included within procedural units of code.

– PL/SQL is an extension to SQL with design features of programming languages.

– Data manipulation and query statements of SQL are included within procedural units of code.

Page 196: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

PL/SQL EnvironmentPL/SQL Environment

PL/SQL engine

ProceduralStatementExecutor

PL/SQL

SQLPL/SQLblock

PL/SQLblock

Oracle Server

SQL Statement Executor

Page 197: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQL

IntegrationIntegration

ApplicationApplication

SharedSharedlibrary

Oracle ServerOracle Serverlibrary

Page 198: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQL

SQL

SQLApplicationApplication Other DBMSs

Improve PerformanceImprove Performance

Other DBMSs

SQLSQLSQL

SQL

ApplicationApplication Oracle with PL/SQL

SQLSQL

Oracle with PL/SQL

SQLSQLIF...THENIF...THEN

SQLSQLELSEELSE

SQLSQLEND IF;END IF;SQLSQL

Page 199: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQLModularize program developmentModularize program development

DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

Page 200: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQL

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

Page 201: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Benefits of PL/SQLBenefits of PL/SQL

– You can program with procedural language control structures.

– It can handle errors.

– You can program with procedural language control structures.

– It can handle errors.

Page 202: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Declaring VariablesDeclaring Variables

Page 203: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

PL/SQL Block StructurePL/SQL Block Structure

• DECLARE – Optional– Variables, cursors, user-defined exceptions

• BEGIN – Mandatory– SQL statements– PL/SQL statements

• EXCEPTION – Optional– Actions to perform when

errors occur• END; – Mandatory DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

• DECLARE – Optional– Variables, cursors, user-defined exceptions

• BEGIN – Mandatory– SQL statements– PL/SQL statements

• EXCEPTION – Optional– Actions to perform when

errors occur• END; – Mandatory

Page 204: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

PL/SQL Block StructurePL/SQL Block Structure

DECLAREv_variable VARCHAR2(5);

BEGINSELECT column_nameINTO v_variableFROM table_name;

EXCEPTIONWHEN exception_name THEN...

END;

DECLAREv_variable VARCHAR2(5);

BEGINSELECT column_nameINTO v_variableFROM table_name;

EXCEPTIONWHEN exception_name THEN...

END;

DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

Page 205: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Block TypesBlock Types

Anonymous Procedure Function

[DECLARE]

BEGIN--statements

[EXCEPTION]

END;

[[DECLARE]DECLARE]

BEGINBEGIN----statementsstatements

[EXCEPTION][EXCEPTION]

END;END;

PROCEDURE nameIS

BEGIN--statements

[EXCEPTION]

END;

PROCEDURE namePROCEDURE nameISIS

BEGINBEGIN----statementsstatements

[EXCEPTION][EXCEPTION]

END;END;

FUNCTION nameRETURN datatypeISBEGIN--statementsRETURN value;

[EXCEPTION]

END;

FUNCTION nameFUNCTION nameRETURNRETURN datatypedatatypeISISBEGINBEGIN

----statementsstatementsRETURN value;RETURN value;

[EXCEPTION][EXCEPTION]

END;END;

Page 206: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Program ConstructsProgram Constructs

Anonymousblock

DECLAREDECLARE

BEGINBEGIN

EXCEPTIONEXCEPTION

END;END;

AnonymousAnonymousblockblock

Stored procedure/

function

Stored Stored procedure/procedure/

functionfunction

Applicationtrigger

ApplicationApplicationtriggertrigger

Applicationprocedure/

function

ApplicationApplicationprocedure/procedure/

functionfunction

Databasetrigger

DatabaseDatabasetriggertrigger

Packagedprocedure/

function

PackagedPackagedprocedure/procedure/

functionfunction

Page 207: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Use of VariablesUse of Variables

Use variables for:– Temporary storage of data– Manipulation of stored values– Reusability– Ease of maintenance

Use variables for:– Temporary storage of data– Manipulation of stored values– Reusability– Ease of maintenance

Page 208: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Handling Variables in PL/SQLHandling Variables in PL/SQL

– Declare and initialize variables in the declaration section.

– Assign new values to variables in the executable section.

– Pass values into PL/SQL blocks through parameters.– View results through output variables.

– Declare and initialize variables in the declaration section.

– Assign new values to variables in the executable section.

– Pass values into PL/SQL blocks through parameters.– View results through output variables.

Page 209: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Types of VariablesTypes of Variables

– PL/SQL variables:ScalarCompositeReferenceLOB (large objects)

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

– PL/SQL variables:ScalarCompositeReferenceLOB (large objects)

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

Page 210: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Types of VariablesTypes of Variables

– PL/SQL variables:ScalarCompositeReferenceLOB (large objects)

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

– PL/SQL variables:ScalarCompositeReferenceLOB (large objects)

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

Page 211: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

TRUETRUE25-OCT-9925-OCT-99

AtlantaAtlanta

“Four score and seven years agour fathers brought forth upon

this continent, a new nation,

conceived in LIBERTY, and dedi

to the proposition that all me

are created equal.”256120.08256120.08

Types of VariablesTypes of Variables

o

cated

n

Page 212: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Declaring PL/SQL VariablesDeclaring PL/SQL Variables

Syntax

Examples

SyntaxSyntax

ExamplesExamples

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

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

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

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

Page 213: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Declaring PL/SQL VariablesDeclaring PL/SQL Variables

Guidelines– Follow naming conventions.– Initialize variables designated as NOT NULL.– Initialize identifiers by using the assignment operator

(:=) or the DEFAULT reserved word.– Declare at most one identifier per line.

Guidelines– Follow naming conventions.– Initialize variables designated as NOT NULL.– Initialize identifiers by using the assignment operator

(:=) or the DEFAULT reserved word.– Declare at most one identifier per line.

Page 214: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Naming RulesNaming Rules

– Two variables can have the same name, provided they are in different blocks.

– The variable name (identifier) should not be the same as the name of table columns used in the block.

– Two variables can have the same name, provided they are in different blocks.

– The variable name (identifier) should not be the same as the name of table columns used in the block.

DECLAREempno NUMBER(4);

BEGINSELECT empnoINTO empnoFROM empWHERE ename = 'SMITH';

END;

DECLAREempno NUMBER(4);

BEGINSELECT empnoINTO empnoFROM empWHERE ename = 'SMITH';

END;

Adopt a nam identempning con

ifiers:vention for

PL/SQL

for example, v_o

Adopt a naming convention for

Adopt a naming convention for

PL/SQL identifiers:

PL/SQL identifiers:

for example, v_

for example, v_empnoempno

Page 215: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Assigning Values to VariablesAssigning Values to Variables

v_ename := 'Maduro';v_ename := 'Maduro';

v_hiredate := '31-DEC-98';v_hiredate := '31-DEC-98';

Syntax

Example• Set a predefined hiredate for new

employees.

identif

SyntaxSyntax

ExampleExample• Set a predefined hiredate for new

employees.

ier := expr;identifier := expr;

• Set the employee name to “Maduro.”• Set the employee name to “Maduro.”

Page 216: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Variable Initialization and KeywordsVariable Initialization and Keywords

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

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

Page 217: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Scalar DatatypesScalar Datatypes

• Hold a single value• Have no internal components• Hold a single value• Have no internal components

25-OCT-9925-OCT-99

AtlantaAtlanta

“Four score and seven yearsago our fathers brought

forth upon this continent, a

new nation, conceived in

LIBERTY, and dedicated to

the proposition that all men

are created equal.”

TRUETRUE

256120.08256120.08

Page 218: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Base Scalar DatatypesBase Scalar Datatypes

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

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

Page 219: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Base Scalar DatatypesBase Scalar Datatypes

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

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

Page 220: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Scalar Variable DeclarationsScalar Variable Declarations

ExampleExample

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

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

Page 221: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The %TYPE AttributeThe %TYPE Attribute

– Declare a variable according to: A database column definitionAnother previously declared variable

– Prefix %TYPE with:The database table and columnThe previously declared variable name

– Declare a variable according to: A database column definitionAnother previously declared variable

– Prefix %TYPE with:The database table and columnThe previously declared variable name

Page 222: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Declaring Variables with the %TYPE AttributeDeclaring Variables with the %TYPE Attribute

ExampleExample

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

...

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

...

Page 223: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Declaring Boolean VariablesDeclaring Boolean Variables

– Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable.

– The variables are connected by the logical operators AND, OR, and NOT.

– The variables always yield TRUE, FALSE, or NULL.– Arithmetic, character, and date expressions can be

used to return a Boolean value.

– Only the values TRUE, FALSE, and NULL can be assigned to a Boolean variable.

– The variables are connected by the logical operators AND, OR, and NOT.

– The variables always yield TRUE, FALSE, or NULL.– Arithmetic, character, and date expressions can be

used to return a Boolean value.

Page 224: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Composite DatatypesComposite Datatypes

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

Page 225: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

LOB Datatype VariablesLOB Datatype Variables

RecipeRecipe(CLOB)(CLOB)

PhotoPhoto(BLOB)(BLOB)

MovieMovie(BFILE)(BFILE)

NCLOBNCLOB

Page 226: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Bind VariablesBind Variables

Server

O/SO/SBind VariableBind Variable

Page 227: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Referencing Non-PL/SQL VariablesReferencing Non-PL/SQL Variables

Store the annual salary into a SQL*Plus host variable.

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

Store the annual salary into a SQL*Plus host variable.

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

:g_monthly_sal := v_sal / 12;:g_monthly_sal := v_sal / 12;

Page 228: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 229: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

DBMS_OUTPUT.PUT_LINEDBMS_OUTPUT.PUT_LINE

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

SET SERVEROUTPUT ON

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

SET SERVEROUTPUT ON

Page 230: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Writing Executable StatementsWriting Executable Statements

Page 231: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

PL/SQL Block Syntax and GuidelinesPL/SQL Block Syntax and Guidelines

– Statements can continue over several lines.– Lexical units can be separated by:

SpacesDelimitersIdentifiersLiteralsComments

– Statements can continue over several lines.– Lexical units can be separated by:

SpacesDelimitersIdentifiersLiteralsComments

Page 232: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

PL/SQL Block Syntax and GuidelinesPL/SQL Block Syntax and Guidelines

Identifiers– Can contain up to 30 characters– Cannot contain reserved words unless enclosed in

double quotation marks– Must begin with an alphabetic character– Should not have the same name as a database table

column name

Identifiers– Can contain up to 30 characters– Cannot contain reserved words unless enclosed in

double quotation marks– Must begin with an alphabetic character– Should not have the same name as a database table

column name

Page 233: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

PL/SQL Block Syntax and GuidelinesPL/SQL Block Syntax and Guidelines

Literals– Character and date literals must be enclosed in single

quotation marks.

– Numbers can be simple values or scientific notation.

Literals– Character and date literals must be enclosed in single

quotation marks.

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

Page 234: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Commenting CodeCommenting Code

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

*/.

Example

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

*/.

Example

...v_sal NUMBER (9,2);

BEGIN/* Compute the annual salary based on the

monthly salary input from the user */v_sal := &p_monthly_sal * 12;

END; -- This is the end of the transaction

...v_sal NUMBER (9,2);

BEGIN/* Compute the annual salary based on the

monthly salary input from the user */v_sal := &p_monthly_sal * 12;

END; -- This is the end of the transaction

Page 235: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

SQL Functions in PL/SQLSQL Functions in PL/SQL– Available:

Single-row number Single-row characterDatatype conversionDate

– Not available:DECODEGroup functions

– Available:Single-row number Single-row characterDatatype conversionDate

– Not available:DECODEGroup functions

Same as in SQL}}

Page 236: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

PL/SQL FunctionsPL/SQL Functions

Example– Build the mailing list for a company.

– Convert the employee name to lowercase.

Example– Build the mailing list for a company.

– Convert the employee name to lowercase.

v_mailing_address := v_name||CHR(10)||

v_address||CHR(10)||v_state||

CHR(10)||v_zip;

v_mailing_address := v_name||CHR(10)||

v_address||CHR(10)||v_state||

CHR(10)||v_zip;

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

Page 237: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Datatype ConversionDatatype Conversion

– Convert data to comparable datatypes.– Mixed datatypes can result in an error and affect

performance.– Conversion functions:

TO_CHARTO_DATETO_NUMBER

– Convert data to comparable datatypes.– Mixed datatypes can result in an error and affect

performance.– Conversion functions:

TO_CHARTO_DATETO_NUMBER DECLARE

v_date VARCHAR2(15);BEGIN

SELECT TO_CHAR(hiredate,

'MON. DD, YYYY')INTO v_dateFROM empWHERE empno = 7839;

END;

DECLAREv_date VARCHAR2(15);

BEGINSELECT TO_CHAR(hiredate,

'MON. DD, YYYY')INTO v_dateFROM empWHERE empno = 7839;

END;

Page 238: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Datatype ConversionDatatype Conversion

This statement produces a compilation error if the variable v_date is declared asdatatype DATE.

This statement produces a compilation This statement produces a compilation error if the variable v_date is declared aserror if the variable v_date is declared asdatatypedatatype DATE.DATE.v_date := 'January 13, 1998'; v_date := 'January 13, 1998';

v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY');

v_date := TO_DATE ('January 13, 1998', 'Month DD, YYYY');

To correct the error, use the TO_DATE conversion function.To correct the error, use the TO_DATE conversion function.

Page 239: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Nested Blocks and Variable ScopeNested Blocks and Variable Scope

– Statements can be nested wherever an executable statement is allowed.

– A nested block becomes a statement.– An exception section can contain nested blocks.– The scope of an object is the region of the program that

can refer to the object.

– Statements can be nested wherever an executable statement is allowed.

– A nested block becomes a statement.– An exception section can contain nested blocks.– The scope of an object is the region of the program that

can refer to the object.

Page 240: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Nested Blocks and Variable ScopeNested Blocks and Variable Scope

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

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

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

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

Page 241: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Nested Blocks and Variable ScopeNested Blocks and Variable Scope

ExampleExample...x BINARY_INTEGER;

BEGIN...DECLAREy NUMBER;

BEGIN...

END;...

END;

...x BINARY_INTEGER;

BEGIN...DECLAREy NUMBER;

BEGIN...

END;...

END;

Scope of x

Scope of y

Page 242: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Operators in PL/SQLOperators in PL/SQL

– Logical– Arithmetic– Concatenation – Parentheses to control order of

operations– Exponential operator (**)

– Logical– Arithmetic– Concatenation – Parentheses to control order of

operations– Exponential operator (**)

Same as in SQL

Page 243: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Operators in PL/SQLOperators in PL/SQL

Example– Increment the index for a loop.

– Set the value of a Boolean flag.

– Validate an employee number if it contains a value.

Example– Increment the index for a loop.

– Set the value of a Boolean flag.

– Validate an employee number if it contains a value.

v_count := v_count + 1;v_count := v_count + 1;

v_equal := (v_n1 = v_n2);v_equal := (v_n1 = v_n2);

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

Page 244: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Using Bind VariablesUsing Bind Variables

To reference a bind variable in PL/SQL, you must prefix its name with a colon (:).Example

To reference a bind variable in PL/SQL, you must prefix its name with a colon (:).Example

VARIABLE g_salary NUMBERDECLARE

v_sal emp.sal%TYPE;BEGIN

SELECT salINTO v_salFROM empWHERE empno = 7369;:g_salary := v_sal;

END;/

VARIABLE g_salary NUMBERDECLARE

v_sal emp.sal%TYPE;BEGIN

SELECT salINTO v_salFROM empWHERE empno = 7369;:g_salary := v_sal;

END;/

Page 245: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Programming GuidelinesProgramming Guidelines

Make code maintenance easier by:– Documenting code with comments– Developing a case convention for the code– Developing naming conventions for identifiers and

other objects– Enhancing readability by indenting

Make code maintenance easier by:– Documenting code with comments– Developing a case convention for the code– Developing naming conventions for identifiers and

other objects– Enhancing readability by indenting

Page 246: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Code Naming ConventionsCode Naming Conventions

Avoid ambiguity:– The names of local variables and formal parameters

take precedence over the names of database tables.– The names of columns take precedence over the

names of local variables.

Avoid ambiguity:– The names of local variables and formal parameters

take precedence over the names of database tables.– The names of columns take precedence over the

names of local variables.

Page 247: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Indenting CodeIndenting Code

For clarity, indent each level of code.ExampleFor clarity, indent each level of code.Example

BEGINIF x=0 THEN

y:=1;END IF;

END;

BEGINIF x=0 THEN

y:=1;END IF;

END;

DECLAREv_deptno NUMBER(2);v_location VARCHAR2(13);

BEGINSELECT deptno,

locINTO v_deptno,

v_locationFROM deptWHERE dname = 'SALES';

...END;

DECLAREv_deptno NUMBER(2);v_location VARCHAR2(13);

BEGINSELECT deptno,

locINTO v_deptno,

v_locationFROM deptWHERE dname = 'SALES';

...END;

Page 248: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Determining Variable ScopeDetermining Variable ScopeClass ExerciseClass Exercise

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

DECLAREV_SAL NUMBER(7,2) := 50000;V_COMM NUMBER(7,2) := 0;V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM;

BEGIN ...V_MESSAGE := 'CLERK not'||V_MESSAGE;

END;

V_MESSAGE := 'SALESMAN'||V_MESSAGE;END;

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

DECLAREV_SAL NUMBER(7,2) := 50000;V_COMM NUMBER(7,2) := 0;V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM;

BEGIN ...V_MESSAGE := 'CLERK not'||V_MESSAGE;

END;

V_MESSAGE := 'SALESMAN'||V_MESSAGE;END;

Page 249: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Writing Control StructuresWriting Control Structures

Page 250: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Controlling PL/SQL Flow of ExecutionControlling PL/SQL Flow of Execution

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

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

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

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

Page 251: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

IF StatementsIF Statements

IF condition THENstatements;

[ELSIF condition THEN statements;]

[ELSE statements;]

END IF;

IF condition THENstatements;

[ELSIF condition THEN statements;]

[ELSE statements;]

END IF;

Syntax

Simple IF statement:Set the manager ID to 22 if the employee name is Osborne.

SyntaxSyntax

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 = 'OSBORNE' THEN v_mgr := 22;

END IF;

IF v_ename = 'OSBORNE' THEN v_mgr := 22;

END IF;

Page 252: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Simple IF StatementsSimple IF Statements

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

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

. . .IF v_ename = 'MILLER' THENv_job := 'SALESMAN'; v_deptno := 35;v_new_comm := sal * 0.20;

END IF;. . .

. . .IF v_ename = 'MILLER' THENv_job := 'SALESMAN'; v_deptno := 35;v_new_comm := sal * 0.20;

END IF;. . .

Page 253: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

IF-THEN-ELSE Statement Execution FlowIF-THEN-ELSE Statement Execution Flow

IF conditionIF condition

THEN actions(including further IFs)

THEN actionsTHEN actions(including further(including further IFsIFs))

ELSE actions(including further IFs)

ELSE actionsELSE actions(including further(including further IFsIFs))

TRUETRUE FALSEFALSE

Page 254: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

IF-THEN-ELSE StatementsIF-THEN-ELSE Statements

Set a flag for orders where there are fewer than five days between order date and ship date.Example

Set a flag for orders where there are fewer than five days between order date and ship date.Example

...IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable';

ELSEv_ship_flag := 'Unacceptable';

END IF;...

...IF v_shipdate - v_orderdate < 5 THEN v_ship_flag := 'Acceptable';

ELSEv_ship_flag := 'Unacceptable';

END IF;...

Page 255: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

IF-THEN-ELSIF Statement Execution FlowIF-THEN-ELSIF Statement Execution Flow

IF conditionTRUETRUE

THEN actionsTHEN actionsTHEN actions

FALSEFALSE

ELSIFcondition

ELSIFELSIFconditioncondition

TRUETRUE

THEN actionsTHEN actionsTHEN actions

FALSEFALSE

ELSEactionsELSEELSE

actionsactions

IF conditionIF condition

Page 256: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

IF-THEN-ELSIF StatementsIF-THEN-ELSIF Statements

For a given value, calculate a percentage of that value based on a condition.Example

For a given value, calculate a percentage of that value based on a condition.Example

. . .IF v_start > 100 THENv_start := 2 * v_start;

ELSIF v_start >= 50 THEN v_start := .5 * v_start;

ELSEv_start := .1 * v_start;

END IF;. . .

. . .IF v_start > 100 THENv_start := 2 * v_start;

ELSIF v_start >= 50 THEN v_start := .5 * v_start;

ELSEv_start := .1 * v_start;

END IF;. . .

Page 257: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Building Logical ConditionsBuilding Logical Conditions

– You can handle null values with the IS NULL operator.– Any arithmetic expression containing a null value

evaluates to NULL.– Concatenated expressions with null values treat null

values as an empty string.

– You can handle null values with the IS NULL operator.– Any arithmetic expression containing a null value

evaluates to NULL.– Concatenated expressions with null values treat null

values as an empty string.

Page 258: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Logic TablesLogic Tables

Build a simple Boolean condition with a comparison operator.Build a simple Boolean condition with a comparison operator.

TRUE

FALSE

NULL

OR TRUE FALSE NULLAND

TRUE

FALSE

NULL

TRUE FALSE NULL

TRUE

NULL NULL

NULL

FALSE FALSE

FALSE

FALSE

FALSE

TRUE

TRUE

TRUE

TRUETRUE

FALSE

NULL NULL

NULL

NOT

TRUE

FALSE

NULL

FALSE

TRUE

NULL

Page 259: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Boolean ConditionsBoolean 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 V_AVAILABLE_FLAG V_FLAG

TRUE TRUE

TRUE FALSE

NULL TRUE

NULL FALSE

TRUETRUE

FALSEFALSE

NULLNULL

FALSEFALSE

Page 260: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Iterative Control: LOOP StatementsIterative Control: LOOP Statements

– Loops repeat a statement or sequence of statements multiple times.

– There are three loop types:Basic loopFOR loopWHILE loop

– Loops repeat a statement or sequence of statements multiple times.

– There are three loop types:Basic loopFOR loopWHILE loop

Page 261: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Basic LoopBasic Loop

SyntaxSyntax

LOOP statement1;. . .EXIT [WHEN condition];

END LOOP;

LOOP statement1;. . .EXIT [WHEN condition];

END LOOP;

---- delimiterdelimiter

---- statementsstatements

---- EXIT statementEXIT statement

---- delimiterdelimiter

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

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

Page 262: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Basic LoopBasic Loop

ExampleExample

DECLAREv_ordid item.ordid%TYPE := 601;v_counter NUMBER(2) := 1;

BEGINLOOPINSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter);

v_counter := v_counter + 1;EXIT WHEN v_counter > 10;

END LOOP;END;

DECLAREv_ordid item.ordid%TYPE := 601;v_counter NUMBER(2) := 1;

BEGINLOOPINSERT INTO item(ordid, itemid) VALUES(v_ordid, v_counter);

v_counter := v_counter + 1;EXIT WHEN v_counter > 10;

END LOOP;END;

Page 263: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

FOR LoopFOR Loop

Syntax

– Use a FOR loop to shortcut the test for the number of iterations.

– Do not declare the index; it is declared implicitly.

Syntax

– Use a FOR loop to shortcut the test for the number of iterations.

– Do not declare the index; it is declared implicitly.

FOR counter in [REVERSE] lower_bound..upper_bound LOOP

statement1;statement2;. . .

END LOOP;

FOR counter in [REVERSE] lower_bound..upper_bound LOOP

statement1;statement2;. . .

END LOOP;

Page 264: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

FOR LoopFOR Loop

Guidelines– Reference the counter within the loop only; it is undefined

outside the loop.– Use an expression to reference the existing value of a

counter.– Do not reference the counter as the target of an

assignment.

Guidelines– Reference the counter within the loop only; it is undefined

outside the loop.– Use an expression to reference the existing value of a

counter.– Do not reference the counter as the target of an

assignment.

Page 265: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

FOR LoopFOR Loop

Insert the first 10 new line items for order number 601.Example

Insert the first 10 new line items for order number 601.Example

DECLAREv_ordid item.ordid%TYPE := 601;

BEGINFOR i IN 1..10 LOOPINSERT INTO item(ordid, itemid) VALUES(v_ordid, i);

END LOOP;END;

DECLAREv_ordid item.ordid%TYPE := 601;

BEGINFOR i IN 1..10 LOOPINSERT INTO item(ordid, itemid) VALUES(v_ordid, i);

END LOOP;END;

Page 266: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

WHILE LoopWHILE Loop

Syntax

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

Syntax

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

WHILE condition LOOPstatement1;statement2;. . .

END LOOP;

WHILE condition LOOPstatement1;statement2;. . .

END LOOP;

Condition isCondition isevaluated at the evaluated at the beginning ofbeginning ofeach iteration.each iteration.

Page 267: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

WHILE LoopWHILE LoopExampleExample

ACCEPT p_new_order PROMPT 'Enter the order number: 'ACCEPT p_items -PROMPT 'Enter the number of items in this order: '

DECLAREv_count NUMBER(2) := 1;BEGINWHILE v_count <= &p_items LOOPINSERT INTO item (ordid, itemid)VALUES (&p_new_order, v_count);v_count := v_count + 1;

END LOOP;COMMIT;

END;/

ACCEPT p_new_order PROMPT 'Enter the order number: 'ACCEPT p_items -PROMPT 'Enter the number of items in this order: '

DECLAREv_count NUMBER(2) := 1;BEGINWHILE v_count <= &p_items LOOPINSERT INTO item (ordid, itemid)VALUES (&p_new_order, v_count);v_count := v_count + 1;

END LOOP;COMMIT;

END;/

Page 268: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Nested Loops and LabelsNested Loops and Labels

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

the label.

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

the label.

Page 269: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Nested Loops and LabelsNested Loops and Labels

...BEGIN<<Outer_loop>>LOOPv_counter := v_counter+1;

EXIT WHEN v_counter>10;<<Inner_loop>>LOOP...EXIT Outer_loop WHEN total_done = 'YES';-- Leave both loopsEXIT WHEN inner_done = 'YES';-- Leave inner loop only...

END LOOP Inner_loop;...

END LOOP Outer_loop;END;

...BEGIN<<Outer_loop>>LOOPv_counter := v_counter+1;

EXIT WHEN v_counter>10;<<Inner_loop>>LOOP...EXIT Outer_loop WHEN total_done = 'YES';-- Leave both loopsEXIT WHEN inner_done = 'YES';-- Leave inner loop only...

END LOOP Inner_loop;...

END LOOP Outer_loop;END;

Page 270: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Writing Explicit CursorsWriting Explicit Cursors

Page 271: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

About CursorsAbout Cursors

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

– Implicit cursors: Declared for all DML and PL/SQL SELECT statements

– Explicit cursors: Declared and named by the programmer

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

– Implicit cursors: Declared for all DML and PL/SQL SELECT statements

– Explicit cursors: Declared and named by the programmer

Page 272: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Explicit Cursor FunctionsExplicit Cursor FunctionsExplicit Cursor Functions

Active setActive set

7369 SMITH CLERK7566 JONES MANAGER7788 SCOTT ANALYST7876 ADAMS CLERK7902 FORD ANALYST

Cursor Current rowCurrent row

Page 273: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Controlling Explicit CursorsControlling Explicit CursorsControlling Explicit Cursors

•• Create a Create a named named SQL areaSQL area

•• Identify Identify the active the active setset

•• Load the Load the current current row into row into variablesvariables

•• Test for Test for existing existing rowsrows

•• Return to Return to FETCH if FETCH if rows rows foundfound

•• Release Release the active the active setset

DECLARE OPENOPENOPEN FETCHFETCHFETCH EMPTY? CLOSECLOSECLOSEYesYes

NoNo

DECLAREDECLARE

Page 274: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Controlling Explicit CursorsControlling Explicit CursorsControlling Explicit CursorsOpen the cursor.Open the cursor.

CursorCursor

PointerPointer

Fetch a row from the cursor.Fetch a row from the cursor.

CursorCursor

PointerPointer

Continue until empty.Continue until empty.

CursorCursor

PointerPointer

Close the cursor.Close the cursor.

CursorCursor

Page 275: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Declaring the CursorDeclaring the CursorDeclaring the Cursor

Syntax

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

ORDER BY clause in the query.

Syntax

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

ORDER BY clause in the query.

CURSOR cursor_name ISselect_statement;

CURSOR cursor_name ISselect_statement;

Page 276: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Declaring the CursorDeclaring the CursorDeclaring the Cursor

ExampleExample

DECLARECURSOR emp_cursor IS SELECT empno, enameFROM emp;

CURSOR dept_cursor ISSELECT *FROM deptWHERE deptno = 10;

BEGIN...

DECLARECURSOR emp_cursor IS SELECT empno, enameFROM emp;

CURSOR dept_cursor ISSELECT *FROM deptWHERE deptno = 10;

BEGIN...

Page 277: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Opening the CursorOpening the CursorOpening the Cursor

Syntax

– Open the cursor to execute the query and identify the active set.

– If the query returns no rows, no exception is raised.– Use cursor attributes to test the outcome after a fetch.

Syntax

– Open the cursor to execute the query and identify the active set.

– If the query returns no rows, no exception is raised.– Use cursor attributes to test the outcome after a fetch.

OPEN cursor_name;OPEN cursor_name;

Page 278: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Fetching Data from the CursorFetching Data from the CursorFetching Data from the Cursor

Syntax

– Retrieve the current row values into output variables.– Include the same number of variables.– Match each variable to correspond to the columns

positionally.– Test to see if the cursor contains rows.

Syntax

– Retrieve the current row values into output variables.– Include the same number of variables.– Match each variable to correspond to the columns

positionally.– Test to see if the cursor contains rows.

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

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

Page 279: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Fetching Data from the CursorFetching Data from the CursorFetching Data from the Cursor

ExampleExample

FETCH emp_cursor INTO v_empno, v_ename;FETCH emp_cursor INTO v_empno, v_ename;

...OPEN defined_cursor;LOOPFETCH defined_cursor INTO defined_variablesEXIT WHEN ...;...-- Process the retrieved data

...END;

...OPEN defined_cursor;LOOPFETCH defined_cursor INTO defined_variablesEXIT WHEN ...;...-- Process the retrieved data

...END;

Page 280: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Closing the CursorClosing the CursorClosing the Cursor

Syntax

– Close the cursor after completing the processing of the rows.

– Reopen the cursor, if required.– Do not attempt to fetch data from a cursor once it has

been closed.

Syntax

– Close the cursor after completing the processing of the rows.

– Reopen the cursor, if required.– Do not attempt to fetch data from a cursor once it has

been closed.

CLOSE cursor_name; CLOSE cursor_name;

Page 281: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Explicit Cursor AttributesExplicit Cursor AttributesExplicit Cursor Attributes

Obtain status information about a cursor.Obtain status information about a cursor.

Attribute Type Description

%ISOPEN Boolean Evaluates to TRUE if the cursor is open

%NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row

%FOUND Boolean Evaluates to TRUE if the mostrecent fetch returns a row; complement of %NOTFOUND

%ROWCOUNT Number Evaluates to the total number of rows returned so far

Page 282: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The %ISOPEN AttributeThe %ISOPEN AttributeThe %ISOPEN Attribute

– Fetch rows only when the cursor is open. – Use the %ISOPEN cursor attribute before performing a

fetch to test whether the cursor is open.

Example

– Fetch rows only when the cursor is open. – Use the %ISOPEN cursor attribute before performing a

fetch to test whether the cursor is open.

Example

IF NOT emp_cursor%ISOPEN THENOPEN emp_cursor;

END IF;LOOPFETCH emp_cursor...

IF NOT emp_cursor%ISOPEN THENOPEN emp_cursor;

END IF;LOOPFETCH emp_cursor...

Page 283: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Controlling Multiple FetchesControlling Multiple Fetches

– Process several rows from an explicit cursor using a loop.

– Fetch a row with each iteration.– Use the %NOTFOUND attribute to write a test for an

unsuccessful fetch.– Use explicit cursor attributes to test the success of

each fetch.

– Process several rows from an explicit cursor using a loop.

– Fetch a row with each iteration.– Use the %NOTFOUND attribute to write a test for an

unsuccessful fetch.– Use explicit cursor attributes to test the success of

each fetch.

Page 284: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The %NOTFOUND and %ROWCOUNT AttributesThe %NOTFOUND and %ROWCOUNT Attributes

– Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows.

– Use the %NOTFOUND cursor attribute to determine when to exit the loop.

– Use the %ROWCOUNT cursor attribute to retrieve an exact number of rows.

– Use the %NOTFOUND cursor attribute to determine when to exit the loop.

Page 285: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 286: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Cursors and RecordsCursors and RecordsCursors and Records

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

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

DECLARE CURSOR emp_cursor ISSELECT empno, enameFROM emp;

emp_record emp_cursor%ROWTYPE;BEGINOPEN emp_cursor;LOOPFETCH emp_cursor INTO emp_record;

...

DECLARE CURSOR emp_cursor ISSELECT empno, enameFROM emp;

emp_record emp_cursor%ROWTYPE;BEGINOPEN emp_cursor;LOOPFETCH emp_cursor INTO emp_record;

...

Page 287: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Cursor FOR LoopsCursor FOR LoopsCursor FOR Loops

Syntax

– The cursor FOR loop is a shortcut to process explicit cursors.

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

Syntax

– The cursor FOR loop is a shortcut to process explicit cursors.

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

FOR record_name IN cursor_name LOOP

statement1;statement2;. . .

END LOOP;

FOR record_name IN cursor_name LOOP

statement1;statement2;. . .

END LOOP;

Page 288: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Cursor FOR LoopsCursor FOR LoopsCursor FOR Loops

Retrieve employees one by one until no more are left.Example

Retrieve employees one by one until no more are left.Example

DECLARECURSOR emp_cursor ISSELECT ename, deptnoFROM emp;

BEGINFOR emp_record IN emp_cursor LOOP

-- implicit open and implicit fetch occurIF emp_record.deptno = 30 THEN...

END LOOP; -- implicit close occursEND;

DECLARECURSOR emp_cursor ISSELECT ename, deptnoFROM emp;

BEGINFOR emp_record IN emp_cursor LOOP

-- implicit open and implicit fetch occurIF emp_record.deptno = 30 THEN...

END LOOP; -- implicit close occursEND;

Page 289: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Cursor FOR Loops Using SubqueriesCursor FOR Loops Using Subqueries

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

BEGINFOR emp_record IN ( SELECT ename, deptno

FROM emp) LOOP-- implicit open and implicit fetch occur

IF emp_record.deptno = 30 THEN...

END LOOP; -- implicit close occursEND;

BEGINFOR emp_record IN ( SELECT ename, deptno

FROM emp) LOOP-- implicit open and implicit fetch occur

IF emp_record.deptno = 30 THEN...

END LOOP; -- implicit close occursEND;

Page 290: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Advanced Explicit Cursor ConceptsAdvanced Explicit Cursor Concepts

Page 291: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Cursors with ParametersCursors with Parameters

Syntax

– 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.

CURSOR cursor_name[(parameter_name datatype, ...)]

ISselect_statement;

CURSOR cursor_name[(parameter_name datatype, ...)]

ISselect_statement;

Page 292: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Cursors with ParametersCursors with Parameters

Pass the department number and job title to the WHERE clause. Example

Pass the department number and job title to the WHERE clause. Example

DECLARECURSOR emp_cursor (v_deptno NUMBER, v_job VARCHAR2) ISSELECT empno, enameFROM empWHERE deptno = v_deptno AND job = v_job;

BEGINOPEN emp_cursor(10, 'CLERK');

...

DECLARECURSOR emp_cursor (v_deptno NUMBER, v_job VARCHAR2) ISSELECT empno, enameFROM empWHERE deptno = v_deptno AND job = v_job;

BEGINOPEN emp_cursor(10, 'CLERK');

...

Page 293: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The FOR UPDATE ClauseThe FOR UPDATE Clause

Syntax

– Explicit locking lets you deny access for the duration of a transaction.

– Lock the rows before the update or delete.

Syntax

– Explicit locking lets you deny access for the duration of a transaction.

– Lock the rows before the update or delete.

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

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

Page 294: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The FOR UPDATE ClauseThe FOR UPDATE Clause

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

DECLARECURSOR emp_cursor IS SELECT empno, ename, sal FROM empWHERE deptno = 30FOR UPDATE NOWAIT;

DECLARECURSOR emp_cursor IS SELECT empno, ename, sal FROM empWHERE deptno = 30FOR UPDATE NOWAIT;

Page 295: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The WHERE CURRENT OF ClauseThe WHERE CURRENT OF Clause

Syntax

– 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.

WHERE CURRENT OF cursorWHERE CURRENT OF cursor

Page 296: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

The WHERE CURRENT OF ClauseThe WHERE CURRENT OF Clause

ExampleExampleExampleDECLARE

CURSOR sal_cursor ISSELECT salFROM empWHERE deptno = 30FOR UPDATE NOWAIT;

BEGINFOR emp_record IN sal_cursor LOOP

UPDATE empSET sal = emp_record.sal * 1.10WHERE CURRENT OF sal_cursor;

END LOOP;COMMIT;

END;

DECLARECURSOR sal_cursor IS

SELECT salFROM empWHERE deptno = 30FOR UPDATE NOWAIT;

BEGINFOR emp_record IN sal_cursor LOOP

UPDATE empSET sal = emp_record.sal * 1.10WHERE CURRENT OF sal_cursor;

END LOOP;COMMIT;

END;

Page 297: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Cursors with SubqueriesCursors with Subqueries

ExampleExampleExample

DECLARECURSOR my_cursor IS SELECT t1.deptno, dname, STAFFFROM dept t1, (SELECT deptno,

count(*) STAFFFROM empGROUP BY deptno) t2

WHERE t1.deptno = t2.deptno AND STAFF >= 5;

DECLARECURSOR my_cursor IS SELECT t1.deptno, dname, STAFFFROM dept t1, (SELECT deptno,

count(*) STAFFFROM empGROUP BY deptno) t2

WHERE t1.deptno = t2.deptno AND STAFF >= 5;

Page 298: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Handling ExceptionsHandling Exceptions

Page 299: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Handling Exceptions with PL/SQLHandling Exceptions with PL/SQL

– What is an exception?Identifier in PL/SQL that is raised during execution

– How is it raised?An Oracle error occurs.You raise it explicitly.

– How do you handle it?Trap it with a handler.Propagate it to the calling environment.

– What is an exception?Identifier in PL/SQL that is raised during execution

– How is it raised?An Oracle error occurs.You raise it explicitly.

– How do you handle it?Trap it with a handler.Propagate it to the calling environment.

Page 300: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Handling ExceptionsHandling Exceptions

Propagate the exceptionPropagate the exceptionTrap the exception

DECLAREDECLARE

BEGINBEGIN

END;END;

EXCEPTIONEXCEPTION

DECLAREDECLARE

BEGINBEGIN

END;END;

EXCEPTIONEXCEPTION

Exception isException isnot trappednot trapped

Exception Exception propagates to calling propagates to calling

environmentenvironment

Exception Exception is raised

Exception Exception is raised is raisedis raised

Exception Exception is trappedis trapped

Page 301: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Exception TypesException Types

}} Implicitly Implicitly raisedraised

Explicitly raisedExplicitly raised

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

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

Page 302: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Trapping ExceptionsTrapping Exceptions

SyntaxSyntax

EXCEPTIONWHEN exception1 [OR exception2 . . .] THENstatement1;statement2;. . .

[WHEN exception3 [OR exception4 . . .] THENstatement1;statement2;. . .]

[WHEN OTHERS THENstatement1;statement2;. . .]

EXCEPTIONWHEN exception1 [OR exception2 . . .] THENstatement1;statement2;. . .

[WHEN exception3 [OR exception4 . . .] THENstatement1;statement2;. . .]

[WHEN OTHERS THENstatement1;statement2;. . .]

Page 303: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Trapping Exceptions GuidelinesTrapping Exceptions Guidelines

– WHEN OTHERS is the last clause.– EXCEPTION keyword starts exception-handling

section.– Several exception handlers are allowed.– Only one handler is processed before leaving the

block.

– WHEN OTHERS is the last clause.– EXCEPTION keyword starts exception-handling

section.– Several exception handlers are allowed.– Only one handler is processed before leaving the

block.

Page 304: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Trapping Predefined Oracle Server ErrorsTrapping Predefined Oracle Server Errors

– Reference the standard name in the exception-handling routine.

– Sample predefined exceptions: NO_DATA_FOUNDTOO_MANY_ROWSINVALID_CURSORZERO_DIVIDEDUP_VAL_ON_INDEX

– Reference the standard name in the exception-handling routine.

– Sample predefined exceptions: NO_DATA_FOUNDTOO_MANY_ROWSINVALID_CURSORZERO_DIVIDEDUP_VAL_ON_INDEX

Page 305: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Predefined ExceptionPredefined ExceptionSyntaxSyntax

BEGIN SELECT ... COMMIT;EXCEPTIONWHEN NO_DATA_FOUND THENstatement1; statement2;

WHEN TOO_MANY_ROWS THENstatement1;

WHEN OTHERS THENstatement1; statement2; statement3;

END;

Page 306: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

DeclareDeclare AssociateAssociate

Declarative sectionDeclarative section

Reference Reference

ExceptionException--handlinghandlingsectionsection

Trapping Non-Predefined Oracle Server ErrorsTrapping Non-Predefined Oracle Server Errors

•• Name the Name the exception

•• Code the PRAGMA Code the PRAGMA EXCEPTION_INITEXCEPTION_INIT

•• Handle the Handle the raised raised exceptionexception

exception

Page 307: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Non-Predefined ErrorNon-Predefined ErrorTrap for Oracle Server error number –2292, an integrity constraint violation.Trap for Oracle Server error number –2292, an integrity constraint violation.

DECLAREe_emps_remaining EXCEPTION;PRAGMA EXCEPTION_INIT (

e_emps_remaining, -2292);v_deptno dept.deptno%TYPE := &p_deptno;

BEGINDELETE FROM deptWHERE deptno = v_deptno;COMMIT;

EXCEPTIONWHEN e_emps_remaining THENDBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. ');

END;

DECLAREe_emps_remaining EXCEPTION;PRAGMA EXCEPTION_INIT (

e_emps_remaining, -2292);v_deptno dept.deptno%TYPE := &p_deptno;

BEGINDELETE FROM deptWHERE deptno = v_deptno;COMMIT;

EXCEPTIONWHEN e_emps_remaining THENDBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(v_deptno) || '. Employees exist. ');

END;

e_emps_remaining EXCEPTION;PRAGMA EXCEPTION_INIT (

e_emps_remaining, -2292);

e_emps_remaining

1

2

3

Page 308: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Trapping User-Defined ExceptionsTrapping User-Defined Exceptions

•• Name the Name the exceptionexception

DeclareDeclare

DeclarativeDeclarativesectionsection

RaiseRaise

•• Explicitly raise Explicitly raise the exception by the exception by using the RAISE using the RAISE

ExecutableExecutablesectionsection

Reference Reference

•• Handle the Handle the raised raised exceptionexception

ExceptionException--handlinghandlingsectionsection

statementstatement

Page 309: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

User-Defined ExceptionUser-Defined Exception

DECLAREe_invalid_product EXCEPTION;

BEGINUPDATE productSET descrip = '&product_description'WHERE prodid = &product_number;IF SQL%NOTFOUND THENRAISE e_invalid_product;

END IF;COMMIT;

EXCEPTIONWHEN e_invalid_product THENDBMS_OUTPUT.PUT_LINE('Invalid product number.');

END;

DECLAREe_invalid_product EXCEPTION;

BEGINUPDATE productSET descrip = '&product_description'WHERE prodid = &product_number;IF SQL%NOTFOUND THENRAISE e_invalid_product;

END IF;COMMIT;

EXCEPTIONWHEN e_invalid_product THENDBMS_OUTPUT.PUT_LINE('Invalid product number.');

END;

e_invalid_product EXCEPTION;

RAISE e_invalid_product;

e_invalid_product

ExampleExampleExample

1

2

3

Page 310: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Functions for Trapping ExceptionsFunctions for Trapping Exceptions

– SQLCODEReturns the numeric value for the error code

– SQLERRMReturns the message associated with the error number

– SQLCODEReturns the numeric value for the error code

– SQLERRMReturns the message associated with the error number

Page 311: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Functions for Trapping ExceptionsFunctions for Trapping ExceptionsExampleExample

DECLAREv_error_code NUMBER;v_error_message VARCHAR2(255);

BEGIN...EXCEPTION...WHEN OTHERS THENROLLBACK;v_error_code := SQLCODE ;v_error_message := SQLERRM ;

INSERT INTO errors VALUES(v_error_code,v_error_message);

END;

SQLCODESQLERRM

Page 312: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Calling EnvironmentsCalling EnvironmentsSQL*Plus

Procedure Builder

OracleDeveloperFormsPrecompilerapplication

An enclosing PL/SQL block

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 throughthe SQLCA data structure

Traps exception in exception-handling routine of enclosing block

Page 313: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 314: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

RAISE_APPLICATION_ERRORProcedureRAISE_APPLICATION_ERRORProcedure

Syntax

– A procedure that lets you issue user-defined error messages from stored subprograms

– Called only from an executing stored subprogram

Syntax

– A procedure that lets you issue user-defined error messages from stored subprograms

– Called only from an executing stored subprogram

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

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

Page 315: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

RAISE_APPLICATION_ERRORProcedureRAISE_APPLICATION_ERRORProcedure

– Used in two different places:Executable sectionException section

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

– Used in two different places:Executable sectionException section

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

Page 316: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 317: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Procedure and Function

Page 318: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 319: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 320: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 321: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 322: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 323: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 324: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 325: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 326: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 327: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 328: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 329: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 330: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 331: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 332: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 333: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 334: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 335: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 336: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 337: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 338: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 339: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 340: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 341: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 342: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 343: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 344: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 345: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 346: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 347: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 348: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 349: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 350: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Package

Page 351: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 352: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 353: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 354: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 355: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 356: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 357: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 358: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 359: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 360: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 361: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 362: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 363: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 364: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 365: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 366: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 367: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 368: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 369: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 370: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 371: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 372: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 373: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 374: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 375: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 376: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 377: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 378: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 379: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 380: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 381: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 382: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 383: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 384: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 385: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 386: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 387: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 388: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 389: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Trigger

Page 390: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 391: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 392: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 393: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 394: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 395: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 396: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 397: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 398: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 399: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 400: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 401: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 402: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 403: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 404: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 405: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 406: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 407: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Managing Dependencies

Page 408: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 409: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 410: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 411: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Page 412: Oracle sql & plsql

Copyright © 2004, Oracle. All rights reserved.

Q U E S T I O N SQ U E S T I O N SA N S W E R SA N S W E R S