Beruflich Dokumente
Kultur Dokumente
Huiyun Mao
Yolanda.mao@oracle.com
SQL Overview
SQL Statements
SELECT
INSERT
UPDATE
DELETE
CREATE
ALTER
DROP
RENAME
TRUNCATE
COMMIT
ROLLBACK
SAVEPOINT
Transaction control
GRANT
REVOKE
EMP
EMP table
table
DEPT
DEPT table
table
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
NEW YORK
DALLAS
CHICAGO
BOSTON
Writing Basic
SQL Statements
Projection
Table 1
Table 1
Join
Table 1
Copyright 2004, Oracle. All rights reserved.
Table 2
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.
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.
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
DEPTNO
--------10
20
30
40
DNAME
-------------ACCOUNTING
RESEARCH
SALES
OPERATIONS
LOC
------------NEW YORK
DALLAS
CHICAGO
BOSTON
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
LOC
------------NEW YORK
DALLAS
CHICAGO
BOSTON
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.
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
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.
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.
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.
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
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
SQL> SELECT
2 FROM
ename||job AS "Employees"
emp;
Employees
------------------KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN
...
14 rows selected.
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.
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.
DEPTNO
--------10
20
30
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
...
DEPTNO
10
10
10
ENAME
---------KING
CLARK
MILLER
JOB
DEPTNO
--------- --------PRESIDENT
10
MANAGER
10
CLERK
10
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
Comparison Operators
Operator
Meaning
Equal to
>
Greater than
>=
<
Less than
<=
<>
Not equal to
ENAME
SAL
COMM
---------- --------- --------MARTIN
1250
1400
ENAME
MGR
---------- --------SMITH
7902
Operator
Meaning
BETWEEN
...AND...
IN(list)
LIKE
IS NULL
Is a null value
ename, sal
emp
sal BETWEEN 1000 AND 1500;
ENAME
SAL
---------- --------MARTIN
1250
TURNER
1500
WARD
1250
ADAMS
1100
MILLER
1300
Lower
limit
Higher
limit
SQL> SELECT
2 FROM
3 WHERE
EMPNO
--------7902
7369
7788
7876
ENAME
SAL
MGR
---------- --------- --------FORD
3000
7566
SMITH
800
7902
SCOTT
3000
7566
ADAMS
1100
7788
ENAME
DEPTNO HIREDATE
---------- --------- --------BLAKE
30 01-MAY-81
MARTIN
30 28-SEP-81
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%';
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.
ename, mgr
emp
mgr IS NULL;
ENAME
MGR
---------- --------KING
Logical Operators
Operator
Meaning
AND
OR
NOT
SELECT
FROM
WHERE
AND
EMPNO
--------7876
7934
ENAME
---------ADAMS
MILLER
JOB
SAL
--------- --------CLERK
1100
CLERK
1300
SELECT
FROM
WHERE
AND
ENAME
MGR
SAL
DEPTNO
---------- --------- --------- --------KING
5000
10
CLARK
7839
2450
10
MILLER
7782
1300
10
SELECT
FROM
WHERE
OR
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
SQL>
2
3
4
SELECT
FROM
WHERE
OR
ENAME
---------KING
BLAKE
CLARK
JONES
MILLER
DEPTNO
-------10
30
10
20
10
MGR
--------7839
7839
7839
7782
ENAME
---------KING
MARTIN
ALLEN
TURNER
WARD
JOB
--------PRESIDENT
SALESMAN
SALESMAN
SALESMAN
SALESMAN
EMPNO
ENAME
DEPTNO
MGR
--------- ---------- --------- --------7654 MARTIN
30
7698
7499 ALLEN
30
7698
...
...
7902 FORD
20
7566
7369 SMITH
20
7902
...
10 rows selected.
ENAME
Salary Before Commission
COMM
---------- ------------------------ --------MARTIN
1250
1400
ALLEN
1600
300
TURNER
1500
0
WARD
1250
500
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.
Rules of Precedence
SQL>
2
3
4
5
SELECT
FROM
WHERE
OR
AND
ENAME
---------KING
MARTIN
ALLEN
TURNER
WARD
JOB
------PRESIDENT
SALESMAN
SALESMAN
SALESMAN
SALESMAN
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
JOB
--------PRESIDENT
SALESMAN
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
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.
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.
Input
Function
Performs
operation
Output
Functions
Single-row
functions
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
Single-Row Functions
Character
Number
Single-row
functions
Conversion
Date
Character Functions
Character
functions
Case conversion
functions
LOWER
UPPER
INITCAP
Character manipulation
functions
Result
LOWER('SQL Course')
sql course
UPPER('SQL Course')
SQL COURSE
INITCAP('SQL Course')
Sql Course
EMPNO ENAME
DEPTNO
--------- ---------- --------7698 BLAKE
30
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
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
---------- --------- --------KING
PRESIDENT
BLAKE
MANAGER
...
TURNER
SALESMAN
0
...
14 rows selected.
Copyright 2004, Oracle. All rights reserved.
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.
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')
Single-Row Functions
Character
Number
Single-row
functions
Conversion
Date
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.
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.
ENAME
HIREDATE
---------- --------SMITH
17-DEC-80
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
ENAME
HIREDATE NEW DATE
---------- --------- --------SMITH
17-DEC-80 16-JAN-81
NUMBER
TO_CHAR
TO_DATE
CHARACTER
TO_CHAR
DATE
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
YEAR
MM
MONTH
DY
DAY
AS HIREDATE
FROM
WHERE job='MANAGER';
ENAME
HIREDATE
emp
---------- -------------------BLAKE
May
01st, 1981
CLARK
June
09th, 1981
JONES
April
02nd, 1981
EMPNO MONTH
--------- ----7698 05/81
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.
ENAME
MGR
SAL HIREDATE
---------- --------- --------- ----------SMITH
7902
800 1980-DEC-17
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
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.
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
TIME
-------13:55:46
9
0
Represents a number
Forces a zero to be displayed
L
.
,
SQL> SELECT
2 FROM
3 WHERE
TO_CHAR(sal,'$99,999') SALARY
emp
ename = 'SCOTT';
SALARY
-------$3,000
Thousand indicator
Dollar sign
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'])
SQL> SELECT
2 FROM
3 WHERE
NEW_SALARY
---------4000
TO_NUMBER('1000')+sal AS NEW_SALARY
emp
ename = 'SCOTT';
Date Functions
FUNCTION
DESCRIPTION
MONTHS_BETWEEN
Number of months
between two dates
ADD_MONTHS
NEXT_DAY
LAST_DAY
ROUND
TRUNC
Truncate date
ENAME
HIREDATE +6 MONTHS
---------- --------- --------BLAKE
01-MAY-81 01-NOV-81
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
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
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
Displaying Data
from Multiple Tables
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
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.
Types of Joins
Equijoin
Equijoin Nonequijoin
Nonequijoin Self
Self join
join
What Is an Equijoin?
EMP
EMPNO ENAME
DEPTNO
------ ------- ------...
7782 CLARK
10
DEPT
DEPTNO DNAME
LOC
------- ---------- -------...
10 ACCOUNTING NEW YORK
...
WHERE emp.deptno=dept.deptno
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
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.
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
SELECT
FROM
WHERE
AND
EMPNO ENAME
DEPTNO LOC
--------- ---------- --------- ------------7839 KING
10 NEW YORK
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
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;
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.
Nonequijoins
EMP
EMPNO ENAME
SAL
------ ------- -----7839 KING
5000
7698 BLAKE
2850
7782 CLARK
2450
7566 JONES
2975
7654 MARTIN
1250
7499 ALLEN
1600
7844 TURNER
1500
7900 JAMES
950
...
14 rows selected.
SALGRADE
GRADE LOSAL HISAL
----- ----- -----1
700
1200
2
1201
1400
3
1401
2000
4
2001
3000
5
3001
9999
Retrieving Records
with Nonequijoins
SQL>
2
3
4
SELECT
FROM
WHERE
BETWEEN
ENAME
SAL
GRADE
---------- --------- --------JAMES
950
1
SMITH
800
1
ADAMS
1100
1
...
14 rows selected.
DEPT
DEPTNO DNAME
--------- ---------10 ACCOUNTING
20 RESEARCH
30 SALES
40 OPERATIONS
SALGRADE
LOSAL
HISAL
GRADE
--------- --------- --------700
1200
1
WHERE emp.sal BETWEEN
1201
1400
2
salgrade.losal AND
1401
2000
3
2001
3000
4
salgrade.hisal
3001
9999
5
AND emp.deptno = dept.deptno
14 rows selected.
SELECT
FROM
WHERE
AND
ENAME
DEPTNO
---------- --------JAMES
30
SMITH
20
ADAMS
20
MARTIN
30
WARD
30
MILLER
10
ALLEN
30
...
14 rows selected.
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
SELECT
AS
FROM
WHERE
WHO_WORKS_FOR_WHOM
------------------------------BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.
Aggregating Data
by Using Group Functions
maximum
salary in
the EMP table
MAX(SAL)
--------5000
AVG
AVG
COUNT
COUNT
MAX
MAX
MIN
MIN
SUM
SUM
SQL> SELECT
2 FROM
3 WHERE
AVG(sal), SUM(sal)
emp
job LIKE 'SALES%';
AVG(SAL) SUM(SAL)
-------- --------1400
5600
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
SQL> SELECT
2 FROM
3 WHERE
COUNT(*)
--------6
COUNT(*)
emp
deptno = 30;
SQL> SELECT
2 FROM
3 WHERE
COUNT(COMM)
----------4
COUNT(comm)
emp
deptno = 30;
AVG(COMM)
--------550
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
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
2916.6667
average
salary
in EMP
2175
table
for each
department
1566.6667
DEPTNO AVG(SAL)
------- --------10 2916.6667
20
2175
30 1566.6667
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
column, group_function
table
condition]
group_by_expression]
column];
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.
AVG(SAL)
--------2916.6667
2175
1566.6667
SQL> SELECT
deptno, COUNT(*) AS "Dept Employees"
2 FROM
emp
3 GROUP BY deptno;
SELECT
FROM
GROUP BY
ORDER BY
deptno, AVG(sal)
emp
deptno
AVG(sal);
DEPTNO
AVG(SAL)
---------- -----------30
1566.6667
20
2175
10
2916.6667
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.
Intersect
A
Minus
Copyright 2004, Oracle. All rights reserved.
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
SELECT
FROM
UNION
SELECT
FROM
ENAME
EMPNO
---------- --------ADAMS
7876
ALLEN
7499
BALFORD
6235
...
20 rows selected.
Copyright 2004, Oracle. All rights reserved.
JOB
--------CLERK
SALESMAN
CLERK
SELECT
FROM
UNION
SELECT
FROM
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
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
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
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
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
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.
SELECT
FROM
UNION
SELECT
FROM
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
Using a Subquery
to Solve a Problem
yWho
yWho has
has aa salary
salary greater
greater than
than Joness?
Joness?
Main Query
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).
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
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.
Types of Subqueries
Single-row
Single-row subquery
subquery
Main query
Subquery
returns
Multiple-row
Multiple-row subquery
subquery
CLERK
Main query
Subquery
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
>=
<
Less than
<=
<>
Not equal to
ENAME
DEPTNO
---------- --------KING
10
CLARK
10
MILLER
10
ENAME
MGR
---------- --------BLAKE
7839
CLARK
7839
JONES
7839
SELECT
FROM
WHERE
AND
ename, job
emp
job =
(SELECT
FROM
WHERE
sal >
(SELECT
FROM
WHERE
ENAME
JOB
---------- --------MILLER
CLERK
CLERK
job
emp
empno = 7369)
1100
sal
emp
empno = 7876);
ENAME
JOB
SAL
---------- --------- --------SMITH
CLERK
800
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
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
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
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
ENAME
SAL
DEPTNO
---------- --------- --------SMITH
800
20
JAMES
950
30
MILLER
1300
10
Controlling Transactions
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.
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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
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
Locking Modes
Lock Mode
Description
Exclusive lock
Share
Implicit Locking
User Action
SELECT ... FROM table ...
None
RX
RX
RX
None
DDL Operation
Explicit Locking
User Action
Row-Level lock
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
Overview of PL/SQL
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.
PL/SQL Environment
PL/SQL engine
PL/SQL
block
PL/SQL
block
PL/SQL
SQL
Procedural
Statement
Executor
Benefits of PL/SQL
yy Integration
Integration
Application
Shared
library
Oracle Server
Benefits of PL/SQL
yy Improve
Improve Performance
Performance
SQL
Application
Application
SQL
SQL
Other
Other DBMSs
DBMSs
SQL
Application
Application
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;
Benefits of PL/SQL
ItIt is
is portable.
portable.
You
You can
can declare
declare identifiers.
identifiers.
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.
Declaring Variables
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;
DECLARE
BEGIN
EXCEPTION
END;
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;
Program Constructs
Anonymous
Anonymous
block
block
Application
Application
trigger
trigger
DECLARE
BEGIN
EXCEPTION
Database
Database
trigger
trigger
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
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.
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
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
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
Atlanta
Copyright 2004, Oracle. All rights reserved.
Examples
Examples
Declare
Declare
v_hiredate
v_hiredate
v_deptno
v_deptno
v_location
v_location
c_comm
c_comm
DATE;
DATE;
NUMBER(2)
NUMBER(2) NOT
NOT NULL
NULL :=
:= 10;
10;
VARCHAR2(13)
VARCHAR2(13) :=
:= 'Atlanta';
'Atlanta';
CONSTANT
CONSTANT NUMBER
NUMBER :=
:= 1400;
1400;
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.
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;
emp
ename
ename == 'SMITH';
'SMITH';
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';
Assignment
Assignment operator
operator (:=)
(:=)
DEFAULT
DEFAULT keyword
keyword
NOT
NOT NULL
NULL constraint
constraint
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
256120.08
Atlanta
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
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
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;
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
Declaring Variables
with the %TYPE Attribute
yy Example
Example
...
...
v_ename
v_ename
v_balance
v_balance
v_min_balance
v_min_balance
...
...
emp.ename%TYPE;
emp.ename%TYPE;
NUMBER(7,2);
NUMBER(7,2);
v_balance%TYPE
v_balance%TYPE :=
:= 10;
10;
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.
Composite Datatypes
PL/SQL
PL/SQL TABLES
TABLES
PL/SQL
PL/SQL RECORDS
RECORDS
Bind Variables
O/S
Bind Variable
Server
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 (:).
(:).
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
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
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
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';
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
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
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
:=
:= 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');
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.
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.
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;
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 (**)
(**)
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
:=
:= (v_empno
(v_empno IS
IS NOT
NOT NULL);
NULL);
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
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.
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;
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;
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.
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
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;
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;
.. .. ..
FALSE
IF condition
THEN
THEN actions
actions
(including
)
(including further
further IFs
IFs)
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;
...
...
-- 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
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;
.. .. ..
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.
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
TRUE
NULL
NULL
AND
TRUE
FALSE
NULL
OR
TRUE
TRUE
FALSE
NULL
TRUE
NULL
NULL
FALSE
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
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
Basic Loop
yy Syntax
Syntax
LOOP
LOOP
statement1;
statement1;
.. .. ..
EXIT
EXIT [WHEN
[WHEN condition];
condition];
END
END LOOP;
LOOP;
where:
where:
condition
condition
-- 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;
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.
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.
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;
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.
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;
//
''
''
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.
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
Active set
Cursor
7369 SMITH
CLERK
7566 JONES
MANAGER
7788 SCOTT
ANALYST
7876 ADAMS
CLERK
7902 FORD
ANALYST
Current row
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
the active
set
Cursor
Copyright 2004, Oracle. All rights reserved.
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.
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.
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.
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;
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.
Type
Description
%ISOPEN
Boolean
%NOTFOUND
Boolean
%FOUND
Boolean
%ROWCOUNT
Number
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...
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.
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.
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;
...
...
cursors.
cursors.
Implicit
Implicit open,
open, fetch,
fetch, and
and close
close occur.
occur.
The
The record
record is
is implicitly
implicitly declared.
declared.
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;
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.
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;
Handling Exceptions
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.
Handling Exceptions
y Trap the exception
Exception
is raised
DECLARE
DECLARE
BEGIN
BEGIN
EXCEPTION
EXCEPTION
Exception
is trapped END;
END;
Exception
is raised
Exception is
not trapped
Exception
propagates to calling
environment
Exception Types
Predefined
Predefined Oracle
Oracle Server
Server
Non-predefined
Non-predefined Oracle
Oracle Server
Server
User-defined
User-defined
Implicitly
raised
Explicitly raised
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;
.. .. .]
.]
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.
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
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;
Declare
Associate
Declarative section
Name the
exception
Reference
Exception-handling
section
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
Declare
Raise
Reference
Declarative
section
Executable
section
Exception-handling
section
Name the
exception
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;
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
NUMBER;
VARCHAR2(255);
SQLCODE ;
:= SQLERRM ;
Calling Environments
SQL*Plus
Procedure
Builder
Oracle
Developer
Forms
Precompiler
application
An enclosing
PL/SQL block
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
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
Package
Trigger
Managing Dependencies
Q U E S T
A N S W
I O N S
E R S