Sie sind auf Seite 1von 412

Copyright 2004, Oracle. All rights reserved.

Oracle SQL & PL/SQL

Huiyun Mao
Yolanda.mao@oracle.com

Copyright 2004, Oracle. All rights reserved.

SQL Overview

Copyright 2004, Oracle. All rights reserved.

SQL Statements
SELECT

Data retrieval language (DRL)

INSERT
UPDATE
DELETE

Data manipulation language (DML)

CREATE
ALTER
DROP
RENAME
TRUNCATE

Data definition language (DDL)

COMMIT
ROLLBACK
SAVEPOINT

Transaction control

GRANT
REVOKE

Data control language (DCL)

Copyright 2004, Oracle. All rights reserved.

Tables Used in the Course


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

EMP
EMP table
table
DEPT
DEPT table
table

Copyright 2004, Oracle. All rights reserved.

The EMP Table


EMP
EMPNO
--------7839
7698
7782
7566
7654
7499
7844
7900
7521
7902
7369
7788
7876
7934

ENAME
---------KING
BLAKE
CLARK
JONES
MARTIN
ALLEN
TURNER
JAMES
WARD
FORD
SMITH
SCOTT
ADAMS
MILLER

Primary key
Copyright 2004, Oracle. All rights reserved.

JOB
MGR HIREDATE
SAL
COMM
DEPTNO
--------- --------- --------- --------- --------- --------PRESIDENT
17-NOV-81
5000
10
MANAGER
7839 01-MAY-81
2850
30
MANAGER
7839 09-JUN-81
1500
10
MANAGER
7839 02-APR-81
2975
20
SALESMAN
7698 28-SEP-81
1250
1400
30
SALESMAN
7698 20-FEB-81
1600
300
30
SALESMAN
7698 08-SEP-81
1500
0
30
CLERK
7698 03-DEC-81
950
30
SALESMAN
7698 22-FEB-81
1250
500
30
ANALYST
7566 03-DEC-81
3000
20
CLERK
7902 17-DEC-80
800
20
ANALYST
7566 09-DEC-82
3000
20
CLERK
7788 12-JAN-83
1100
20
CLERK
7782 23-JAN-82
1300
10

Foreign key

Foreign key

DEPT Tables
DEPT
DEPTNO DNAME
LOC
--------- -------------- ---------10
20
30
40

ACCOUNTING
RESEARCH
SALES
OPERATIONS

Primary key

Copyright 2004, Oracle. All rights reserved.

NEW YORK
DALLAS
CHICAGO
BOSTON

Writing Basic
SQL Statements

Copyright 2004, Oracle. All rights reserved.

Capabilities of SQL SELECT


Statements
Restriction

Projection

Table 1

Table 1

Join

Table 1
Copyright 2004, Oracle. All rights reserved.

Table 2

Basic SELECT Statement


SELECT
FROM
[WHERE
[GROUP BY
[ORDER BY

[DISTINCT] {*, column [alias],...}


table
condition(s)]
group_by_expression]
column];

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

Copyright 2004, Oracle. All rights reserved.

Writing SQL Statements

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

Copyright 2004, Oracle. All rights reserved.

Retrieving All Columns


from a Table
DEPT
DEPTNO DNAME
10
20
30
40

ACCOUNTING
RESEARCH
SALES
OPERATIONS

LOC
NEW YORK
DALLAS
CHICAGO
BOSTON

Retrieve all
columns from the
DEPT table

DEPT
DEPTNO DNAME
10
20
30
40

ACCOUNTING
RESEARCH
SALES
OPERATIONS

LOC
NEW YORK
DALLAS
CHICAGO
BOSTON

All columns are displayed


Copyright 2004, Oracle. All rights reserved.

Selecting All Columns


SQL> SELECT *
2 FROM
dept;

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

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

Copyright 2004, Oracle. All rights reserved.

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

Creating a Projection on a Table


DEPT
DEPTNO DNAME
10
20
30
40

ACCOUNTING
RESEARCH
SALES
OPERATIONS

Retrieve DEPTNO
and LOC columns
from the DEPT
table

LOC
NEW YORK
DALLAS
CHICAGO
BOSTON

DEPT
DEPTNO LOC
10
20
30
40

NEW YORK
DALLAS
CHICAGO
BOSTON

Only two columns are displayed


Copyright 2004, Oracle. All rights reserved.

Selecting Specific Columns


SQL> SELECT deptno, loc
2 FROM
dept;
DEPTNO
--------10
20
30
40

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

Copyright 2004, Oracle. All rights reserved.

Default Column Justification


Character
left justified

Date
left justified

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

Copyright 2004, Oracle. All rights reserved.

Number
right justified

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

Operator

Description

Add

Subtract

Multiply

Divide

Copyright 2004, Oracle. All rights reserved.

Using Arithmetic Operators


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

Copyright 2004, Oracle. All rights reserved.

Using Arithmetic Operators on


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

Copyright 2004, Oracle. All rights reserved.

Operator Precedence

/ +

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

Copyright 2004, Oracle. All rights reserved.

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

Copyright 2004, Oracle. All rights reserved.

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

Copyright 2004, Oracle. All rights reserved.

Defining a Column Alias

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

Copyright 2004, Oracle. All rights reserved.

Using Column Aliases

SQL> SELECT ename AS name, sal salary


2 FROM
emp;
NAME
SALARY
------------- --------KING
5000
BLAKE
2850
CLARK
2450
JONES
2975
...
14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Using Column Aliases

SQL> SELECT ename "Name",


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

Copyright 2004, Oracle. All rights reserved.

Concatenation Operator

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

Copyright 2004, Oracle. All rights reserved.

Using the Concatenation Operator

SQL> SELECT
2 FROM

ename||job AS "Employees"
emp;

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

Copyright 2004, Oracle. All rights reserved.

Literals

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

Copyright 2004, Oracle. All rights reserved.

Using Literal Character Strings


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

Copyright 2004, Oracle. All rights reserved.

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

deptno
emp;

DEPTNO
--------10
30
10
20
..
14 rows selected.
Copyright 2004, Oracle. All rights reserved.

Eliminating Duplicate Rows


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

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

Copyright 2004, Oracle. All rights reserved.

Restricting and Sorting Data

Copyright 2004, Oracle. All rights reserved.

Limiting Rows by Using a Restriction


EMP
EMPNO ENAME
7839
7698
7782
7566
...

KING
BLAKE
CLARK
JONES

JOB

...

DEPTNO

PRESIDENT
MANAGER
MANAGER
MANAGER

10
30
10
20

Retrieve all
employees
in department 10

EMP
EMPNO ENAME

JOB

7839 KING
PRESIDENT
7782 CLARK MANAGER
7934 MILLER CLERK

Copyright 2004, Oracle. All rights reserved.

...

DEPTNO
10
10
10

Using the WHERE Clause


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

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

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

Copyright 2004, Oracle. All rights reserved.

Character Strings and Dates

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

SQL> SELECT
2 FROM
3 WHERE

Copyright 2004, Oracle. All rights reserved.

ename, job, deptno, hiredate


emp
ename = 'JAMES';

Comparison Operators
Operator

Meaning

Equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

<>

Not equal to

Copyright 2004, Oracle. All rights reserved.

Using the Comparison Operators


with Another Column

SQL> SELECT ename, sal, comm


2 FROM
emp
3 WHERE sal<=comm;

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

Copyright 2004, Oracle. All rights reserved.

Using the Comparison Operators


with Characters

SQL> SELECT ename, mgr


2 FROM
emp
3 WHERE ename='SMITH';

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

Copyright 2004, Oracle. All rights reserved.

Other SQL Comparison Operators

Operator

Meaning

BETWEEN
...AND...

Between two values (inclusive)

IN(list)

Match any of a list of values

LIKE

Match a character pattern

IS NULL

Is a null value

Copyright 2004, Oracle. All rights reserved.

Using the BETWEEN Operator


yy Use
Use the
the BETWEEN
BETWEEN operator
operator to
to display
display rows
rows based
based on
on
aa range
range of
of values.
values.
SQL> SELECT
2 FROM
3 WHERE

ename, sal
emp
sal BETWEEN 1000 AND 1500;

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

Copyright 2004, Oracle. All rights reserved.

Lower
limit

Higher
limit

Using the IN Operator


yy Use
Use the
the IN
IN operator
operator to
to test
test for
for values
values in
in aa list.
list.

SQL> SELECT
2 FROM
3 WHERE

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

empno, ename, sal, mgr


emp
mgr IN (7902, 7566, 7788);

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

Copyright 2004, Oracle. All rights reserved.

Using the IN Operator with Strings


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

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

Copyright 2004, Oracle. All rights reserved.

Using the LIKE Operator

Use
Use the
the LIKE
LIKE operator
operator to
to perform
perform wildcard
wildcard searches
searches of
of
valid
valid search
search string
string values.
values.
Search
Search conditions
conditions can
can contain
contain either
either literal
literal characters
characters
or
or numbers.
numbers.
yy
yy

%
% denotes
denotes zero
zero or
or many
many characters
characters
__ denotes
denotes one
one character
character

SQL> SELECT
2 FROM
3 WHERE
Copyright 2004, Oracle. All rights reserved.

ename
emp
ename LIKE 'S%';

Using the LIKE Operator


You
You can
can combine
combine pattern
pattern matching
matching
characters.
characters.
SQL> SELECT
2 FROM
3 WHERE

ename
emp
ename LIKE '_A%';

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

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

Using the IS NULL Operator


yy Test
Test for
for null
null values
values with
with the
the IS
IS NULL
NULL operator.
operator.
SQL> SELECT
2 FROM
3 WHERE

ename, mgr
emp
mgr IS NULL;

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

Copyright 2004, Oracle. All rights reserved.

Logical Operators

Operator

Meaning

AND

Returns TRUE if both component


conditions are TRUE

OR

Returns TRUE if either component


condition is TRUE

NOT

Returns TRUE if the following


condition is FALSE

Copyright 2004, Oracle. All rights reserved.

Using the AND Operator


yy AND
AND requires
requires both
both conditions
conditions to
to be
be TRUE.
TRUE.
SQL>
2
3
4

SELECT
FROM
WHERE
AND

EMPNO
--------7876
7934

empno, ename, job, sal


emp
sal>=1100
job='CLERK';

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

Copyright 2004, Oracle. All rights reserved.

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

Using the AND Operator


yy AND
AND requires
requires both
both conditions
conditions to
to be
be TRUE.
TRUE.
SQL>
2
3
4

SELECT
FROM
WHERE
AND

ename, mgr, sal,deptno


emp
sal>1000
deptno = 10;

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

Copyright 2004, Oracle. All rights reserved.

Using the OR Operator


OR
OR requires
requires either
either condition
condition to
to be
be TRUE.
TRUE.
SQL>
2
3
4

SELECT
FROM
WHERE
OR

empno, ename, job, sal


emp
sal>=2000
job='CLERK';

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

JOB
SAL
--------- --------PRESIDENT
5000
MANAGER
2850
MANAGER
2450
MANAGER
2975
CLERK
950
ANALYST
3000

Using the OR Operator


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

SQL>
2
3
4

SELECT
FROM
WHERE
OR

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

ename, deptno, mgr


emp
deptno = 10
mgr = 7839;

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

Copyright 2004, Oracle. All rights reserved.

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

Using the NOT Operator


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

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

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

Copyright 2004, Oracle. All rights reserved.

Using the NOT Operator


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

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

Copyright 2004, Oracle. All rights reserved.

Using the NOT Operator


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

Using the NOT Operator


SQL>
2
3
4

SELECT ename, sal AS "Salary Before Commission",


comm
FROM
emp
WHERE comm IS NOT NULL;

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

Copyright 2004, Oracle. All rights reserved.

Rules of Precedence
Order Evaluated
1
2
3
4

Operator
All comparison
operators
NOT
AND
OR

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

Copyright 2004, Oracle. All rights reserved.

Rules of Precedence
SQL>
2
3
4
5

SELECT
FROM
WHERE
OR
AND

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

ename, job, sal


emp
job='SALESMAN'
job='PRESIDENT'
sal>1500;

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

Copyright 2004, Oracle. All rights reserved.

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

Rules of Precedence
Use
Use parentheses
parentheses to
to force
force priority.
priority.
SQL>
2
3
4
5

SELECT
FROM
WHERE
OR
AND

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

ename, job, sal


emp
(job='SALESMAN'
job='PRESIDENT')
sal>1500;

JOB
--------PRESIDENT
SALESMAN

Copyright 2004, Oracle. All rights reserved.

SAL
--------5000
1600

ORDER BY Clause

Sort
Sort rows
rows with
with the
the ORDER
ORDER BY
BY clause:
clause:

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

yy ASC:
ASC: ascending
ascending order,
order, default
default
yy DESC:
DESC: descending
descending order
order

SQL> SELECT ename, job, deptno


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

Sorting in Descending Order


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

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

Sorting by Column Alias


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

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

Sorting by Multiple Columns


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

Sorting by a Column Not in the


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

Copyright 2004, Oracle. All rights reserved.

Single-Row Number and Character


Functions

Copyright 2004, Oracle. All rights reserved.

How a Function Works

Input

Function
Performs
operation

Copyright 2004, Oracle. All rights reserved.

Output

Two Types of SQL Functions

Functions

Single-row
functions

Copyright 2004, Oracle. All rights reserved.

Multiple-row
functions

Single-Row Functions

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

Copyright 2004, Oracle. All rights reserved.

Single-Row Functions
Character

Number

Single-row
functions

Conversion

Copyright 2004, Oracle. All rights reserved.

Date

Character Functions
Character
functions

Case conversion
functions
LOWER
UPPER
INITCAP

Copyright 2004, Oracle. All rights reserved.

Character manipulation
functions

Case Conversion Functions


yy Convert
Convert the
the case
case for
for character
character strings
strings
Function

Result

LOWER('SQL Course')

sql course

UPPER('SQL Course')

SQL COURSE

INITCAP('SQL Course')

Sql Course

Copyright 2004, Oracle. All rights reserved.

Using Case Conversion Functions


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

empno, ename, deptno


emp
ename = UPPER('blake');

EMPNO ENAME
DEPTNO
--------- ---------- --------7698 BLAKE
30
Copyright 2004, Oracle. All rights reserved.

Using Case Conversion Functions


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

Number Functions

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

Copyright 2004, Oracle. All rights reserved.

Defining a Null Value

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

SQL> SELECT
2 FROM

ename, job, comm


emp;

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

Null Values in Arithmetic


Expressions

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

Using the NVL Function


NVL (expr1, expr2)

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

NVL
NVL can
can be
be used
used with
with date,
date, character,
character, and
and number
number
data
data types.
types.
Data
Data types
types must
must match.
match. For
For example:
example:
yy
yy
yy

NVL(comm,0)
NVL(comm,0)
NVL(hiredate,'01-JAN-97')
NVL(hiredate,'01-JAN-97')
NVL(job,
'no job
yet'
NVL(job,'no
job yet')
yet')

Copyright 2004, Oracle. All rights reserved.

Using the NVL Function to Handle


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

Copyright 2004, Oracle. All rights reserved.

Single-Row Date and Conversion


Functions

Copyright 2004, Oracle. All rights reserved.

Single-Row Functions
Character

Number

Single-row
functions

Conversion

Copyright 2004, Oracle. All rights reserved.

Date

Working with Dates

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

Copyright 2004, Oracle. All rights reserved.

SYSDATE

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

SQL> SELECT SYSDATE


2 FROM
DUAL;
SYSDATE
--------26-JAN-98

Copyright 2004, Oracle. All rights reserved.

Default Date Formats


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

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

Copyright 2004, Oracle. All rights reserved.

Arithmetic with Dates

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

Copyright 2004, Oracle. All rights reserved.

Using Arithmetic Operators


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

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

Copyright 2004, Oracle. All rights reserved.

Using SYSDATE in Calculations


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

Copyright 2004, Oracle. All rights reserved.

Explicit Data Type Conversion


TO_NUMBER

NUMBER

TO_CHAR

Copyright 2004, Oracle. All rights reserved.

TO_DATE

CHARACTER

TO_CHAR

DATE

Modifying the Display Format of


Dates

Tuesday the 27th of January, 1998


27-JAN-98

January 27, 1998


01/27/98

Copyright 2004, Oracle. All rights reserved.

TO_CHAR Function with Dates


TO_CHAR(date, 'fmfmt')

yy The
The format
format model:
model:

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

Copyright 2004, Oracle. All rights reserved.

Date Format Model Elements


YYYY

Full year in numbers

YEAR

Year spelled out

MM

2-digit value for month

MONTH

Full name of the month

DY

3-letter abbreviation of the day


of the week

DAY

Full name of the day

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with


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

AS HIREDATE

FROM

WHERE job='MANAGER';

ENAME

HIREDATE

emp

---------- -------------------BLAKE

May

01st, 1981

CLARK

June

09th, 1981

JONES

April

02nd, 1981

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with


Dates
SQL> SELECT
2 FROM
3 WHERE

empno, TO_CHAR(hiredate, 'MM/YY') AS MONTH


emp
ename='BLAKE';

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

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with


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

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

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with


Dates
SQL>
2
3
4
5

SELECT ename, mgr, sal,TO_CHAR(hiredate,'YYYY-MON-DD')


AS
HIREDATE
FROM
emp
WHERE sal<1000
AND hiredate like '%80';

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

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with


Dates
SQL>
2
3
4

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

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

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

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with


Dates
SQL>
2
3
4

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

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

Copyright 2004, Oracle. All rights reserved.

Date Format Model Elements

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

HH24:MI:SS AM

15:45:32 PM

DD "of" MONTH

12 of OCTOBER

ddspth

fourteenth

Copyright 2004, Oracle. All rights reserved.

Using Format Models to Display Time

SQL> SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') TIME


2 FROM
DUAL;

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

Copyright 2004, Oracle. All rights reserved.

TO_CHAR Function with Numbers


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

9
0

Represents a number
Forces a zero to be displayed

Places a floating dollar sign

L
.
,

Uses the floating local currency symbol


Prints a decimal point
Places a thousand indicator

Copyright 2004, Oracle. All rights reserved.

Using the TO_CHAR Function with


Numbers

SQL> SELECT
2 FROM
3 WHERE

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

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

Thousand indicator
Dollar sign

Copyright 2004, Oracle. All rights reserved.

Using the TO_NUMBER and


TO_DATE Functions

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

TO_NUMBER(char)

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

Copyright 2004, Oracle. All rights reserved.

Using the TO_NUMBER Function

SQL> SELECT
2 FROM
3 WHERE

NEW_SALARY
---------4000

Copyright 2004, Oracle. All rights reserved.

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

Date Functions
FUNCTION

DESCRIPTION

MONTHS_BETWEEN

Number of months
between two dates

ADD_MONTHS

Adds calendar months to


date

NEXT_DAY

Next day following the date


specified

LAST_DAY

Last day of the month

ROUND

Round off date

TRUNC

Truncate date

Copyright 2004, Oracle. All rights reserved.

Using Date Functions


yy Use
Use the
the ADD_MONTHS
ADD_MONTHS function
function to
to add
add months
months to
to
aa date.
date.
SQL>
2
3
4

SELECT ename, hiredate, ADD_MONTHS(hiredate, 6)


AS
"+6 MONTHS"
FROM
emp
WHERE ename='BLAKE';

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

Copyright 2004, Oracle. All rights reserved.

Nesting Functions

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

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

Copyright 2004, Oracle. All rights reserved.

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

Result 2

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

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

Copyright 2004, Oracle. All rights reserved.

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

Months
---------1.03225806

Copyright 2004, Oracle. All rights reserved.

Displaying Data
from Multiple Tables

Copyright 2004, Oracle. All rights reserved.

Obtaining
Obtaining Data
Data from
from Multiple
Multiple Tables
Tables
EMP
EMPNO
-----7839
7698
...
7934

DEPT
ENAME
----KING
BLAKE

... DEPTNO
... -----...
10
...
30

MILLER ...

EMPNO
----7839
7698
7782
7566
7654
7499

Copyright 2004, Oracle. All rights reserved.

10

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

DEPTNO
-----10
20
30
40

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

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

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

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

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

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

Copyright 2004, Oracle. All rights reserved.

Types of Joins
Equijoin
Equijoin Nonequijoin
Nonequijoin Self
Self join
join

Copyright 2004, Oracle. All rights reserved.

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

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

Links rows that satisfy a specified condition

WHERE emp.deptno=dept.deptno

Copyright 2004, Oracle. All rights reserved.

Equijoin
EMP

DEPT

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

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

DNAME
---------ACCOUNTING
SALES
ACCOUNTING
RESEARCH
SALES
SALES
SALES
SALES
SALES
RESEARCH
RESEARCH
selected.

Primary key

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

Retrieving Records
with an Equijoin
SQL> SELECT
2
3 FROM
4 WHERE

emp.empno, emp.ename, emp.deptno,


dept.deptno, dept.loc
emp, dept
emp.deptno=dept.deptno;

EMPNO ENAME DEPTNO DEPTNO LOC


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

Copyright 2004, Oracle. All rights reserved.

Qualifying Ambiguous
Column Names

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

Copyright 2004, Oracle. All rights reserved.

Additional Search Conditions


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

DEPT
DEPTNO DNAME
------ --------10 ACCOUNTING
30 SALES
10 ACCOUNTING
20 RESEARCH
30 SALES
30 SALES
30 SALES
30 SALES
...
14 rows selected.

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

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

Copyright 2004, Oracle. All rights reserved.

Using Additional Search Conditions


with a Join
SQL>
2
3
4

SELECT
FROM
WHERE
AND

emp.empno, emp.ename, emp.deptno, dept.loc


emp, dept;
emp.deptno = dept.deptno
emp.ename = 'KING';

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

Copyright 2004, Oracle. All rights reserved.

Using Additional Search Conditions


with a Join
SQL> SELECT emp.ename, emp.job, dept.deptno, dept.dname
2
3
4

FROM
WHERE
AND

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

emp, dept
emp.deptno=dept.deptno
emp.job IN ('MANAGER','PRESIDENT');

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

Copyright 2004, Oracle. All rights reserved.

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

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

Copyright 2004, Oracle. All rights reserved.

Using Table Aliases


SQL> SELECT e.empno, e.ename, e.deptno,
2
d.deptno, d.loc
3 FROM
emp e, dept d
4 WHERE e.deptno=d.deptno;
EMPNO
--------7839
7698
7782
7566
7654
7499
...

ENAME
DEPTNO
DEPTNO LOC
---------- --------- --------- ----------KING
10
10 NEW YORK
BLAKE
30
30 CHICAGO
CLARK
10
10 NEW YORK
JONES
20
20 DALLAS
MARTIN
30
30 CHICAGO
ALLEN
30
30 CHICAGO

14 rows selected.

Copyright 2004, Oracle. All rights reserved.

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

Copyright 2004, Oracle. All rights reserved.

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

Salary in the EMP


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

Retrieving Records
with Nonequijoins
SQL>
2
3
4

SELECT
FROM
WHERE
BETWEEN

e.ename, e.sal, s.grade


emp e,
salgrade s
e.sal
s.losal AND s.hisal;

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

Copyright 2004, Oracle. All rights reserved.

Joining More Than Two Tables


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

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

SALGRADE

LOSAL
HISAL
GRADE
--------- --------- --------700
1200
1
WHERE emp.sal BETWEEN
1201
1400
2
salgrade.losal AND
1401
2000
3
2001
3000
4
salgrade.hisal
3001
9999
5
AND emp.deptno = dept.deptno
14 rows selected.

Copyright 2004, Oracle. All rights reserved.

Using Multiple Joins


SQL>
2
3
4

SELECT
FROM
WHERE
AND

e.ename, e.deptno, d.dname, e.sal, s.grade


emp e,
dept d,
salgrade s
e.deptno=d.deptno
e.sal BETWEEN s.losal and s.hisal;

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

Copyright 2004, Oracle. All rights reserved.

DNAME
SAL
GRADE
-------------- --------- --------SALES
950
1
RESEARCH
800
1
RESEARCH
1100
1
SALES
1250
2
SALES
1250
2
ACCOUNTING
1300
2
SALES
1600
3

Selfjoins
EMP (WORKER)
EMPNO
----7839
7698
7782
7566
7654
7499

ENAME
-----KING
BLAKE
CLARK
JONES
MARTIN
ALLEN

MGR
---7839
7839
7839
7698
7698

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

KING
KING
KING
BLAKE
BLAKE

MGR in the WORKER table is equal to EMPNO in the


MANAGER table.

Copyright 2004, Oracle. All rights reserved.

Joining a Table to Itself


SQL>
2
3
4

SELECT
AS
FROM
WHERE

worker.ename||' works for '||manager.ename


WHO_WORKS_FOR_WHOM
emp worker, emp manager
worker.mgr = manager.empno;

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

Copyright 2004, Oracle. All rights reserved.

Aggregating Data
by Using Group Functions

Copyright 2004, Oracle. All rights reserved.

What Are Group Functions?


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

maximum
salary in
the EMP table

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

Types of Group Functions

AVG
AVG
COUNT
COUNT
MAX
MAX
MIN
MIN
SUM
SUM

Copyright 2004, Oracle. All rights reserved.

Guidelines for Using Group


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

Copyright 2004, Oracle. All rights reserved.

Using the AVG and SUM Functions


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

SQL> SELECT
2 FROM
3 WHERE

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

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

Copyright 2004, Oracle. All rights reserved.

Using the MIN and MAX Functions


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

SQL> SELECT
2
3 FROM

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

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

Copyright 2004, Oracle. All rights reserved.

Using the MIN and MAX Functions


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

SQL> SELECT MIN(sal) AS "Lowest Salary",


2 MAX(sal) AS "Highest Salary"
3 FROM
emp;
Lowest Salary Highest Salary
------------- -------------800
5000

Copyright 2004, Oracle. All rights reserved.

Using the COUNT Function


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

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

Copyright 2004, Oracle. All rights reserved.

COUNT(*)
emp
deptno = 30;

Using the COUNT Function


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

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

Copyright 2004, Oracle. All rights reserved.

COUNT(comm)
emp
deptno = 30;

Group Functions and Null Values


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

SQL> SELECT AVG(comm)


2 FROM
emp;

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

Copyright 2004, Oracle. All rights reserved.

Using the NVL Function


with Group Functions

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

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

Copyright 2004, Oracle. All rights reserved.

Using the NVL Function


with Group Functions

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

SQL>
2
3
4
5

SELECT
FROM
WHERE
BETWEEN
AND

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

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

Copyright 2004, Oracle. All rights reserved.

Creating Groups of Data


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

Copyright 2004, Oracle. All rights reserved.

2916.6667

average
salary
in EMP
2175
table
for each
department
1566.6667

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

Creating Groups of Data:


GROUP BY Clause

yy Use
Use the
the GROUP
GROUP BY
BY clause
clause to
to divide
divide rows
rows in
in aa table
table
into
into smaller
smaller groups.
groups.
SELECT
FROM
[WHERE
[GROUP BY
[ORDER BY

Copyright 2004, Oracle. All rights reserved.

column, group_function
table
condition]
group_by_expression]
column];

Using the GROUP BY Clause


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

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

DEPTNO AVG(SAL)
--------- --------10 2916.6667
20
2175
30 1566.6667
Copyright 2004, Oracle. All rights reserved.

Using the GROUP BY Clause


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

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

Copyright 2004, Oracle. All rights reserved.

Using the GROUP BY Clause


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

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

DEPTNO Dept Employees


--------- -------------10
3
20
5
30
6

Copyright 2004, Oracle. All rights reserved.

Using a Group Function in the


ORDER BY Clause
SQL>
2
3
4

SELECT
FROM
GROUP BY
ORDER BY

deptno, AVG(sal)
emp
deptno
AVG(sal);

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

Copyright 2004, Oracle. All rights reserved.

Illegal Queries
Using Group Functions
yy Any
Any column
column or
or expression
expression in
in the
the SELECT
SELECT list
list that
that is
is
not
not an
an aggregate
aggregate function
function must
must be
be in
in the
the GROUP
GROUP BY
BY
e
e
s
s
clause.
clause.
u
u
a
a
l
l
cc
BBYY
PP
SQL>
U
U
SQL> SELECT
SELECT deptno,
deptno, COUNT(ename)
COUNT(ename)
O
O
R
22 FROM
emp;
R
FROM
emp;
G
G
e
e
tthh
nn
i
i
SELECT
SELECT deptno,
deptno, COUNT(ename)
COUNT(ename)nngg
ii
**
s
s
iiss
ERROR
at
line
1:
m
ERROR at line 1:
m
n
n
ORA-00937:
group
ORA-00937: not
not aa single-group
single-group
group function
function
m
m
u
u
l
l
o
o
CC
Copyright 2004, Oracle. All rights reserved.

Using Set Operators

Copyright 2004, Oracle. All rights reserved.

The Set Operators


A

Intersect
A

Union / Union All


A

Minus
Copyright 2004, Oracle. All rights reserved.

Tables Used in This Lesson


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

COMM
COMM
----------------- ---------------

TITLE
TITLE
1400
1400
----------------300
300
OPERATOR
OPERATOR
00
MANAGER
MANAGER
CLERK
CLERK

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

500
500
ANALYST
05-MAY-81
ANALYST
05-MAY-81
ANALYST
ANALYST

10-JUN-81
10-JUN-81

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

UNION
A

Copyright 2004, Oracle. All rights reserved.

Using the UNION Operator


yy Display
Display the
the name,
name, employee
employee number,
number, and
and job
job title
title of
of
all
all employees.
employees. Display
Display each
each employee
employee only
only once.
once.
SQL>
2
3
4
5

SELECT
FROM
UNION
SELECT
FROM

ename, empno, job


emp
name, empid, title
emp_history;

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

JOB
--------CLERK
SALESMAN
CLERK

Using the UNION Operator


yy Display
Display the
the name,
name, job
job title,
title, and
and salary
salary of
of all
all
employees.
employees.
SQL>
2
3
4
5

SELECT
FROM
UNION
SELECT
FROM

ename, job, sal


emp
name, title, 0
emp_history;

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

UNION ALL
A

Copyright 2004, Oracle. All rights reserved.

Using the UNION ALL Operator


yy Display
Display the
the names,
names, employee
employee numbers,
numbers, and
and job
job
titles
titles of
of all
all employees.
employees.
SQL>
2
3
4
5

SELECT ename, empno, job


FROM
emp
UNION ALL
SELECT name, empid, title
FROM
emp_history;

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

JOB
--------PRESIDENT
MANAGER
MANAGER
MANAGER

INTERSECT
A

Copyright 2004, Oracle. All rights reserved.

Using the INTERSECT Operator


yy Display
Display the
the distinct
distinct names,
names, employee
employee numbers,
numbers, and
and
job
job titles
titles of
of employees
employees found
found in
in both
both the
the EMP
EMP and
and
EMP_HISTORY
EMP_HISTORY tables.
tables.
SQL>
2
3
4
5

SELECT ename, empno, job


FROM
emp
INTERSECT
SELECT name, empid, title
FROM
emp_history;

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

MINUS
A

Copyright 2004, Oracle. All rights reserved.

MINUS
Display
Display the
the names,
names, employee
employee numbers,
numbers, and
and
job
job titles
titles for
for all
all employees
employees who
who have
have left
left the
the
company.
company.
SQL>
2
3
4
5

SELECT
FROM
MINUS
SELECT
FROM

name, empid, title


emp_history
ename, empno, job
emp;

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

TITLE
TITLE
----------------CLERK
CLERK
PAY
PAY CLERK
CLERK

SET Operator Rules

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

Copyright 2004, Oracle. All rights reserved.

Matching the SELECT


Statement
Display
Display the
the department
department numbers,
numbers,
locations,
locations, and
and hiredates
hiredates for
for all
all employees.
employees.
SQL>
2
3
4
5

SELECT
FROM
UNION
SELECT
FROM

deptno, null location, hiredate


emp
deptno, loc, TO_DATE(null)
dept;

Copyright 2004, Oracle. All rights reserved.

Controlling the Order of Rows


Produce
Produce an
an English
English sentence
sentence using
using two
two
UNION
UNION operators.
operators.
SQL>
SQL>
SQL>
SQL>
22
33
44
55
66
77
88
99

COLUMN
COLUMN a_dummy
a_dummy NOPRINT
NOPRINT
SELECT
SELECT 'sing'
'sing' "My
"My dream",
dream", 33 a_dummy
a_dummy
FROM
FROM dual
dual
UNION
UNION
SELECT
SELECT 'I''d
'I''d like
like to
to teach',
teach', 11
FROM
FROM dual
dual
UNION
UNION
SELECT
SELECT 'the
'the world
world to',
to', 22
FROM
FROM dual
dual
ORDER
ORDER BY
BY 2;
2;

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

Writing Subqueries

Copyright 2004, Oracle. All rights reserved.

Using a Subquery
to Solve a Problem
yWho
yWho has
has aa salary
salary greater
greater than
than Joness?
Joness?
Main Query

Which employees have a salary greater


than Joness salary?
Subquery

Copyright 2004, Oracle. All rights reserved.

What is Joness salary?

Subqueries
SELECT
FROM
WHERE

select_list
table
expr operator
(SELECT
FROM

select_list
table);

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

Copyright 2004, Oracle. All rights reserved.

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

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

Copyright 2004, Oracle. All rights reserved.

Guidelines for Using Subqueries

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

Copyright 2004, Oracle. All rights reserved.

Types of Subqueries

Single-row
Single-row subquery
subquery
Main query

Subquery

returns

Multiple-row
Multiple-row subquery
subquery

CLERK

Main query
Subquery

Copyright 2004, Oracle. All rights reserved.

returns

CLERK
MANAGER

Single-Row Subqueries

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

Operator

Meaning

Equal to

>

Greater than

>=

Greater than or equal to

<

Less than

<=

Less than or equal to

<>

Not equal to

Copyright 2004, Oracle. All rights reserved.

Executing Single-Row Subqueries


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

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

Copyright 2004, Oracle. All rights reserved.

Executing Single-Row Subqueries


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

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

Copyright 2004, Oracle. All rights reserved.

Executing Single-Row Subqueries


Who has the same job as employee 7369 and
earns a higher salary than employee 7876?
SQL>
2
3
4
5
6
7
8
9
10

SELECT
FROM
WHERE

AND

ename, job
emp
job =
(SELECT
FROM
WHERE
sal >
(SELECT
FROM
WHERE

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

Copyright 2004, Oracle. All rights reserved.

CLERK
job
emp
empno = 7369)
1100
sal
emp
empno = 7876);

Using Group Functions


in a Subquery
Display all employees who earn the minimum salary.
SQL> SELECT
2 FROM
3 WHERE
4
5

ename, job, sal


emp
sal =
(SELECT
FROM

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

Copyright 2004, Oracle. All rights reserved.

800
MIN(sal)
emp);

What Is Wrong
with This Statement?
SQL> SELECT empno, ename
2 FROM
emp
3 WHERE sal =
4
(SELECT
5
FROM
6
GROUP BY

ERROR:
ORA-01427: single-row
one row

w
o
-r
e
l
g
n
Si

no rows selected

Copyright 2004, Oracle. All rights reserved.

w
o
r
MIN(sal)
e
emp ipl
t
l
deptno);
u
m

ith
w
r
o
t
subquery
returns
a
r
e
p
o

y
r
e
u
q
b
su

more than

Will This Statement Work?

SQL> SELECT ename,


2 FROM
emp
3 WHERE job =
4
5
6

job

s
(SELECT job
e
u
l
FROM
emp
a
v
WHERE
ename='SMYTHE');
o

no rows selected

y
r
e
u
q
b
Su

Copyright 2004, Oracle. All rights reserved.

s
n
r
u
t
e
r

Multiple-Row Subqueries

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

Copyright 2004, Oracle. All rights reserved.

Using Group Functions


in a Multiple-Row Subquery
Display all employees who earn the same salary as
the minimum salary for each department.
SQL> SELECT
2 FROM
3 WHERE
4
5
6

ename, sal, deptno


emp
800, 950, 1300
sal IN
(SELECT
MIN(sal)
FROM
emp
GROUP BY deptno);

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

Copyright 2004, Oracle. All rights reserved.

Using Group Functions


in a Multiple-Row Subquery
Display the employees who were hired on the same
date as the longest serving employee in any
department.
SQL>
2
3
4
5
6
7

SELECT ename, sal, deptno,


TO_CHAR(hiredate,'DD-MON-YYYY')HIREDATE
FROM
emp
WHERE
hiredate IN
(SELECT
MIN(hiredate)
FROM
emp
GROUP BY deptno);
ENAME
SAL
DEPTNO HIREDATE
---------- --------- --------- ----------SMITH
800
20 17-DEC-1980
ALLEN
1600
30 20-FEB-1981
CLARK
2450
10 09-JUN-1981

Copyright 2004, Oracle. All rights reserved.

Controlling Transactions

Copyright 2004, Oracle. All rights reserved.

Data Manipulation Language

A
A DML
DML statement
statement is
is executed
executed when
when you:
you:
yy
yy
yy

Add
Add new
new rows
rows to
to aa table
table (INSERT)
(INSERT)
Modify
Modify existing
existing rows
rows in
in aa table
table (UPDATE)
(UPDATE)
Remove
Remove existing
existing rows
rows from
from aa table
table (DELETE)
(DELETE)

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

Copyright 2004, Oracle. All rights reserved.

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

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

One
One DDL
DDL statement
statement
Example:
Example: CREATE
CREATE

One
One DCL
DCL statement
statement
Example:
Example: GRANT
GRANT and
and REVOKE
REVOKE

Copyright 2004, Oracle. All rights reserved.

Database Transactions

Begin
Begin when
when the
the first
first executable
executable SQL
SQL statement
statement is
is
executed
executed
End
End with
with one
one of
of the
the following
following events:
events:
yy
yy
yy
yy

COMMIT
COMMIT or
or ROLLBACK
ROLLBACK
DDL
DDL or
or DCL
DCL statement
statement executes
executes (automatic
(automatic commit)
commit)
User
User exits
exits
System
System crashes
crashes

Copyright 2004, Oracle. All rights reserved.

Advantages of COMMIT
and ROLLBACK

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

Copyright 2004, Oracle. All rights reserved.

Controlling Transactions
yy Transaction
Transaction

INSERT
COMMIT

UPDATE

Savepoint A

INSERT

DELETE

Savepoint B

ROLLBACK to Savepoint B

ROLLBACK to Savepoint A

ROLLBACK
Copyright 2004, Oracle. All rights reserved.

Implicit Transaction Processing

An
An automatic
automatic commit
commit occurs
occurs under
under the
the following
following
circumstances:
circumstances:
yy
yy
yy

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

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

Copyright 2004, Oracle. All rights reserved.

State of the Data Before


COMMIT or ROLLBACK

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

Copyright 2004, Oracle. All rights reserved.

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

Make
Make the
the changes.
changes.

SQL>
SQL> UPDATE
UPDATE emp
emp
22 SET
deptno
SET
deptno == 10
10
33 WHERE
empno
WHERE
empno == 7782;
7782;
11 row
row updated.
updated.

Commit
Commit the
the changes.
changes.
SQL> COMMIT;
Commit complete.

Copyright 2004, Oracle. All rights reserved.

State of the Data After COMMIT


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

State of the Data After ROLLBACK


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

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

SQL> DELETE FROM employee;


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

Rolling Back Changes


to a Marker

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

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

Copyright 2004, Oracle. All rights reserved.

Statement-Level Rollback

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

Copyright 2004, Oracle. All rights reserved.

Read Consistency

Read
Read consistency
consistency guarantees
guarantees aa consistent
consistent view
view of
of the
the
data
data at
at all
all times.
times.
Changes
Changes made
made by
by one
one user
user do
do not
not conflict
conflict with
with
changes
changes made
made by
by another
another user.
user.
Read
Read consistency
consistency ensures
ensures that
that on
on the
the same
same data:
data:
yy
yy

Readers
Readers do
do not
not wait
wait for
for writers
writers or
or other
other readers
readers
Writers
Writers do
do not
not wait
wait for
for readers
readers

Copyright 2004, Oracle. All rights reserved.

Implementation of Read Consistency

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

Data
blocks
Rollback
segments

User A
SELECT *
FROM emp;

User B
Copyright 2004, Oracle. All rights reserved.

Read
consistent
image

Changed
and
unchanged
data
Before
change
old data

Locking
yy The
The Oracle
Oracle Server
Server locks:
locks:

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

Copyright 2004, Oracle. All rights reserved.

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

Copyright 2004, Oracle. All rights reserved.

Implicit Locking
User Action
SELECT ... FROM table ...

Row-Level Lock Table-Level Lock


None

None

INSERT INTO table ...

RX

UPDATE table ...

RX

DELETE FROM table ...

RX

None

DDL Operation

Copyright 2004, Oracle. All rights reserved.

Explicit Locking
User Action

Row-Level lock

SELECT FOR UPDATE

LOCK TABLE IN option

None

Table-Level lock
RS [NOWAIT]
Depends on the MODE
restrictiveness used

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

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

Copyright 2004, Oracle. All rights reserved.

Overview of PL/SQL

Copyright 2004, Oracle. All rights reserved.

About PL/SQL

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

Copyright 2004, Oracle. All rights reserved.

PL/SQL Environment
PL/SQL engine
PL/SQL
block

PL/SQL
block

PL/SQL
SQL

Procedural
Statement
Executor

SQL Statement Executor


Oracle Server

Copyright 2004, Oracle. All rights reserved.

Benefits of PL/SQL
yy Integration
Integration

Application

Shared
library

Copyright 2004, Oracle. All rights reserved.

Oracle Server

Benefits of PL/SQL
yy Improve
Improve Performance
Performance
SQL

Application
Application

SQL
SQL

Other
Other DBMSs
DBMSs

SQL

Application
Application

Copyright 2004, Oracle. All rights reserved.

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

Oracle
Oracle with
with
PL/SQL
PL/SQL

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

BEGIN

EXCEPTION

END;

Copyright 2004, Oracle. All rights reserved.

Benefits of PL/SQL

ItIt is
is portable.
portable.
You
You can
can declare
declare identifiers.
identifiers.

Copyright 2004, Oracle. All rights reserved.

Benefits of PL/SQL

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

Copyright 2004, Oracle. All rights reserved.

Declaring Variables

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Structure

DECLARE
DECLAREOptional
Optional

BEGIN
BEGINMandatory
Mandatory

EXCEPTION
EXCEPTIONOptional
Optional

Variables,
Variables,cursors,
cursors,user-defined
user-definedexceptions
exceptions
SQL
SQLstatements
statements
PL/SQL
PL/SQLstatements
statements
Actions
Actionstotoperform
performwhen
when
errors
errorsoccur
occur

END;
END;Mandatory
Mandatory

DECLARE
BEGIN
EXCEPTION
END;

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Structure


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

DECLARE
BEGIN
EXCEPTION
END;

Copyright 2004, Oracle. All rights reserved.

Block Types
y Anonymous

Procedure

Function

[[DECLARE]
DECLARE]

PROCEDURE
PROCEDURE name
name
IS
IS

BEGIN
BEGIN
-statements
--statements

BEGIN
BEGIN
-statements
--statements

[EXCEPTION]
[EXCEPTION]

[EXCEPTION]
[EXCEPTION]

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

END;
END;

END;
END;

END;
END;

Copyright 2004, Oracle. All rights reserved.

Program Constructs
Anonymous
Anonymous
block
block

Application
Application
trigger
trigger

DECLARE
BEGIN
EXCEPTION

Database
Database
trigger
trigger

Copyright 2004, Oracle. All rights reserved.

END;

Stored
Stored
procedure/
procedure/
function
function
Application
Application
procedure/
procedure/
function
function

Packaged
Packaged
procedure/
procedure/
function
function

Use of Variables
yy Use
Use variables
variables for:
for:

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

Copyright 2004, Oracle. All rights reserved.

Handling Variables in PL/SQL

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

Copyright 2004, Oracle. All rights reserved.

Types of Variables

PL/SQL
PL/SQL variables:
variables:
yy
yy
yy
yy

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

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

Copyright 2004, Oracle. All rights reserved.

Types of Variables

PL/SQL
PL/SQL variables:
variables:
yy
yy
yy
yy

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

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

Copyright 2004, Oracle. All rights reserved.

Types of Variables

TRUE

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

256120.08

to the proposition that all men


are created equal.

Atlanta
Copyright 2004, Oracle. All rights reserved.

Declaring PL/SQL Variables


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

Examples
Examples
Declare
Declare
v_hiredate
v_hiredate
v_deptno
v_deptno
v_location
v_location
c_comm
c_comm

Copyright 2004, Oracle. All rights reserved.

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

Declaring PL/SQL Variables


yy Guidelines
Guidelines

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

Copyright 2004, Oracle. All rights reserved.

Naming Rules

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

rr
o
f
o
f
nn
o
i
o
t
i
nnt
e
e
v
v
oonn errss::
c
c
gg tiiffiie
n
oo
i
n
DECLARE
i
n
t
DECLARE
n
n
m
n
p
m
e
a
p
nna L iidde _eem
m
empno
a
empno NUMBER(4);
NUMBER(4);
a
L
_
t
v
t
Q llee,, v
BEGIN
oopp LL//SSQ
BEGIN
d
d
pp
A
PP
A
m
m
SELECT
empno
a
SELECT
empno
xxa
e
e
r
INTO
empno
INTO
empno
ffoor
FROM
emp
FROM
WHERE
WHERE
END;
END;

Copyright 2004, Oracle. All rights reserved.

emp
ename
ename == 'SMITH';
'SMITH';

Assigning Values to Variables


Syntax
Syntax
yidentifier
yidentifier :=
:= expr;
expr;

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

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

Copyright 2004, Oracle. All rights reserved.

Variable Initialization and Keywords


yy Using:
Using:

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

Copyright 2004, Oracle. All rights reserved.

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

25-OCT-99
Four score and seven years
ago our fathers brought

TRUE

forth upon this continent, a


new nation, conceived in

256120.08

LIBERTY, and dedicated to


the proposition that all men
are created equal.

Copyright 2004, Oracle. All rights reserved.

Atlanta

Base Scalar Datatypes

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

Copyright 2004, Oracle. All rights reserved.

Base Scalar Datatypes

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

Copyright 2004, Oracle. All rights reserved.

Scalar Variable Declarations


yy Example
Example
v_job
v_job
v_count
v_count
v_total_sal
v_total_sal
v_orderdate
v_orderdate
c_tax_rate
c_tax_rate
v_valid
v_valid

Copyright 2004, Oracle. All rights reserved.

VARCHAR2(9);
VARCHAR2(9);
BINARY_INTEGER
BINARY_INTEGER :=
:= 0;
0;
NUMBER(9,2)
NUMBER(9,2) :=
:= 0;
0;
DATE
DATE :=
:= SYSDATE
SYSDATE ++ 7;
7;
CONSTANT
CONSTANT NUMBER(3,2)
NUMBER(3,2) :=
:= 8.25;
8.25;
BOOLEAN
BOOLEAN NOT
NOT NULL
NULL :=
:= TRUE;
TRUE;

The %TYPE Attribute

Declare
Declare aa variable
variable according
according to:
to:
yy
yy

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

Prefix
Prefix %TYPE
%TYPE with:
with:
yy The
The database
database table
table and
and column
column
yy The
The previously
previously declared
declared variable
variable name
name

Copyright 2004, Oracle. All rights reserved.

Declaring Variables
with the %TYPE Attribute
yy Example
Example

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

Copyright 2004, Oracle. All rights reserved.

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

Declaring Boolean Variables

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

Copyright 2004, Oracle. All rights reserved.

Composite Datatypes

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

Copyright 2004, Oracle. All rights reserved.

LOB Datatype Variables


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

Copyright 2004, Oracle. All rights reserved.

Bind Variables

O/S
Bind Variable
Server

Copyright 2004, Oracle. All rights reserved.

Referencing Non-PL/SQL Variables

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

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

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

DBMS_OUTPUT.PUT_LINE

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

Copyright 2004, Oracle. All rights reserved.

Writing Executable Statements

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Syntax


and Guidelines

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

Spaces
Spaces
Delimiters
Delimiters
Identifiers
Identifiers
Literals
Literals
Comments
Comments

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Syntax


and Guidelines
yy Identifiers
Identifiers

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

Copyright 2004, Oracle. All rights reserved.

PL/SQL Block Syntax and Guidelines


yy Literals
Literals

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

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

Copyright 2004, Oracle. All rights reserved.

Commenting Code

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

yy Example
Example

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

Copyright 2004, Oracle. All rights reserved.

SQL Functions in PL/SQL

Available:
Available:
yy
yy
yy
yy

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

Not
Not available:
available:
yy
yy

DECODE
DECODE
Group
Group functions
functions

Copyright 2004, Oracle. All rights reserved.

Same as in SQL

PL/SQL Functions
yy Example
Example

Build
Build the
the mailing
mailing list
list for
for aa company.
company.

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

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

v_ename
v_ename

Copyright 2004, Oracle. All rights reserved.

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

Datatype Conversion

Convert
Convert data
data to
to comparable
comparable datatypes.
datatypes.
Mixed
Mixed datatypes
datatypes can
can result
result in
in an
an error
error and
and affect
affect
performance.
performance.
Conversion
Conversion functions:
functions:
yy
yy
yy

TO_CHAR
TO_CHAR
TO_DATE
TO_DATE
TO_NUMBER
TO_NUMBER

DECLARE
DECLARE
v_date
v_date
BEGIN
BEGIN
SELECT
SELECT

VARCHAR2(15);
VARCHAR2(15);

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

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

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

Copyright 2004, Oracle. All rights reserved.

Nested Blocks
and Variable Scope

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

Copyright 2004, Oracle. All rights reserved.

Nested Blocks
and Variable Scope
yy An
An identifier
identifier is
is visible
visible in
in the
the regions
regions in
in which
which you
you
can
can reference
reference the
the unqualified
unqualified identifier:
identifier:

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

Copyright 2004, Oracle. All rights reserved.

Nested Blocks
and Variable Scope
Example
Example
y...
y...
yy xx BINARY_INTEGER;
BINARY_INTEGER;
yBEGIN
yBEGIN
yy ...
...
yy DECLARE
DECLARE
yy
yy NUMBER;
NUMBER;
yy BEGIN
BEGIN
yy
...
...
yy END;
END;
yy ...
...
yEND;
yEND;

Copyright 2004, Oracle. All rights reserved.

Scope of x

Scope of y

Operators in PL/SQL

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

Copyright 2004, Oracle. All rights reserved.

Same as in
SQL

Operators in PL/SQL
yy Example
Example

Increment
Increment the
the index
index for
for aa loop.
loop.

v_count
v_count

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

Set
Set the
the value
value of
of aa Boolean
Boolean flag.
flag.

v_equal
:=
(v_n1
v_n2);
v_equal
:=employee
(v_n1 == number
v_n2);ifif itit contains
Validate
Validate an
an
employee
number
contains aa value.
value.

v_valid
v_valid

Copyright 2004, Oracle. All rights reserved.

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

Using Bind Variables


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

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

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

Copyright 2004, Oracle. All rights reserved.

Code Naming Conventions


yy Avoid
Avoid ambiguity:
ambiguity:

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

Copyright 2004, Oracle. All rights reserved.

Indenting Code
yy
yy

For
For clarity,
clarity, indent
indent each
each level
level of
of code.
code.
Example
Example
BEGIN
BEGIN
IF
IF x=0
x=0 THEN
THEN
y:=1;
y:=1;
END
END IF;
IF;
END;
END;

Copyright 2004, Oracle. All rights reserved.

DECLARE
DECLARE
v_deptno
NUMBER(2);
v_deptno
NUMBER(2);
v_location
VARCHAR2(13);
v_location
VARCHAR2(13);
BEGIN
BEGIN
SELECT
SELECT deptno,
deptno,
loc
loc
INTO
v_deptno,
INTO
v_deptno,
v_location
v_location
FROM
dept
FROM
dept
WHERE
dname
WHERE
dname == 'SALES';
'SALES';
...
...
END;
END;

Determining Variable Scope


yy Class
Class Exercise
Exercise
...
...
DECLARE
DECLARE
V_SAL
V_SAL
V_COMM
V_COMM
V_MESSAGE
V_MESSAGE
BEGIN
BEGIN ...
...

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

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

Writing Control Structures

Copyright 2004, Oracle. All rights reserved.

Controlling PL/SQL Flow


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

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

Copyright 2004, Oracle. All rights reserved.

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

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

== 'OSBORNE'
'OSBORNE' THEN
THEN
22;
22;

Copyright 2004, Oracle. All rights reserved.

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

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

Copyright 2004, Oracle. All rights reserved.

IF-THEN-ELSE Statement Execution


Flow
TRUE

FALSE
IF condition

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

Copyright 2004, Oracle. All rights reserved.

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

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

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

Copyright 2004, Oracle. All rights reserved.

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

IF-THEN-ELSIF
Statement Execution Flow
IF
IF condition
condition
TRUE

ELSIF
ELSIF
condition
condition

THEN
THEN actions
actions
TRUE

THEN
THEN actions
actions

Copyright 2004, Oracle. All rights reserved.

FALSE

FALSE
ELSE
ELSE
actions
actions

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

Copyright 2004, Oracle. All rights reserved.

Building Logical Conditions

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

Copyright 2004, Oracle. All rights reserved.

Logic Tables
yy Build
Build aa simple
simple Boolean
Boolean condition
condition with
with aa
comparison
comparison operator.
operator.
TRUE FALSE NULL

NOT

TRUE

TRUE

TRUE

FALSE

FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL

FALSE

TRUE

NULL

NULL

AND

TRUE

FALSE

NULL

OR

TRUE

TRUE

FALSE

NULL

TRUE

NULL

NULL

FALSE

Copyright 2004, Oracle. All rights reserved.

NULL

NULL

TRUE

TRUE

NULL

NULL

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

V_REORDER_FLAG

V_AVAILABLE_FLAG

V_FLAG

TRUE

TRUE

TRUE

TRUE

FALSE

FALSE

NULL

TRUE

NULL

NULL

FALSE

FALSE

Copyright 2004, Oracle. All rights reserved.

Iterative Control: LOOP Statements

Loops
Loops repeat
repeat aa statement
statement or
or sequence
sequence of
of statements
statements
multiple
multiple times.
times.
There
There are
are three
three loop
loop types:
types:
yy
yy
yy

Basic
Basic loop
loop
FOR
FOR loop
loop
WHILE
WHILE loop
loop

Copyright 2004, Oracle. All rights reserved.

Basic Loop
yy Syntax
Syntax
LOOP
LOOP
statement1;
statement1;
.. .. ..
EXIT
EXIT [WHEN
[WHEN condition];
condition];
END
END LOOP;
LOOP;

where:
where:

condition
condition

Copyright 2004, Oracle. All rights reserved.

-- delimiter
-- statements
-- EXIT statement
-- delimiter

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

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

Copyright 2004, Oracle. All rights reserved.

FOR Loop
yy

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

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

Copyright 2004, Oracle. All rights reserved.

FOR Loop
yy Guidelines
Guidelines

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

Copyright 2004, Oracle. All rights reserved.

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

Copyright 2004, Oracle. All rights reserved.

WHILE Loop
yy Syntax
Syntax
WHILE
WHILE condition
condition LOOP
LOOP
statement1;
statement1;
statement2;
statement2;
.. .. ..
END
END LOOP;
LOOP;

Condition is
evaluated at the
beginning of
each iteration.

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

Copyright 2004, Oracle. All rights reserved.

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

Copyright 2004, Oracle. All rights reserved.

''
''

Nested Loops and Labels

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

Copyright 2004, Oracle. All rights reserved.

Nested Loops and Labels


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

Writing Explicit Cursors

Copyright 2004, Oracle. All rights reserved.

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

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

Copyright 2004, Oracle. All rights reserved.

Explicit Cursor Functions

Active set

Cursor

Copyright 2004, Oracle. All rights reserved.

7369 SMITH

CLERK

7566 JONES

MANAGER

7788 SCOTT

ANALYST

7876 ADAMS

CLERK

7902 FORD

ANALYST

Current row

Controlling Explicit Cursors


No
Yes
DECLARE
DECLARE

OPEN
OPEN

Create a

Identify

named
SQL area

the active
set

EMPTY?

CLOSE
CLOSE

Load the

Test for

Release

current
row into
variables

existing
rows

FETCH
FETCH

Return to
FETCH if
rows
found

Copyright 2004, Oracle. All rights reserved.

the active
set

Controlling Explicit Cursors


Open the cursor.
Pointer
Cursor

Fetch a row from the cursor.


Pointer
Cursor

Continue until empty.


Pointer
Cursor

Close the cursor.

Cursor
Copyright 2004, Oracle. All rights reserved.

Declaring the Cursor


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

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

Copyright 2004, Oracle. All rights reserved.

Declaring the Cursor


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

Copyright 2004, Oracle. All rights reserved.

Opening the Cursor


yy Syntax
Syntax
OPEN
OPEN cursor_name;
cursor_name;

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

Copyright 2004, Oracle. All rights reserved.

Fetching Data from the Cursor


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

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

Copyright 2004, Oracle. All rights reserved.

Fetching Data from the Cursor


yy Example
Example
yy

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

Copyright 2004, Oracle. All rights reserved.

Closing the Cursor


yy Syntax
Syntax
CLOSE
CLOSE

cursor_name;
cursor_name;

Close
Close the
the cursor
cursor after
after completing
completing the
the processing
processing of
of the
the
rows.
rows.
Reopen
Reopen the
the cursor,
cursor, ifif required.
required.
Do
Do not
not attempt
attempt to
to fetch
fetch data
data from
from aa cursor
cursor once
once itit has
has
been
been closed.
closed.

Copyright 2004, Oracle. All rights reserved.

Explicit Cursor Attributes


yy Obtain
Obtain status
status information
information about
about aa cursor.
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 most


recent fetch returns a row;
complement of %NOTFOUND

%ROWCOUNT

Number

Evaluates to the total number of


rows returned so far

Copyright 2004, Oracle. All rights reserved.

The %ISOPEN Attribute

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

yy Example
Example

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

Copyright 2004, Oracle. All rights reserved.

Controlling Multiple Fetches

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

Copyright 2004, Oracle. All rights reserved.

The %NOTFOUND
and %ROWCOUNT Attributes

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

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Cursors and Records


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

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

Copyright 2004, Oracle. All rights reserved.

Cursor FOR Loops


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

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

Copyright 2004, Oracle. All rights reserved.

Cursor FOR Loops


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

Copyright 2004, Oracle. All rights reserved.

Cursor FOR Loops


Using Subqueries

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

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

Copyright 2004, Oracle. All rights reserved.

Advanced Explicit Cursor


Concepts

Copyright 2004, Oracle. All rights reserved.

Cursors with Parameters


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

Pass parameter values to a cursor when the cursor is


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

Copyright 2004, Oracle. All rights reserved.

Cursors with Parameters


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

Copyright 2004, Oracle. All rights reserved.

The FOR UPDATE Clause


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

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

Copyright 2004, Oracle. All rights reserved.

The FOR UPDATE Clause


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

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

Copyright 2004, Oracle. All rights reserved.

The WHERE CURRENT OF Clause


y Syntax
WHERE
WHERE CURRENT
CURRENT OF
OF cursor
cursor

Use cursors to update or delete the current row.


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

Copyright 2004, Oracle. All rights reserved.

The WHERE CURRENT OF Clause


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

Copyright 2004, Oracle. All rights reserved.

Cursors with Subqueries


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

Copyright 2004, Oracle. All rights reserved.

Handling Exceptions

Copyright 2004, Oracle. All rights reserved.

Handling Exceptions with PL/SQL

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

How
How is
is itit raised?
raised?
yy An
An Oracle
Oracle error
error occurs.
occurs.
yy You
You raise
raise itit explicitly.
explicitly.

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

Trap
Trap itit with
with aa handler.
handler.
Propagate
Propagate itit to
to the
the calling
calling environment.
environment.

Copyright 2004, Oracle. All rights reserved.

Handling Exceptions
y Trap the exception

Exception
is raised

Propagate the exception

DECLARE

DECLARE

BEGIN

BEGIN

EXCEPTION

EXCEPTION

Exception
is trapped END;

END;

Exception
is raised
Exception is
not trapped

Exception
propagates to calling
environment

Copyright 2004, Oracle. All rights reserved.

Exception Types

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

Implicitly
raised

Explicitly raised

Copyright 2004, Oracle. All rights reserved.

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

Copyright 2004, Oracle. All rights reserved.

Trapping Exceptions Guidelines

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

Copyright 2004, Oracle. All rights reserved.

Trapping Predefined
Oracle Server Errors

Reference
Reference the
the standard
standard name
name in
in the
the exceptionexceptionhandling
handling routine.
routine.
Sample
Sample predefined
predefined exceptions:
exceptions:
yy
yy
yy
yy
yy

NO_DATA_FOUND
NO_DATA_FOUND
TOO_MANY_ROWS
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_CURSOR
ZERO_DIVIDE
ZERO_DIVIDE
DUP_VAL_ON_INDEX
DUP_VAL_ON_INDEX

Copyright 2004, Oracle. All rights reserved.

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

Copyright 2004, Oracle. All rights reserved.

Trapping Non-Predefined Oracle


Server Errors

Declare

Associate

Declarative section

Name the
exception

Copyright 2004, Oracle. All rights reserved.

Reference
Exception-handling
section

Code the PRAGMA Handle the


EXCEPTION_INIT

raised
exception

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

1
2

Trapping User-Defined Exceptions

Declare

Raise

Reference

Declarative
section

Executable
section

Exception-handling
section

Name the
exception

Copyright 2004, Oracle. All rights reserved.

Explicitly raise
the exception by
using the RAISE
statement

Handle the
raised
exception

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

Copyright 2004, Oracle. All rights reserved.

Functions for Trapping Exceptions

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

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

Copyright 2004, Oracle. All rights reserved.

Functions for Trapping Exceptions


yy Example
Example
DECLARE
v_error_code
v_error_message
BEGIN
...
EXCEPTION
...
WHEN OTHERS THEN
ROLLBACK;
v_error_code :=
v_error_message

NUMBER;
VARCHAR2(255);

SQLCODE ;
:= SQLERRM ;

INSERT INTO errors VALUES(v_error_code,


v_error_message);
END;

Copyright 2004, Oracle. All rights reserved.

Calling Environments
SQL*Plus

Displays error number and message


to screen

Procedure
Builder

Displays error number and message


to screen

Oracle
Developer
Forms

Accesses error number and message


in a trigger by means of the
ERROR_CODE and ERROR_TEXT
packaged functions

Precompiler
application

Accesses exception number through


the SQLCA data structure

An enclosing
PL/SQL block

Traps exception in exceptionhandling routine of enclosing block

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

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

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

Copyright 2004, Oracle. All rights reserved.

RAISE_APPLICATION_ERROR
Procedure

Used
Used in
in two
two different
different places:
places:
yy Executable
Executable section
section
yy Exception
Exception section
section

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

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Procedure and Function

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Package

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Trigger

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Managing Dependencies

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Copyright 2004, Oracle. All rights reserved.

Q U E S T
A N S W

Copyright 2004, Oracle. All rights reserved.

I O N S
E R S

Das könnte Ihnen auch gefallen