Oracle 9i SQL & PLSQL
Oracle 9i SQL & PLSQL
2
Oracle 9i Course – Target Audience
• Officers from any of the streams:
Engineering
Accounts
Administration
5
System Development Life Cycle
Strategy
and
Analysis
Design
Build
and
Document
Transition
Production
6
Data Storage on Different Media
SALGRADE
GRADE LOSAL HISAL
--------- --------- ---------
DEPT
1 700 1200
DEPTNO DNAME LOC
2 1201 1400
--------- -------------- ----------
3 1401 2000
10 ACCOUNTING NEW
4 2001 3000
YORK
5 3001 9999
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Database
9
Relational Database Definition
A relational database is a collection of
relations or two-dimensional tables.
Database
10
Data Models
Model of
system
in client’s Entity model of
mind client’s model
Table model
of entity model
Server
Tables on disk
11
Entity Relationship Model
• Create an entity relationship diagram from
business specifications or narratives
• Scenario
– “. . . Assign one or more employees to a
department . . .”
– “. . . Some departments do not yet have
assigned employees . . .”
12
Entity Relationship Modeling
Conventions
Entity Attribute
Soft box Singular name
Singular, unique name Lowercase
Uppercase Mandatory marked with “*”
Synonym in parentheses Optional marked with “o”
15
Relating Multiple Tables
• Each row of data in a table is uniquely
identified by a primary key (PK).
• You can logically relate data from
multiple tables using foreign keys (FK).
Table Name: EMP Table Name: DEPT
EMPNO ENAME JOB DEPTNO DEPTNO DNAME LOC
7839 KING PRESIDENT 10 10 ACCOUNTING NEW YORK
7698 BLAKE MANAGER 30 20 RESEARCH DALLAS
7782 CLARK MANAGER 10 30 SALES CHICAGO
7566 JONES MANAGER 20 40 OPERATIONS BOSTON
A relational database
• Can be accessed and modified by
executing structured query language
(SQL) statements
• Contains a collection of tables with no
physical pointers
• Uses a set of operators
17
Communicating with a RDBMS
Using SQL
SQL statement
is entered Statement is sent to
SQL> SELECT loc database
2 FROM dept;
Database
Data is displayed
LOC
-------------
NEW YORK
DALLAS
CHICAGO
BOSTON
18
Relational Database
Management System
Server
20
Defining an Object
An object
• Is a person, place, or thing
• Knows things about itself and performs
actions
• Has an identity
I am a clock. I know
my time zone, and I
can display time.
21
Using an Object Model
• Objects model a problem to solve.
• The model is stated in terms of the
interactions between objects.
• Object models closely resemble the real
world.
Buy
Sell
Customers Business
22
Characteristics of Object systems
• Present information in object form
• Classify objects into object types
• Inherit attributes and code
• Hide data, code, and attributes
• Interact with other objects
• Recognize different objects without
analysis
• Interpret the same command in
different ways
23
Welcome to Oracle 9i
Availability
Scalability &
Performance
Security
Manageability
24
Oracle Complete Solution
Applications Developer 2K
HR
Financials
Manufacturing Application Server Web Clients
...
Database Data
dictionary
Data tables
25
SQL Statements
SELECT Data retrieval
INSERT
UPDATE Data manipulation language (DML)
DELETE
CREATE
ALTER
DROP Data definition language (DDL)
RENAME
TRUNCATE
COMMIT
ROLLBACK Transaction control
SAVEPOINT
27
PL/SQL Environment
PL/SQL engine
PL/SQL Procedural
PL/SQL PL/SQL
block block SQL Statement
Executor
Oracle Server
28
Benefits of PL/SQL
Integration
Application
29
Benefits of PL/SQL
Improve Performance
SQL
SQL
Application Other DBMSs
SQL
SQL
SQL
IF...THEN
SQL Oracle with
Application ELSE PL/SQL
SQL
END IF;
SQL
30
Benefits of PL/SQL
Modularize program development
Stored
Anonymous
procedure/
block
DECLARE function
BEGIN Application
Application
procedure/
trigger
function
EXCEPTION
Database
END; Packaged
trigger procedure
31
Benefits of PL/SQL
• It is portable.
• You can declare identifiers.
• You can program with procedural
language control structures.
• It can handle errors.
32
Benefits of PL/SQL
• It is portable.
• You can declare identifiers.
• You can program with procedural
language control structures.
• It can handle errors.
33
Tables Used in the Course
EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 1500 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
DEPT 7900 JAMES CLERK 7698 03-DEC-81 950 30
DEPTNO 7521
DNAMEWARD SALESMAN
LOC 7698 22-FEB-81 1250 500 30
--------- 7902 FORD
-------------- ANALYST
---------- 7566 03-DEC-81 SALGRADE
3000 20
7369 10
SMITH CLERK NEW
ACCOUNTING 7902 17-DEC-80 800
GRADE LOSAL 20
HISAL
YORK 7788 SCOTT ANALYST 7566 09-DEC-82 3000
--------- 20
--------- ---------
20 7876 ADAMS
RESEARCH CLERK
DALLAS 7788 12-JAN-83 1100 1 700 20
1200
30 7934
SALESMILLER CLERK
CHICAGO 7782 23-JAN-82 1300 2 1201 10
1400
40 OPERATIONS BOSTON 3 1401 2000
4 2001 3000
5 3001 9999
34
SQL Example
• Distance Calculator:
To write a function that
calculates the radial distance
between two towns in AP State
given the data of latitudes and
longitudes of different places
in AP.
36
Data for the distance calculator
Approx. values of Latitude and
Longitude in Radians
37
PL-SQL Example
Create FUNCTION get_geo_distance
(lat1 IN NUMBER, lon1 IN NUMBER,lat2 IN NUMBER, lon2 IN NUMBER)
RETURN NUMBER
IS
v_r NUMBER :=6378.7;
BEGIN
IF lat1=lat2 AND lon1=lon2 THEN
RETURN 0;
END IF;
RETURN v_r * ACOS( SIN(lat1) * SIN(lat2) + COS(lat1) * COS(lat2) *
COS(lon2- lon1) );
EXCEPTION WHEN OTHERS
THEN RETURN NULL;
END;
38
Summary
• Relational databases are composed of
relations, managed by relational
operations, and governed by data
integrity constraints.
• Oracle Server allows you to store and
manage information by using the SQL
language and PL/SQL engine.
• PL/SQL is an extension to SQL with
design features of programming
languages.
39
Writing Basic
SQL Statements
Objectives
42
Capabilities of SQL SELECT
Statements
Selection Projection
Table 1 Table 1
Join
Table 1 Table 2
43
Basic SELECT Statement
44
Writing SQL Statements
SQL> SELECT *
2 FROM dept;
46
Selecting Specific Columns
DEPTNO LOC
--------- -------------
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
47
Column Heading Defaults
• Default justification
– Left: Date and character data
– Right: Numeric data
• Default display: Uppercase
48
Arithmetic Expressions
Create expressions on NUMBER and DATE
data by using arithmetic operators.
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
49
Using Arithmetic Operators
50
Operator Precedence
_
* / +
• Multiplication and division take priority
over addition and subtraction.
• Operators of the same priority are
evaluated from left to right.
• Parentheses are used to force
prioritized evaluation and to clarify
statements.
51
Operator Precedence
52
Using Parentheses
53
Defining a Null Value
• A null is a value that is unavailable,
unassigned, unknown, or inapplicable.
• A null is not the same as zero or a blank
space.
SQL> SELECT ename, job, comm
2 FROM emp;
NAME 12*SAL+COMM
---------- -----------
KING
55
Defining a Column Alias
56
Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM emp;
NAME SALARY
------------- ---------
...
58
Using the Concatenation
Operator
SQL> SELECT ename||job AS "Employees"
2 FROM emp;
Employees
-------------------
KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN
...
14 rows selected.
59
Literal Character Strings
60
Using Literal Character Strings
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.
61
Duplicate Rows
The default display of queries is all rows,
including duplicate rows.
SQL> SELECT deptno
2 FROM emp;
DEPTNO
---------
10
30
10
20
...
14 rows selected.
62
Eliminating Duplicate Rows
Eliminate duplicate rows by using the
DISTINCT keyword in the SELECT clause.
SQL> SELECT DISTINCT deptno
2 FROM emp;
DEPTNO
---------
10
20
30
63
SQL and SQL*Plus Interaction
SQL Statements SQL Statements
Buffer
Server
SQL*Plus
64
SQL Statements Versus
SQL*Plus Commands
SQL SQL*Plus
• A language • An environment
• ANSI standard • Oracle proprietary
• Keyword cannot be • Keywords can be
abbreviated abbreviated
• Statements manipulate • Commands do not
data and table allow manipulation of
definitions in the values in the database
database
65
Overview of SQL*Plus
• Log in to SQL*Plus.
• Describe the table structure.
• Edit your SQL statement.
• Execute SQL from SQL*Plus.
• Save SQL statements to files and
append SQL statements to files.
• Execute saved files.
• Load commands from file to buffer
to edit.
66
Logging In to SQL*Plus
• From Windows environment:
DESC[RIBE] tablename
68
Displaying Table Structure
69
SQL*Plus Editing Commands
• A[PPEND] text
• C[HANGE] / old / new
• C[HANGE] / text /
• CL[EAR] BUFF[ER]
• DEL
• DEL n
• DEL m n
70
SQL*Plus Editing Commands
• I[NPUT]
• I[NPUT] text
• L[IST]
• L[IST] n
• L[IST] m n
• R[UN]
• n
• n text
• 0 text
71
SQL*Plus File Commands
• SAVE filename
• GET filename
• START filename
• @ filename
• EDIT filename
• SPOOL filename
72
Summary
73
Practice Overview
74
Restricting and Sorting Data
Objectives
77
Limiting Rows Using a Selection
EMP
EMPNO ENAME JOB ... DEPTNO
"…retrieve all
7839 KING PRESIDENT 10 employees
7698 BLAKE MANAGER 30 in department 10"
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...
EMP
EMPNO ENAME JOB ... DEPTNO
78
Limiting Rows Selected
• Restrict the rows returned by using the
WHERE clause.
79
Using the WHERE Clause
80
Character Strings and Dates
• Character strings and date values are
enclosed in single quotation marks
• Character values are case-sensitive and
date values are format-sensitive
• Default date format is 'DD-MON-YY'
81
Comparison Operators
Operator Meaning
= Equal to
82
Using the Comparison
Operators
83
Other Comparison Operators
Operator Meaning
84
Using the BETWEEN Operator
Use the BETWEEN operator to display
rows based on a range of values.
SQL> SELECT ename, sal
2 FROM emp
3 WHERE sal BETWEEN 1000 AND 1500;
ENAME SAL
---------- --------- Lower Higher
MARTIN 1250 limit limit
TURNER 1500
WARD 1250
ADAMS 1100
MILLER 1300
85
Using the IN Operator
Use the IN operator to test for values in a
list.
86
Using the LIKE Operator
• Use the LIKE operator to perform
wildcard searches of valid search string
values.
• Search conditions can contain either
literal characters or numbers.
– % denotes zero or many characters
– _ denotes one character
87
Using the LIKE Operator
ENAME
----------
JAMES
WARD
ENAME MGR
---------- ---------
KING
89
Logical Operators
Operator Meaning
90
Using the AND Operator
AND requires both conditions to be TRUE.
91
Using the OR Operator
OR requires either condition to be TRUE.
SQL> SELECT empno, ename, job, sal
2 FROM emp
3 WHERE sal>=1100
4 OR job='CLERK';
ENAME JOB
---------- ---------
KING PRESIDENT
MARTIN SALESMAN
ALLEN SALESMAN
TURNER SALESMAN
WARD SALESMAN
93
Rules of Precedence
94
Rules of Precedence
SQL> SELECT ename, job, sal
2 FROM emp
3 WHERE job='SALESMAN'
4 OR job='PRESIDENT'
5 AND sal>1500;
95
Rules of Precedence
Use parentheses to force priority.
SQL> SELECT ename, job, sal
2 FROM emp
3 WHERE (job='SALESMAN'
4 OR job='PRESIDENT')
5 AND sal>1500;
96
ORDER BY Clause
• Sort rows with the ORDER BY clause
– ASC: ascending order, default
– DESC: descending order
• The ORDER BY clause comes last in the
SELECT statement.
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate;
98
Sorting by Column Alias
SQL> SELECT empno, ename, sal*12 annsal
2 FROM emp
3 ORDER BY annsal;
99
Sorting by Multiple Columns
• The order of ORDER BY list is the order of
sort.
SQL> SELECT ename, deptno, sal
2 FROM emp
3 ORDER BY deptno, sal DESC;
101
Practice Overview
102
Single-Row Functions
Objectives
105
SQL Functions
Input Output
Function
arg 1 Function
performs action
arg 2
Result
value
arg n
106
Two Types of SQL Functions
Functions
Single-row Multiple-row
functions functions
107
Single-Row Functions
• Manipulate data items
• Accept arguments and return one value
• Act on each row returned
• Return one result per row
• May modify the datatype
• Can be nested
function_name (column|expression, [arg1, arg2,...])
108
Single-Row Functions
Character
General Number
Single-row
functions
Conversion Date
109
Character Functions
Character
functions
111
Using Case Conversion Functions
Display the employee number, name, and
department number for employee Blake.
SQL> SELECT empno, ename, deptno
2 FROM emp
3 WHERE ename = 'blake';
no rows selected
112
Character Manipulation Functions
113
Using the Character
Manipulation Functions
114
Number Functions
• ROUND: Rounds value to specified
decimal
ROUND(45.926, 2) 45.93
• TRUNC: Truncates value to specified
decimal
TRUNC(45.926, 2) 45.92
115
Using the ROUND Function
116
Using the TRUNC Function
117
Using the MOD Function
Calculate the remainder of the ratio of
salary to commission for all employees
whose job title is a salesman.
118
Working with Dates
• Oracle stores dates in an internal
numeric format: Century, year, month,
day, hours, minutes, seconds.
• The default date format is DD-MON-YY.
• SYSDATE is a function returning date
and time.
• DUAL is a dummy table used to view
SYSDATE.
119
Arithmetic with Dates
120
Using Arithmetic Operators
with Dates
ENAME WEEKS
---------- ---------
KING 830.93709
CLARK 853.93709
MILLER 821.36566
121
Date Functions
FUNCTION DESCRIPTION
Number of months
MONTHS_BETWEEN between two dates
Add calendar months to
ADD_MONTHS date
Next day of the date
NEXT_DAY specified
122
Using Date Functions
• MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')
19.6774194
• LAST_DAY('01-SEP-95') '30-SEP-95'
123
Using Date Functions
• ROUND('25-JUL-95','MONTH') 01-AUG-95
• ROUND('25-JUL-95','YEAR') 01-JAN-96
• TRUNC('25-JUL-95','MONTH') 01-JUL-95
• TRUNC('25-JUL-95','YEAR') 01-JAN-
95
124
Conversion Functions
Datatype
conversion
125
Implicit Datatype Conversion
NUMBER VARCHAR2
DATE VARCHAR2
126
Implicit Datatype Conversion
127
Explicit Datatype Conversion
TO_NUMBER TO_DATE
TO_CHAR TO_CHAR
128
TO_CHAR Function with Dates
TO_CHAR(date, 'fmt')
130
Date Format Model Elements
131
Using TO_CHAR Function
with Dates
SQL> SELECT ename,
2 TO_CHAR(hiredate, 'fmDD Month YYYY') 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.
132
TO_CHAR Function with Numbers
TO_CHAR(number, 'fmt')
SALARY
--------
$3,000
134
TO_NUMBER and TO_DATE
Functions
• Convert a character string to a number
format using the TO_NUMBER function
TO_NUMBER(char)
TO_DATE(char[, 'fmt'])
135
RR Date Format
Current Year Specified Date RR Format YY Format
1995 27-OCT-95 1995 1995
1995 27-OCT-17 2017 1917
2001 27-OCT-17 2017 2017
2001 27-OCT-95 1995 2095
0-49 50-99
If two digits The return date is in The return date is in
of the 0-49 the current century. the century before
current the current one.
year are The return date is The return date is in
50-99 in the century after the current century.
the current one.
136
NVL Function
137
Using the NVL Function
138
DECODE Function
139
Using the DECODE Function
140
Nesting Functions
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
141
Nesting Functions
ENAME NVL(TO_CHAR(MGR),'NOMANAGER')
---------- -----------------------------
KING No Manager
142
Summary
143
Practice Overview
145
Displaying Data
from Multiple Tables
Objectives
147
Obtaining Data from Multiple Tables
EMP DEPT
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON
148
What Is a Join?
Use a join to query data from more than
one table.
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
150
Generating a Cartesian Product
EMP (14 rows) DEPT (4 rows)
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON
ENAME DNAME
------ ----------
KING ACCOUNTING
“Cartesian BLAKE ACCOUNTING
product: ...
KING RESEARCH
14*4=56 rows” BLAKE RESEARCH
...
56 rows selected.
151
Types of Joins
152
What Is an Equijoin?
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
------ ------- ------- ------- ---------- --------
7839 KING 10 10 ACCOUNTING NEW YORK
7698 BLAKE 30 30 SALES CHICAGO
7782 CLARK 10 10 ACCOUNTING NEW YORK
7566 JONES 20 20 RESEARCH DALLAS
7654 MARTIN 30 30 SALES CHICAGO
7499 ALLEN 30 30 SALES CHICAGO
7844 TURNER 30 30 SALES CHICAGO
7900 JAMES 30 30 SALES CHICAGO
7521 WARD 30 30 SALES CHICAGO
7902 FORD 20 20 RESEARCH DALLAS
7369 SMITH 20 20 RESEARCH DALLAS
... ...
14 rows selected. 14 rows selected.
154
Qualifying Ambiguous
Column Names
• Use table prefixes to qualify column
names that are in multiple tables.
• Improve performance by using table
prefixes.
• Distinguish columns that have identical
names but reside in different tables by
using column aliases.
155
Additional Search Conditions
Using the AND Operator
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
------ ------- ------- ------ --------- --------
7839 KING 10 10 ACCOUNTING NEW YORK
7698 BLAKE 30 30 SALES CHICAGO
7782 CLARK 10 10 ACCOUNTING NEW YORK
7566 JONES 20 20 RESEARCH DALLAS
7654 MARTIN 30 30 SALES CHICAGO
7499 ALLEN 30 30 SALES CHICAGO
7844 TURNER 30 30 SALES CHICAGO
7900 JAMES 30 30 SALES CHICAGO
7521 WARD 30 30 SALES CHICAGO
7902 FORD 20 20 RESEARCH DALLAS
7369 SMITH 20 20 RESEARCH DALLAS
... ...
14 rows selected. 14 rows selected.
156
Using Table Aliases
Simplify queries by using table aliases.
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;
157
Joining More Than Two Tables
CUSTOMER ORD
NAME CUSTID CUSTID ORDID
----------- ------ ------- -------
JOCKSPORTS 100 101 610
TKB SPORT SHOP 101 102 611
VOLLYRITE 102 104 612
JUST TENNIS 103 106 601
K+T SPORTS 105 102 602 ITEM
SHAPE UP 106 106 604
ORDID ITEMID
WOMENS SPORTS 107 106 605
------ -------
... ... ...
610 3
9 rows selected. 21 rows selected.
611 1
612 1
601 1
602 1
...
64 rows selected.
158
Non-Equijoins
EMP SALGRADE
EMPNO ENAME SAL GRADE LOSAL HISAL
------ ------- ------ ----- ----- ------
7839 KING 5000 1 700 1200
7698 BLAKE 2850 2 1201 1400
7782 CLARK 2450 3 1401 2000
7566 JONES 2975 4 2001 3000
7654 MARTIN 1250 5 3001 9999
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
... “salary in the EMP
14 rows selected. table is between
low salary and high
salary in the SALGRADE
table”
159
Retrieving Records
with Non-Equijoins
SQL> SELECT e.ename, e.sal, s.grade
2 FROM emp e, salgrade s
3 WHERE e.sal
4 BETWEEN s.losal AND s.hisal;
160
Outer Joins
EMP DEPT
ENAME DEPTNO DEPTNO DNAME
----- ------ ------ ----------
KING 10 10 ACCOUNTING
BLAKE 30 30 SALES
CLARK 10 10 ACCOUNTING
JONES 20 20 RESEARCH
... ...
40 OPERATIONS
No employee in the
OPERATIONS department
161
Outer Joins
• You use an outer join to also see rows
that do not usually meet the join
condition.
• Outer join operator is the plus sign (+).
SELECT table.column, table.column
FROM table1, table2
WHERE table1.column(+) = table2.column;
162
Using Outer Joins
SQL> SELECT e.ename, d.deptno, d.dname
2 FROM emp e, dept d
3 WHERE e.deptno(+) = d.deptno
4 ORDER BY e.deptno;
163
Self Joins
EMP (WORKER) EMP (MANAGER)
EMPNO ENAME MGR EMPNO ENAME
----- ------ ---- ----- --------
7839 KING
7698 BLAKE 7839 7839 KING
7782 CLARK 7839 7839 KING
7566 JONES 7839 7839 KING
7654 MARTIN 7698 7698 BLAKE
7499 ALLEN 7698 7698 BLAKE
164
Joining a Table to Itself
SQL> SELECT worker.ename||' works for '||manager.ename
2 FROM emp worker, emp manager
3 WHERE worker.mgr = manager.empno;
WORKER.ENAME||'WORKSFOR'||MANAG
-------------------------------
BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.
165
Summary
166
Practice Overview
167
Aggregating Data
Using Group Functions
Objectives
170
What Are Group Functions?
Group functions operate on sets of rows to give
one result per group.
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000 “maximum MAX(SAL)
20 3000 salary in ---------
20 2975 the EMP table” 5000
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
171
Using AVG and SUM Functions
You can use AVG and SUM for numeric data.
SQL> SELECT AVG(sal), MAX(sal),
2 MIN(sal), SUM(sal)
3 FROM emp
4 WHERE job LIKE 'SALES%';
174
Using MIN and MAX Functions
You can use MIN and MAX for any datatype.
MIN(HIRED MAX(HIRED
--------- ---------
17-DEC-80 12-JAN-83
175
Using the COUNT Function
COUNT(*) returns the number of rows in a
table.
SQL> SELECT COUNT(*)
2 FROM emp
3 WHERE deptno = 30;
COUNT(*)
---------
6
176
Using the COUNT Function
COUNT(expr) returns the number of
nonnull rows.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;
COUNT(COMM)
-----------
4
177
Group Functions and Null Values
Group functions ignore null values in the
column.
SQL> SELECT AVG(comm)
2 FROM emp;
AVG(COMM)
---------
550
178
Using the NVL Function
with Group Functions
The NVL function forces group functions
to include null values.
AVG(NVL(COMM,0))
----------------
157.14286
179
Creating Groups of Data
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 2916.6667
10 1300
20 800 “average DEPTNO AVG(SAL)
20 1100 salary
------- ---------
20 3000 2175 in EMP
20 3000 table 10 2916.6667
20 2975 for each 20 2175
30 1600 department” 30 1566.6667
30 2850
30 1250 1566.6667
30 950
30 1500
30 1250
180
Creating Groups of Data:
GROUP BY Clause
181
Using the GROUP BY Clause
All columns in the SELECT list that are not
in group functions must be in the GROUP
BY clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 GROUP BY deptno;
DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
30 1566.6667
182
Using the GROUP BY Clause
The GROUP BY column does not have to
be in the SELECT list.
SQL> SELECT AVG(sal)
2 FROM emp
3 GROUP BY deptno;
AVG(SAL)
---------
2916.6667
2175
1566.6667
183
Grouping by More
EMP
Than One Column
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
DEPTNO JOB SUM(SAL)
10 PRESIDENT 5000
-------- --------- ---------
10 CLERK 1300
10 CLERK 1300
20 CLERK 800 “sum salaries in 10 MANAGER 2450
20 CLERK 1100 the EMP table
10 PRESIDENT 5000
20 ANALYST 3000 for each job,
20 ANALYST 6000
20 ANALYST 3000 grouped by
20 CLERK 1900
20 MANAGER 2975 department”
20 MANAGER 2975
30 SALESMAN 1600
30 CLERK 950
30 MANAGER 2850
30 MANAGER 2850
30 SALESMAN 1250
30 SALESMAN 5600
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250
184
Using the GROUP BY Clause
on Multiple Columns
SQL> SELECT deptno, job, sum(sal)
2 FROM emp
3 GROUP BY deptno, job;
185
Illegal Queries
Using Group Functions
Any column or expression in the SELECT
list that is not an aggregate function must
s e
be in the GROUP BY clause. au cl
BY
SQL> SELECT deptno, COUNT(ename) UP
2 FROM emp; RO
G
e
th
SELECT deptno, COUNT(ename) in
n g
* s i
ERROR at line 1: i s
m
ORA-00937: not ansingle-group group function
l um
Co
186
Illegal Queries
Using Group Functions
• You cannot use the WHERE clause to restrict
groups.
• You use the HAVING clause to restrict groups.
SQL> SELECT deptno, AVG(sal)
s e
2 FROM emp l a u
3 WHERE AVG(sal) > 2000 c
RE
4 GROUP BY deptno; s
HE oup
e W r
WHERE AVG(sal) > 2000 t h ct g
* s e tri
t u e s
ERROR at line 3:
n o to r
a n
ORA-00934: group function is not allowed here
C
187
Excluding Group Results
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 5000
10 1300
20 800
20 1100 “maximum DEPTNO MAX(SAL)
20 3000 salary --------- ---------
3000
20 3000 per department 10 5000
20 2975 greater than 20 3000
30 1600 $2900”
30 2850
30 1250
30 950
2850
30 1500
30 1250
188
Excluding Group Results:
HAVING Clause
Use the HAVING clause to restrict groups
– Rows are grouped.
– The group function is applied.
– Groups matching the HAVING clause
are displayed.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
189
Using the HAVING Clause
DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
190
Using the HAVING Clause
JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
191
Nesting Group Functions
Display the maximum average salary.
MAX(AVG(SAL))
-------------
2916.6667
192
Summary
SELECT column, group_function (column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
193
Practice Overview
194
Oracle 9i SQL
PPT: 2/3 & 3/3
Subqueries
Objectives
198
Using a Subquery
to Solve a Problem
“Who has a salary greater than Jones’s?”
Main Query
Subquery
?
“What is Jones’s salary?”
199
Subqueries
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
200
Using a Subquery
SQL> SELECT ename
2 FROM emp 2975
3 WHERE sal >
4 (SELECT sal
5 FROM emp
6 WHERE empno=7566);
ENAME
----------
KING
FORD
SCOTT
201
Guidelines for Using Subqueries
• Enclose subqueries in parentheses.
• Place subqueries on the right side of the
comparison operator.
• Do not add an ORDER BY clause to a
subquery.
• Use single-row operators with single-
row subqueries.
• Use multiple-row operators with
multiple-row subqueries.
202
Types of Subqueries
• Single-row subquery
Main query
returns
Subquery CLERK
• Multiple-row subquery
Main query
Subquery
returns CLERK
MANAGER
• Multiple-column subquery
Main query
returns
Subquery CLERK 7900
MANAGER 7698
203
Single-Row Subqueries
• Return only one row
• Use single-row comparison operators
Operator Meaning
= Equal to
204
Executing Single-Row Subqueries
SQL> SELECT ename, job
2 FROM emp
3 WHERE job = CLERK
4 (SELECT job
5 FROM emp
6 WHERE empno = 7369)
7 AND sal > 1100
8 (SELECT sal
9 FROM emp
10 WHERE empno = 7876);
ENAME JOB
---------- ---------
MILLER CLERK
205
Using Group Functions
in a Subquery
SQL> SELECT ename, job, sal
800
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp);
206
HAVING Clause with Subqueries
• The Oracle Server executes subqueries
first.
• The Oracle Server returns results into
the main query’s HAVING clause.
SQL> SELECT deptno, MIN(sal)
2 FROM emp
3 GROUP BY deptno
800
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM emp
7 WHERE deptno = 20);
207
What Is Wrong
with This Statement? e r y
qu
SQL> SELECT empno, ename b
2 FROM emp su
3 WHERE sal = ow
4 (SELECT -
MIN(sal)r
p le
5 FROM
l t i
emp
6 GROUP BYu deptno);
m
ith
r w
ERROR:
t o
ORA-01427: single-row rasubquery returns more than
one row pe
o
ow
no rows selected
e-r
gl
i n
S
208
Will This Statement Work?
209
Multiple-Row Subqueries
• Return more than one row
• Use multiple-row comparison operators
Operator Meaning
210
Using ANY Operator
in Multiple-Row Subqueries
SQL> SELECT empno, ename, job 1300
2 FROM emp 1100
800
3 WHERE sal < ANY 950
4 (SELECT sal
5 FROM emp
6 WHERE job = 'CLERK')
7 AND job <> 'CLERK';
211
Using ALL Operator
in Multiple-Row Subqueries
SQL> SELECT empno, ename, job 1566.6667
2 FROM emp 2175
2916.6667
3 WHERE sal > ALL
4 (SELECT avg(sal)
5 FROM emp
6 GROUP BY deptno);
212
Summary
Subqueries are useful when a query is
based on unknown values.
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
213
Practice Overview
214
Producing Readable Output
with SQL*Plus
Objectives
216
Interactive Reports
User
217
Substitution Variables
218
Using the & Substitution Variable
Use a variable prefixed with an ampersand
(&) to prompt the user for a value.
SQL> SELECT empno, ename, sal, deptno
2 FROM emp
3 WHERE empno = &employee_num;
219
Using the SET VERIFY Command
Toggling the display of the text of a
command before and after SQL*Plus
replaces substitution variables with values.
SQL> SET VERIFY ON
SQL> SELECT empno, ename, sal, deptno
2 FROM emp
3 WHERE empno = &employee_num;
...
220
Character and Date Values
with Substitution Variables
Use single quotation marks for date and
character values.
SQL> SELECT ename, deptno, sal*12
2 FROM emp
3 WHERE job='&job_title';
221
Specifying Column Names,
Expressions, and Text at Runtime
Use substitution variables to supplement
• A WHERE condition
• An ORDER BY clause
• A column expression
• A table name
• An entire SELECT statement
222
Specifying Column Names,
Expressions, and Text at Runtime
SQL> SELECT empno, ename, job, &column_name
2 FROM emp
3 WHERE &condition
4 ORDER BY &order_column;
223
Using the && Substitution Variable
Use the double-ampersand (&&) if you
want to reuse the variable value without
prompting the user each time.
SQL> SELECT empno, ename, job, &&column_name
2 FROM emp
3 ORDER BY &column_name;
226
Using the ACCEPT Command
227
DEFINE and UNDEFINE Commands
• A variable remains defined until you either:
– Use the UNDEFINE command to clear it
– Exit SQL*Plus
• You can verify your changes with the
DEFINE command.
• To define variables for every session,
modify your login.sql file so that the
variables are created at startup.
228
Using the DEFINE Command
• Create a variable to hold the department
name.
SQL> DEFINE deptname = sales
SQL> DEFINE deptname
229
Customizing the SQL*Plus
Environment
• Use SET commands to control current
session.
SET system_variable value
230
SET Command Variables
• ARRAYSIZE {20 | n}
• COLSEP {_ | text}
• FEEDBACK {6 | n |OFF | ON}
• HEADING {OFF | ON}
• LINESIZE {80 | n}
• LONG {80 | n}
• PAGESIZE {24 | n}
• PAUSE {OFF | ON | text}
• TERMOUT {OFF | ON}
231
Saving Customizations
in the login.sql File
• The login.sql file contains standard SET
and other SQL*Plus commands that are
implemented at login.
• You can modify login.sql to contain
additional SET commands.
232
SQL*Plus Format Commands
233
The COLUMN Command
Controls display of a column
COL[UMN] [{column|alias} [option]]
235
COLUMN Format Models
236
Using the BREAK Command
Suppresses duplicates and sections rows
• To suppress duplicates
SQL> BREAK ON ename ON job
237
Using the TTITLE and BTITLE
Commands
Display headers and footers
TTI[TLE] [text|OFF|ON]
238
Creating a Script File
to Run a Report
1. Create the SQL SELECT statement.
2. Save the SELECT statement to a
script file.
3. Load the script file into an editor.
4. Add formatting commands before the
SELECT statement.
5. Verify that the termination character
follows the SELECT statement.
239
Creating a Script File
to Run a Report
6. Clear formatting commands after the
SELECT statement.
7. Save the script file.
8. Enter “START filename” to run the
script.
240
Sample Report
Fri Oct 24 page 1
Employee
Report
Job
Category Employee Salary
----------------------- ----------------------- -----------------
CLERK ADAMS $1,100.00
CLERK JAMES $950.00
CLERK MILLER $1,300.00
CLERK SMITH $800.00
MANAGER BLAKE $2,850.00
MANAGER CLARK $2,450.00
MANAGER JONES $2,975.00
SALESMAN ALLEN $1,600.00
SALESMAN MARTIN $1,250.00
SALESMAN TURNER $1,500.00
SALESMAN WARD $1,250.00
Confidential
241
Summary
• Use SQL*Plus substitution variables to
temporarily store values.
• Use SET commands to control current
SQL*Plus environment.
• Use the COLUMN command to control
the display of a column.
• Use the BREAK command to suppress
duplicates and section rows.
• Use TTITLE and BTITLE to display
headers and footers.
242
Practice Overview
243
Manipulating Data
Objectives
245
Data Manipulation Language
246
Adding a New Row to a Table
50 DEVELOPMENT DETROIT
New row
“…insert a new row
DEPT
into DEPT table…”
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS DEPT
30 SALES CHICAGO DEPTNO DNAME LOC
40 OPERATIONS BOSTON ------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 DEVELOPMENT DETROIT
247
The INSERT Statement
248
Inserting New Rows
250
Inserting Special Values
The SYSDATE function records the
current date and time.
251
Inserting Specific Date Values
• Add a new employee.
SQL> INSERT INTO emp
2 VALUES (2296,'AROMANO','SALESMAN',7782,
3 TO_DATE('FEB 3,97', 'MON DD, YY'),
4 1300, NULL, 10);
1 row created.
252
Inserting Values by Using
Substitution Variables
Create an interactive script by using
SQL*Plus substitution parameters.
SQL> INSERT INTO dept (deptno, dname, loc)
2 VALUES (&department_id,
3 '&department_name', '&location');
1 row created.
253
Creating a Script
with Customized Prompts
• ACCEPT stores the value into a variable.
• PROMPT displays your customized text.
ACCEPT department_id PROMPT 'Please enter the -
department number:'
ACCEPT department_name PROMPT 'Please enter -
the department name:'
ACCEPT location PROMPT 'Please enter the -
location:'
INSERT INTO dept (deptno, dname, loc)
VALUES (&department_id, '&department_name',
'&location');
254
Copying Rows
from Another Table
• Write your INSERT statement with a
subquery.
SQL> INSERT INTO managers(id, name, salary, hiredate)
2 SELECT empno, ename, sal, hiredate
3 FROM emp
4 WHERE job = 'MANAGER';
3 rows created.
EMP
EMPNO ENAME JOB ... DEPTNO
256
The UPDATE Statement
257
Updating Rows in a Table
• Specific row or rows are modified when
you specify the WHERE clause.
SQL> UPDATE emp
2 SET deptno = 20
3 WHERE empno = 7782;
1 row updated.
258
Updating with
Multiple-Column Subquery
Update employee 7698’s job and department
to match that of employee 7499.
SQL> UPDATE emp
2 SET (job, deptno) =
3 (SELECT job, deptno
4 FROM emp
5 WHERE empno = 7499)
6 WHERE empno = 7698;
1 row updated.
259
Updating Rows Based
on Another Table
Use subqueries in UPDATE statements to
update rows in a table based on values
from another table.
SQL> UPDATE employee
2 SET deptno = (SELECT deptno
3 FROM emp
4 WHERE empno = 7788)
5 WHERE job = (SELECT job
6 FROM emp
7 WHERE empno = 7788);
2 rows updated.
260
Updating Rows:
Integrity Constraint Error
261
Removing a Row from a Table
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS “…delete a row
30 SALES CHICAGO
40 OPERATIONS BOSTON from DEPT table…”
50 DEVELOPMENT DETROIT
60 MIS DEPT
...
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
60 MIS
...
262
The DELETE Statement
263
Deleting Rows from a Table
• Specific row or rows are deleted when
you specify the WHERE clause.
264
Deleting Rows Based
on Another Table
Use subqueries in DELETE statements to
remove rows from a table based on values
from another table.
SQL> DELETE FROM employee
2 WHERE deptno =
3 (SELECT deptno
4 FROM dept
5 WHERE dname ='SALES');
6 rows deleted.
265
Deleting Rows:
Integrity Constraint Error
ary .
r im able
a p rt
SQL> DELETE FROM dept s h e
i n t
2 WHERE deptno = 10; nta ano
co in
at ey
th n k
DELETE FROM dept r ow eig
a or
*
te a f
ERROR at line 1: le
de as
t
ORA-02292: integrity
o recorde d constraint (USR.EMP_DEPTNO_FK)
n
violated - child
n u s found
c a is
u ha t
o
Y yt
ke
266
Database Transactions
267
Database Transactions
268
Advantages of COMMIT
and ROLLBACK
• Ensure data consistency
• Preview data changes before making
changes permanent
• Group logically related operations
269
Controlling Transactions
Transaction
ROLLBACK to Savepoint B
ROLLBACK to Savepoint A
ROLLBACK
270
Implicit Transaction Processing
274
State of the Data After ROLLBACK
Discard all pending changes by using the
ROLLBACK statement.
• Data changes are undone.
• Previous state of the data is restored.
• Locks on the affected rows are
released.
SQL> DELETE FROM employee;
14 rows deleted.
SQL> ROLLBACK;
Rollback complete.
275
Rolling Back Changes
to a Marker
• Create a marker within a current
transaction by using the SAVEPOINT
statement.
• Roll back to that marker by using the
ROLLBACK TO SAVEPOINT statement.
SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.
276
Statement-Level Rollback
278
Implementation of Read
Consistency
UPDATE emp Data
SET sal = 2000 blocks
WHERE ename =
'SCOTT';
Rollback
segments
User A
changed
SELECT * and
FROM emp; Read unchanged
data
consistent
image before
change
“old” data
User B
279
Locking
Oracle locks:
• Prevent destructive interaction between
concurrent transactions
• Require no user action
• Automatically use the lowest level of
restrictiveness
• Are held for the duration of the
transaction
• Have two basic modes:
– Exclusive
– Share
280
Summary
Statement Description
281
Practice Overview
282
Creating and Managing
Tables
Objectives
284
Database Objects
Object Description
Table Basic unit of storage; composed of rows
and columns
View Logically represents subsets of data from
one or more tables
Sequence Generates primary key values
Index Improves the performance of some queries
Synonym Gives alternative names to objects
285
Naming Conventions
286
The CREATE TABLE Statement
• You must have :
– CREATE TABLE privilege
– A storage area
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr];
• You specify:
– Table name
– Column name, column datatype, and
column size
287
Referencing Another User’s
Tables
• Tables belonging to other users are not
in the user’s schema.
• You should use the owner’s name as a
prefix to the table.
288
The DEFAULT Option
• Specify a default value for a column during
an insert.
290
Querying the Data Dictionary
• Describe tables owned by the user.
SQL> SELECT *
2 FROM user_tables;
291
Datatypes
Datatype Description
VARCHAR2(size) Variable-length character data
CHAR(size) Fixed-length character data
NUMBER(p,s) Variable-length numeric data
DATE Date and time values
LONG Variable-length character data
up to 2 gigabytes
CLOB Single-byte character data up to 4
gigabytes
RAW and LONG RAW Raw binary data
BLOB Binary data up to 4 gigabytes
BFILE Binary data stored in an external
file; up to 4 gigabytes
292
Creating a Table
by Using a Subquery
• Create a table and insert rows by
combining the CREATE TABLE statement
and AS subquery option.
CREATE TABLE table
[column(, column...)]
AS subquery;
294
The ALTER TABLE Statement
Use the ALTER TABLE statement to:
• Add a new column
• Modify an existing column
• Define a default value for the new column
ALTER TABLE table
ADD (column datatype [DEFAULT expr]
[, column datatype]...);
295
Adding a Column
“…add a
DEPT30 New column
new
EMPNO ENAME ANNSAL HIREDATE JOB column
------ ---------- -------- into
7698 BLAKE 34200 01-MAY-81 DEPT30
7654 MARTIN 15000 28-SEP-81 table…”
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
DEPT30
EMPNO ENAME ANNSAL HIREDATE JOB
297
Modifying a Column
• You can change a column's datatype,
size, and default value.
ALTER TABLE dept30
MODIFY (ename VARCHAR2(15));
Table altered.
298
Dropping a Table
299
Changing the Name of an Object
300
Truncating a Table
• The TRUNCATE TABLE statement:
– Removes all rows from a table
– Releases the storage space used by
that table
SQL> TRUNCATE TABLE department;
Table truncated.
Statement Description
CREATE TABLE Creates a table
ALTER TABLE Modifies table structures
DROP TABLE Removes the rows and table structure
RENAME Changes the name of a table, view,
sequence, or synonym
TRUNCATE Removes all rows from a table and
releases the storage space
COMMENT Adds comments to a table or view
303
Practice Overview
304
Including Constraints
Objectives
306
What Are Constraints?
• Constraints enforce rules at the table level.
• Constraints prevent the deletion of a table
if there are dependencies.
• The following constraint types are valid in
Oracle:
– NOT NULL
– UNIQUE Key
– PRIMARY KEY
– FOREIGN KEY
– CHECK
307
Constraint Guidelines
• Name a constraint or the Oracle Server will
generate a name by using the SYS_Cn
format.
• Create a constraint:
– At the same time as the table is created
– After the table has been created
• Define a constraint at the column or table
level.
• View a constraint in the data dictionary.
308
Defining Constraints
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
…
[table_constraint]);
309
Defining Constraints
310
The NOT NULL Constraint
Ensures that null values are not permitted
for the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO
311
The NOT NULL Constraint
Defined at the column level
SQL> CREATE TABLE emp(
2 empno NUMBER(4),
3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL);
312
The UNIQUE Key Constraint
UNIQUE key constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
313
The UNIQUE Key Constraint
Defined at either the table level or the column
level
314
The PRIMARY KEY Constraint
PRIMARY KEY
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
315
The PRIMARY KEY Constraint
Defined at either the table level or the column
level
316
The FOREIGN KEY Constraint
DEPT
PRIMARY DEPTNO DNAME LOC
KEY ------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
...
EMP
EMPNO ENAME JOB ... COMM DEPTNO FOREIGN
KEY
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
... Not allowed
(DEPTNO
(DEPTNO 9
Insert into does not exist
in the DEPT
7571 FORD MANAGER ... 200 9 table
7571 FORD MANAGER ... 200 Allowed
317
The FOREIGN KEY Constraint
Defined at either the table level or the
column level
SQL> CREATE TABLE emp(
2 empno NUMBER(4),
3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL,
10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)
11 REFERENCES dept (deptno));
318
FOREIGN KEY Constraint
Keywords
• FOREIGN KEY
Defines the column in the child table at
the table constraint level
• REFERENCES
Identifies the table and column in the
parent table
• ON DELETE CASCADE
Allows deletion in the parent table and
deletion of the dependent rows in the
319
child table
The CHECK Constraint
• Defines a condition that each row must
satisfy
• Expressions that are not allowed:
– References to pseudocolumns CURRVAL,
NEXTVAL, LEVEL, and ROWNUM
– Calls to SYSDATE, UID, USER, and
USERENV functions
– Queries that refer to other values in other
rows
..., deptno NUMBER(2),
CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...
320
Adding a Constraint
321
Adding a Constraint
Add a FOREIGN KEY constraint to the
EMP table indicating that a manager must
already exist as a valid employee in the
EMP table.
SQL> ALTER TABLE emp
2 ADD CONSTRAINT emp_mgr_fk
3 FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.
322
Dropping a Constraint
• Remove the manager constraint from
the EMP table.
SQL> ALTER TABLE emp
2 DROP CONSTRAINT emp_mgr_fk;
Table altered.
323
Disabling Constraints
• Execute the DISABLE clause of the
ALTER TABLE statement to deactivate
an integrity constraint.
• Apply the CASCADE option to disable
dependent integrity constraints.
SQL> ALTER TABLE emp
2 DISABLE CONSTRAINT emp_empno_pk CASCADE;
Table altered.
324
Enabling Constraints
• Activate an integrity constraint currently
disabled in the table definition by using
the ENABLE clause.
SQL> ALTER TABLE emp
2 ENABLE CONSTRAINT emp_empno_pk;
Table altered.
325
Viewing Constraints
CONSTRAINT_NAME C SEARCH_CONDITION
------------------------ - -------------------------
SYS_C00674 C EMPNO IS NOT NULL
SYS_C00675 C DEPTNO IS NOT NULL
EMP_EMPNO_PK P
...
326
Viewing the Columns
Associated with Constraints
View the columns associated with the
constraint names in the
USER_CONS_COLUMNS view
SQL> SELECT constraint_name, column_name
2 FROM user_cons_columns
3 WHERE table_name = 'EMP';
CONSTRAINT_NAME COLUMN_NAME
------------------------- ----------------------
EMP_DEPTNO_FK DEPTNO
EMP_EMPNO_PK EMPNO
EMP_MGR_FK MGR
SYS_C00674 EMPNO
SYS_C00675 DEPTNO
327
Summary
• Create the following types of constraints:
– NOT NULL
– UNIQUE key
– PRIMARY KEY
– FOREIGN KEY
– CHECK
• Query the USER_CONSTRAINTS table to
view all constraint definitions and names.
328
Practice Overview
329
Creating Views
Objectives
After completing this lesson, you should
be able to do the following:
• Describe a view
• Create a view
• Retrieve data through a view
• Alter the definition of a view
• Insert, update, and delete data through
a view
• Drop a view
331
Database Objects
Object Description
332
What Is a View?
EMP Table
EMPNO ENAME JOB
JOB MGR HIREDATE SAL
SAL COMM
COMM DEPTNO
DEPTNO
----- --------
------- ---------
--------------
---- --------- ------
----- -----
------------
-------
7839
7839 KING PRESIDENT
PRESIDENT 17-NOV-81 5000
5000 10
10
7782
7698 CLARK
BLAKE MANAGER
MANAGER 7839 09-JUN-81
01-MAY-81 2850
1500 300 30
10
7934
7782 MILLER
CLARK MANAGER
CLERK 7782
7839 23-JAN-82
09-JUN-81 2450
1300 10
10
7566
7566 JONES MANAGER
MANAGER 7839 02-APR-81 2975
2975 20
20
EMPVU10
7788 ViewSALESMAN
7654 SCOTT
MARTIN ANALYST 7566
7698 09-DEC-82
28-SEP-81 1250
3000 1400 30
20
EMPNO 7876
7499 ADAMS
ENAMEALLEN SALESMAN
CLERK
JOB 7788
7698 12-JAN-83
20-FEB-81 1600
1100 300 30
20
------ 7369
--------
7844 SMITH -----------
TURNER SALESMAN
CLERK 7902
7698 17-DEC-80
08-SEP-81 1500
800 0 30
20
7902
7900 FORD
JAMES CLERK
ANALYST 7566
7698 03-DEC-81 3000
950 30
20
7839 7698
KING
7521 BLAKE
WARD
PRESIDENT
SALESMAN
MANAGER 7839
7698 01-MAY-81
22-FEB-81 1250
2850 500 30
30
7782 7654
CLARK
7902 MARTIN
FORD MANAGER
ANALYST
SALESMAN 7698
7566 28-SEP-81
03-DEC-81 3000
1250 1400 20
30
7934 7499
MILLER
7369 ALLEN
SMITH
CLERK
CLERK
SALESMAN 7698
7902 20-FEB-81
17-DEC-80 1600
800 300 20
30
7844
7788 TURNER
SCOTT ANALYST
SALESMAN 7698
7566 08-SEP-81
09-DEC-82 3000
1500 0 20
30
7900
7876 JAMES
ADAMS CLERK
CLERK 7698
7788 03-DEC-81
12-JAN-83 1100
950 20
30
7521
7934 WARD
MILLER CLERK
SALESMAN 7698
7782 22-FEB-81
23-JAN-82 1300
1250 500 10
30
333
Why Use Views?
334
Simple Views
and Complex Views
Feature Simple Views Complex Views
335
Creating a View
• You embed a subquery within the CREATE
VIEW statement.
336
Creating a View
• Create a view, EMPVU10, that contains
details of employees in department 10.
SQL> CREATE VIEW empvu10
2 AS SELECT empno, ename, job
3 FROM emp
4 WHERE deptno = 10;
View created.
337
Creating a View
• Create a view by using column aliases
in the subquery.
SQL> CREATE VIEW salvu30
2 AS SELECT empno EMPLOYEE_NUMBER, ename NAME,
3 sal SALARY
4 FROM emp
5 WHERE deptno = 30;
View created.
338
Retrieving Data from a View
SQL> SELECT *
2 FROM salvu30;
6 rows selected.
339
Querying a View
SQL*Plus
USER_VIEWS
SELECT *
EMPVU10
FROM empvu10;
SELECT empno, ename, job
FROM emp
WHERE deptno = 10;
7839 KING PRESIDENT
7782 CLARK MANAGER EMP
7934 MILLER CLERK
340
Modifying a View
• Modify the EMPVU10 view by using
CREATE OR REPLACE VIEW clause. Add
an alias for each column name.
SQL> CREATE OR REPLACE VIEW empvu10
2 (employee_number, employee_name, job_title)
3 AS SELECT empno, ename, job
4 FROM emp
5 WHERE deptno = 10;
View created.
341
Creating a Complex View
Create a complex view that contains group
functions to display values from two tables.
SQL> CREATE VIEW dept_sum_vu
2 (name, minsal, maxsal, avgsal)
3 AS SELECT d.dname, MIN(e.sal), MAX(e.sal),
4 AVG(e.sal)
5 FROM emp e, dept d
6 WHERE e.deptno = d.deptno
7 GROUP BY d.dname;
View created.
342
Rules for Performing
DML Operations on a View
• You can perform DML operations on
simple views.
• You cannot remove a row if the view
contains the following:
– Group functions
– A GROUP BY clause
– The DISTINCT keyword
343
Rules for Performing
DML Operations on a View
• You cannot modify data in a view if it contains:
– Any of the conditions mentioned in the
previous slide
– Columns defined by expressions
– The ROWNUM pseudocolumn
• You cannot add data if:
– The view contains any of the conditions
mentioned above or in the previous slide
– There are NOT NULL columns in the base
tables that are not selected by the view
344
Using the WITH CHECK OPTION
Clause
• You can ensure that DML on the view stays
within the domain of the view by using the
WITH CHECK OPTION.
SQL> CREATE OR REPLACE VIEW empvu20
2 AS SELECT *
3 FROM emp
4 WHERE deptno = 20
5 WITH CHECK OPTION CONSTRAINT empvu20_ck;
View created.
347
Summary
• A view is derived from data in other
tables or other views.
• A view provides the following
advantages:
– Restricts database access
– Simplifies queries
– Provides data independence
– Allows multiple views of the same data
– Can be dropped without removing the
underlying data
348
Practice Overview
349
Controlling User Access
Objectives
351
Controlling User Access
Database
administrator
352
Privileges
• Database security
– System security
– Data security
• System privileges: Gain access to the
database
• Object privileges: Manipulate the
content of the database objects
• Schema: Collection of objects, such as
tables, views, and sequences
353
System Privileges
• More than 80 privileges are available.
• The DBA has high-level system
privileges.
– Create new users
– Remove users
– Remove tables
– Backup tables
354
Creating Users
355
User System Privileges
• Once a user is created, the DBA can grant
specific system privileges to a user.
GRANT privilege [, privilege...]
TO user [, user...];
357
What Is a Role?
Users
Manager
Privileges
358
Creating and Granting Privileges
to a Role
SQL> CREATE ROLE manager;
Role created.
359
Changing Your Password
360
Object Privileges
Object
Privilege Table View Sequence Procedure
ALTER
DELETE
EXECUTE
INDEX
INSERT
REFERENCES
SELECT
UPDATE
361
Object Privileges
• Object privileges vary from object to object.
• An owner has all the privileges on the object.
• An owner can give specific privileges on that
owner’s object.
362
Granting Object Privileges
• Grant query privileges on the EMP table.
SQL> GRANT select
2 ON emp
3 TO sue, rich;
Grant succeeded.
363
Using WITH GRANT OPTION
and PUBLIC Keywords
• Give a user authority to pass along the
privileges.
SQL> GRANT select, insert
2 ON dept
3 TO scott
4 WITH GRANT OPTION;
Grant succeeded.
365
How to Revoke Object Privileges
• You use the REVOKE statement to
revoke privileges granted to other
users.
• Privileges granted to others through the
WITH GRANT OPTION will also be
revoked.
REVOKE {privilege [, privilege...]|ALL}
ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];
366
Revoking Object Privileges
367
Summary
CREATE USER Allows the DBA to create a user
GRANT Allows the user to give other users
privileges to access the user's
objects
CREATE ROLE Allows the DBA to create a collection
of privileges
ALTER USER Allows users to change their
password
REVOKE Removes privileges on an object from
users
368
Practice Overview
369
Oracle PL/SQL
About PL/SQL
371
PL/SQL Environment
PL/SQL engine
PL/SQL Procedural
PL/SQL PL/SQL
block block SQL Statement
Executor
Oracle Server
372
Benefits of PL/SQL
Integration
Application
373
Benefits of PL/SQL
Improve Performance
SQL
SQL
Application Other DBMSs
SQL
SQL
SQL
IF...THEN
SQL Oracle with
Application ELSE PL/SQL
SQL
END IF;
SQL
374
Benefits of PL/SQL
Modularize program development
Stored
Anonymous
procedure/
block
DECLARE function
BEGIN Application
Application
procedure/
trigger
function
EXCEPTION
Database
END; Packaged
trigger procedure
375
Benefits of PL/SQL
• It is portable.
• You can declare identifiers.
• You can program with procedural
language control structures.
• It can handle errors.
376
Benefits of PL/SQL
• It is portable.
• You can declare identifiers.
• You can program with procedural
language control structures.
• It can handle errors.
377
Tables Used in the Course
EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 1500 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
DEPT 7900 JAMES CLERK 7698 03-DEC-81 950 30
DEPTNO 7521
DNAMEWARD SALESMAN
LOC 7698 22-FEB-81 1250 500 30
--------- 7902 FORD
-------------- ANALYST
---------- 7566 03-DEC-81 SALGRADE
3000 20
7369 10
SMITH CLERK NEW
ACCOUNTING 7902 17-DEC-80 800
GRADE LOSAL 20
HISAL
YORK 7788 SCOTT ANALYST 7566 09-DEC-82 3000
--------- 20
--------- ---------
20 7876 ADAMS
RESEARCH CLERK
DALLAS 7788 12-JAN-83 1100 1 700 20
1200
30 7934
SALESMILLER CLERK
CHICAGO 7782 23-JAN-82 1300 2 1201 10
1400
40 OPERATIONS BOSTON 3 1401 2000
4 2001 3000
5 3001 9999
378
PL-SQL Example
Create FUNCTION get_geo_distance
(lat1 IN NUMBER, lon1 IN NUMBER,lat2 IN NUMBER, lon2 IN NUMBER)
RETURN NUMBER
IS
v_r NUMBER :=6378.7;
BEGIN
IF lat1=lat2 AND lon1=lon2 THEN
RETURN 0;
END IF;
RETURN v_r * ACOS( SIN(lat1) * SIN(lat2) + COS(lat1) * COS(lat2) *
COS(lon2- lon1) );
EXCEPTION WHEN OTHERS
THEN RETURN NULL;
END;
379
Data for the distance calculator
Approx. values of Latitude and
Longitude in Radians
380
Summary
• Relational databases are composed of
relations, managed by relational
operations, and governed by data
integrity constraints.
• Oracle Server allows you to store and
manage information by using the SQL
language and PL/SQL engine.
• PL/SQL is an extension to SQL with
design features of programming
languages.
381
Objectives
After completing this lesson, you should
be able to do the following:
• Recognize the basic PL/SQL block and
its sections
• Describe the significance of variables in
PL/SQL
• Distinguish between PL/SQL and non-
PL/SQL variables
• Declare PL/SQL variables
• Execute a PL/SQL block
382
Declaring Variables
PL/SQL Block Structure
• DECLARE – Optional
– Variables, cursors, user-defined
exceptions
• BEGIN – Mandatory
– SQL statements
– PL/SQL statements
• EXCEPTION – Optional
DECLARE
– Actions to perform when
errors occur BEGIN
• END; – Mandatory
EXCEPTION
END;
384
PL/SQL Block Structure
DECLARE
v_variable VARCHAR2(5);
BEGIN
SELECT column_name
INTO v_variable
FROM table_name;
EXCEPTION
WHEN exception_name THEN DECLARE
...
BEGIN
END;
EXCEPTION
END;
385
Block Types
Anonymous Procedure
Function
[DECLARE] PROCEDURE name FUNCTION name
IS RETURN datatype
IS
BEGIN BEGIN BEGIN
--statements --statements --statements
RETURN value;
[EXCEPTION] [EXCEPTION] [EXCEPTION]
386
Program Constructs
Stored
Anonymous
procedure/
block
DECLARE function
BEGIN Application
Application
procedure/
trigger
function
EXCEPTION
Database
END; Packaged
procedure/
trigger
function
387
Use of Variables
388
Handling Variables in PL/SQL
389
Types of Variables
• PL/SQL variables
– Scalar
– Composite
– Reference
– LOB (large objects)
• Non-PL/SQL variables
– Bind and host variables
390
Types of Variables
21-JUL-05
TRUE “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.”
Hyderabad
391
Declaring PL/SQL Variables
Syntax
identifier [CONSTANT] datatype [NOT NULL]
[:= | DEFAULT expr];
Examples
Declare
v_hiredate DATE;
v_deptno NUMBER(2) NOT NULL := 10;
v_location VARCHAR2(13) := ‘Hyderabad';
c_ comm CONSTANT NUMBER := 1400;
392
Declaring PL/SQL Variables
Guidelines
• Follow naming conventions.
• Initialize variables designated as NOT
NULL.
• Initialize identifiers by using the
assignment operator (:=) or by using the
DEFAULT reserved word.
• Declare at most one identifier per line.
393
Naming Rules
• Two variables can have the same name,
provided they are in different blocks.
• The variable name (identifier) should not
be the same as the name of table
columns used in the block.
DECLARE
empno NUMBER(4);
BEGIN
SELECT empno
INTO empno
FROM emp
WHERE ename = 'SMITH';
END;
394
Assigning Values to Variables
Syntax
identifier := expr;
Examples
Set a predefined hiredate for new
employees.
v_hiredate := ’21-JUL-05';
395
Variable Initialization and
Keywords
Using
• := Assignment Operator
• DEFAULT
• NOT NULL
396
Scalar Datatypes
• Hold a single value
• Have no internal components
21-JUL-05
“Four score and seven years
ago our fathers brought
TRUE
forth upon this continent, a
new nation, conceived in
Examples
v_job VARCHAR2(9);
v_count BINARY_INTEGER := 0;
v_total_sal NUMBER(9,2) := 0;
v_orderdate DATE := SYSDATE + 7;
c_tax_rate CONSTANT NUMBER(3,2) := 8.25;
v_valid BOOLEAN NOT NULL := TRUE;
399
The %TYPE Attribute
• Declare a variable according to:
– A database column definition
– Another previously declared variable
• Prefix %TYPE with:
– The database table and column
– The previously declared variable
name
400
Declaring Variables with the
%TYPE Attribute
Examples
...
v_ename emp.ename%TYPE;
v_balance NUMBER(7,2);
v_min_balance v_balance%TYPE := 10;
...
401
Declaring BOOLEAN Variables
• Only the values TRUE, FALSE, and
NULL can be assigned to a Boolean
variable.
• The variables are connected by the
logical operators AND, OR, and NOT.
• The variables always yield TRUE,
FALSE, or NULL.
• Arithmetic, character, and date
expressions may be used to return a
Boolean value.
402
Composite Datatypes
Types
• PL/SQL TABLES
• PL/SQL RECORDS
403
LOB Datatype Variables
Recipe
(CLOB)
Photo
(BLOB)
Movie
(BFILE)
NCLOB
404
Bind Variables
O/S
Bind Variable
Server
405
Referencing Non-PL/SQL
Variables
406
Summary
407
Summary
• PL/SQL identifiers:
– Are defined in the declarative section
– Can be of scalar, composite,
reference, or LOB datatype
– Can be based on the structure of
another variable or database object
– Can be initialized
408
Practice Overview
409
Writing Executable
Statements
Objectives
• Recognize the significance of the
executable section
• Write statements within the executable
section
• Describe the rules of nested blocks
• Execute and test a PL/SQL block
• Use coding conventions
411
PL/SQL Block Syntax and
Guidelines
• Statements can continue over several
lines.
• Lexical units can be separated by
spaces:
– Delimiters
– Identifiers
– Literals
– Comments
412
PL/SQL Block Syntax and
Guidelines
Identifiers
• Can contain up to 30 characters
• Cannot contain reserved words unless
enclosed in double quotation marks
• Must begin with an alphabetic character
• Should not have the same name as a
database table column name
413
PL/SQL Block Syntax and
Guidelines
Literals
• Character and date literals must be
enclosed in single quotation marks.
v_ename := 'Henderson';
414
Commenting Code
• Prefix single-line comments with two
dashes (- -).
• Place multi-line comments between the
symbols /* and */.
Example
...
v_sal NUMBER (9,2);
BEGIN
/* Compute the annual salary based on the
monthly salary input from the user */
v_sal := v_sal * 12;
END; -- This is the end of the transaction
415
SQL Functions in PL/SQL
procedural statements
}
• Available:
– Single-row number Same as in SQL
– Single-row character
– Datatype conversion
– Date
• Not available
– SQL aggregate functions (eg. AVG, COUNT)
– SQL analytic functions (eg. CORR, LAG)
– Object-reference functions DEREF, REF, VALUE
– Miscellaneous functions DECODE, DUMP, VSIZ
416
PL/SQL Functions
Examples
• Build the mailing list for a company.
v_mailing_address := v_name||CHR(10)||
v_address||CHR(10)||v_state||
CHR(10)||v_zip;
417
Datatype Conversion
418
Datatype Conversion
419
Nested Blocks and Variable
Scope
• Statements can be nested wherever an
executable statement is allowed.
• A nested block becomes a statement.
• An exception section can contain
nested blocks.
• The scope of an object is the region of
the program that can refer to the object.
420
Nested Blocks and Variable
Scope
An identifier is visible in the regions in
which you can reference the unqualified
identifier:
• A block can look up to the enclosing
block.
• A block cannot look down to enclosed
blocks.
421
Nested Blocks and Variable
Scope
Example
...
x BINARY_INTEGER;
BEGIN Scope of x
...
DECLARE
y NUMBER;
BEGIN Scope of y
...
END;
...
END;
422
Operators in PL/SQL
}
• Logical
• Arithmetic
• Concatenation Same as in
SQL
• Parentheses to
control order of
operations
• Exponential operator (**)
423
Operators in PL/SQL
Examples
• Increment the index for a loop.
v_count := v_count + 1;
424
Using Bind Variables
425
Programming Guidelines
426
Code Naming Conventions
Avoid ambiguity:
• The names of local variables and formal
parameters take precedence over the
names of database tables.
• The names of columns take precedence
over the names of local variables.
427
Indenting Code
For clarity, indent each level of code.
Example DECLARE
v_detpno NUMBER(2);
BEGIN v_location VARCHAR2(13);
IF x=0 THEN BEGIN
y=1; SELECT deptno,
END IF; location
END; INTO v_deptno,
v_location
FROM dept
WHERE dname = 'SALES';
...
END;
428
Determine Variable Scope
Class Exercise
...
DECLARE
V_SAL NUMBER(7,2) := 60000;
V_COMM NUMBER(7,2) := V_SAL / .20;
V_MESSAGE VARCHAR2(255) := ' eligible for commission';
BEGIN ...
DECLARE
V_SAL NUMBER(7,2) := 50000;
V_COMM NUMBER(7,2) := 0;
V_TOTAL_COMP NUMBER(7,2) := V_SAL + V_COMM;
BEGIN ...
V_MESSAGE := 'CLERK not'||V_MESSAGE;
END;
V_MESSAGE := 'SALESMAN'||V_MESSAGE;
END;
429
Summary
• PL/SQL block structure:
– Nesting blocks and scoping
rules
• PL/SQL programming:
– Functions
DECLARE
– Datatype conversions
BEGIN
– Operators EXCEPTION
431
Interacting with the
Oracle Server
Objectives
After completing this lesson, you should
be able to do the following:
• Write a successful SELECT statement in
PL/SQL
• Declare the datatype and size of a
PL/SQL variable dynamically
• Write DML statements in PL/SQL
• Control transactions in PL/SQL
• Determine the outcome of SQL DML
statements
433
SQL Statements in PL/SQL
435
SELECT Statements in PL/SQL
436
Retrieving Data in PL/SQL
Retrieve the order date and the ship date for the
specified order.
Example
DECLARE
v_orderdate ord.orderdate%TYPE;
v_shipdate ord.shipdate%TYPE;
BEGIN
SELECT orderdate, shipdate
INTO v_orderdate, v_shipdate
FROM ord
WHERE id = 157;
...
END;
437
Retrieving Data in PL/SQL
Return the sum of the salaries for all
employees in the specified department.
Example
DECLARE
v_sum_sal emp.sal%TYPE;
v_deptno NUMBER NOT NULL := 10;
BEGIN
SELECT SUM(sal) -- group function
INTO v_sum_sal
FROM emp
WHERE deptno = v_deptno;
END;
438
Manipulating Data Using PL/SQL
DELETE
439
Inserting Data
440
Updating Data
Increase the salary of all employees in the
emp table who are Analysts.
Example
DECLARE
v_sal_increase emp.sal%TYPE := 2000;
BEGIN
UPDATE emp
SET sal = sal + v_sal_increase
WHERE job = 'ANALYST';
END;
441
Deleting Data
442
Naming Conventions
443
Naming Conventions
DECLARE
order_date ord.orderdate%TYPE;
ship_date ord.shipdate%TYPE;
v_date DATE := SYSDATE;
BEGIN
SELECT orderdate, shipdate
INTO order_date, ship_date
FROM ord
WHERE shipdate = v_date;
END;
SQL> /
DECLARE
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 6
444
COMMIT and ROLLBACK
Statements
445
SQL Cursor
• A cursor is a private SQL work area.
• There are two types of cursors:
– Implicit cursors
– Explicit cursors
• The Oracle Server uses implicit cursors
to parse and execute your SQL
statements.
• Explicit cursors are explicitly declared
by the programmer.
446
SQL Cursor Attributes
Using SQL cursor attributes, you can test
the outcome of your SQL statements.
SQL%ROWCOUNT Number of rows affected by the
most recent SQL statement (an
integer value).
SQL%FOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
statement affects one or more rows.
SQL%NOTFOUND Boolean attribute that evaluates to
TRUE if the most recent SQL
statement does not affect any rows.
SQL%ISOPEN Always evaluates to FALSE because
PL/SQL closes implicit cursors
immediately after they are executed.
447
SQL Cursor Attributes
Delete rows that have the specified order
number from the ITEM table. Print the
number of rows deleted.
Example
VARIABLE rows_deleted
DECLARE
v_ordid NUMBER := 605;
BEGIN
DELETE FROM item
WHERE ordid = v_ordid;
rows_deleted := SQL%ROWCOUNT
||' rows deleted.');
END;
PRINT rows_deleted
448
Summary
449
Summary
• There are two cursor types: implicit and
explicit.
• Implicit cursor attributes verify the
outcome of DML statements:
– SQL%ROWCOUNT
– SQL%FOUND
– SQL%NOTFOUND
– SQL%ISOPEN
• Explicit cursors are defined by the user.
450
Practice Overview
451
Writing Control Structures
Objectives
453
Controlling PL/SQL Flow of
Execution
You can change the logical flow of
statements using conditional IF
statements and loop control structures.
Conditional IF statements:
• IF-THEN-END IF
• IF-THEN-ELSE-END IF
• IF-THEN-ELSIF-THEN-END IF
454
IF Statements
Syntax
IF condition THEN
statements;
[ELSIF condition THEN
statements;]
[ELSE
statements;]
END IF;
Simple IF Statement:
Set the manager ID to 22 if the employee
name is Miller.
IF v_ename = ‘Miller' THEN
v_mgr := 22;
END IF;
455
Simple IF Statements
Set the job title to Salesman, the department
number to 35, and the commission to 20%of the
current salary if the last name is Miller.
Example
. . .
IF v_ename = 'MILLER' THEN
v_job := 'SALESMAN';
v_deptno := 35;
v_new_comm := sal * 0.20;
END IF;
. . .
456
IF-THEN Example
declare
v_hire_date date :='12-dec-2000';
begin
dbms_output.put_line(‘123');
if months_between(sysdate,v_hire_date )/12>5 then
dbms_output.put_line('true');
end if;
end;
Output:123
PL/SQL procedure successfully completed
457
IF-THEN-ELSE Statement
Execution Flow
TRUE FALSE
IF Condition
458
IF-THEN-ELSE Statements
459
If-then-else-end if
declare
v_hire_date date :='12-dec-2000';
begin
dbms_output.put_line('123');
if months_between(sysdate,v_hire_date )/12>5 then
dbms_output.put_line('true');
else
dbms_output.put_line('false');
end if;
end;
460
IF-THEN-ELSIF
Statement Execution Flow
IF Condition
TRUE FALSE
ELSIF
Condition
THEN Actions
TRUE FALSE
ELSE
THEN Actions
Actions
461
IF-THEN-ELSIF Statements
462
IF-THEN-ELSIF-END IF
declare
v_hire_date date :='12-dec-2000';
begin
dbms_output.put_line(‘Welcome');
if months_between(sysdate,v_hire_date )/12>5 then
dbms_output.put_line('true');
elsif months_between(sysdate,v_hire_date )/12<5 then
dbms_output.put_line('false');
end if;
end;
463
USING CASE (SIMPLE EXAMPLE )
Declare
v_grade char(1) :=upper('&p_grade');
v_appraisal varchar2(20);
Begin
v_appraisal :=
case v_grade
when 'A' then 'EXCELLENT'
when 'b' then 'verygood'
when 'c' then 'good'
Else 'nosuch grade'
end;
Dbms_output.put_line('grade;'||v_grade||'Appraisal' ||
464
v_appraisal);
End;
Building Logical Conditions
465
Logic Tables
TRUE TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE
FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL FALSE TRUE
NULL NULL FALSE NULL NULL TRUE NULL NULL NULL NULL
466
Boolean Conditions
467
Iterative Control: LOOP
Statements
468
Basic Loop
Syntax
LOOP -- delimiter
statement1; -- statements
. . .
EXIT [WHEN condition]; -- EXIT statement
END LOOP; -- delimiter
469
Basic Loop
Example
DECLARE
v_ordid item.ordid%TYPE := 101;
v_counter NUMBER(2) := 1;
BEGIN
LOOP
INSERT INTO item(ordid, itemid)
VALUES(v_ordid, v_counter);
v_counter := v_counter + 1;
EXIT WHEN v_counter > 10;
END LOOP;
END;
470
Loop example
declare
v_count number(2):=1;
begin
loop
dbms_output.put_line('counter value:'||
to_char(v_count));
v_count:=v_count+1;
exit when v_count>10;
end loop;
End;
471
FOR Loop
Syntax
FOR counter in [REVERSE]
lower_bound..upper_bound LOOP
statement1;
statement2;
. . .
END LOOP;
472
FOR Loop
Guidelines
• Reference the counter within the loop
only; it is undefined outside the loop.
• Use an expression to reference the
existing value of a counter.
• Do not reference the counter as the target
of an assignment.
473
FOR Loop
Insert the first 10 new line items for order
number 101.
Example
DECLARE
v_ordid item.ordid%TYPE := 101;
BEGIN
FOR i IN 1..10 LOOP
INSERT INTO item(ordid, itemid)
VALUES(v_ordid, i);
END LOOP;
END;
474
For Loop
begin
for v_count in 1..10 loop
dbms_output.put_line('counter value:'||
to_char(v_count));
insert into fordemo values(v_count);
end loop;
end;--please create a table fordemo before
u use it
475
WHILE Loop
Syntax
WHILE condition LOOP Condition is
statement1; evaluated at the
statement2; beginning of
. . . each iteration.
END LOOP;
476
WHILE Loop
Example
477
WHILE Loop
declare
v_count number(2):=1;
begin
while v_count<=10 loop
dbms_output.put_line('counter value:'||
to_char(v_count));
v_count:=v_count+1;
end loop;
end;
478
Nested Loops and Labels
479
Nested Loops and Labels
...
BEGIN
<<Outer_loop>>
LOOP
v_counter := v_counter+1;
EXIT WHEN v_counter>10;
<<Inner_loop>>
LOOP
...
EXIT Outer_loop WHEN total_done = 'YES';
-- Leave both loops
EXIT WHEN inner_done = 'YES';
-- Leave inner loop only
...
END LOOP Inner_loop;
...
END LOOP Outer_loop;
END;
480
Summary
482
Working with Composite
Data types
Objectives
• Create user-defined PL/SQL records
• Create a record with the %ROWTYPE
attribute
• Create a PL/SQL table
• Create a PL/SQL table of records
• Describe the difference between
records, tables, and tables of records
484
Composite Datatypes
• Types:
– PL/SQL RECORDS
– PL/SQL TABLES
• Contain internal components
• Are reusable
485
PL/SQL Records
• Must contain one or more components of
any scalar, RECORD, or PL/SQL TABLE
datatype-called fields
• Are similar in structure to records in a 3GL
• Are not the same as rows in a database
table
• Treat a collection of fields as a logical unit
• Are convenient for fetching a row of data
from a table for processing
486
Creating a PL/SQL Record
Syntax
TYPE type_name IS RECORD
(field_declaration[, field_declaration]…);
identifier type_name;
487
Creating a PL/SQL Record
488
PL/SQL Record Structure
Example
489
The %ROWTYPE Attribute
490
Advantages of Using
%ROWTYPE
• The number and data types of the
underlying database columns may not
be known.
• The number and data types of the
underlying database column may
change at runtime.
• Useful when retrieving a row with the
SELECT statement.
491
The %ROWTYPE Attribute
Examples
Declare a variable to store the same
information about a department as it is
stored in the DEPT table.
dept_record dept%ROWTYPE;
492
PL/SQL Tables
493
Creating a PL/SQL Table
Syntax
TYPE type_name IS TABLE OF
{column_type | variable%TYPE
| table.column%TYPE} [NOT NULL]
[INDEX BY BINARY_INTEGER];
identifier type_name;
494
PL/SQL Table Structure
1 Jones
2 Smith
3 Maduro
... ...
BINARY_INTEGER Scalar
495
Creating a PL/SQL Table
DECLARE
TYPE ename_table_type IS TABLE OF emp.ename%TYPE
INDEX BY BINARY_INTEGER;
TYPE hiredate_table_type IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
hiredate_table hiredate_table_type;
BEGIN
ename_table(1) := 'CAMERON';
hiredate_table(1) := SYSDATE + 7;
IF ename_table.EXISTS(1) THEN
INSERT INTO ...
...
END;
496
PL/SQL Table of Records
• Define a TABLE variable with the
%ROWTYPE attribute.
• Declare a PL/SQL variable to hold
department information.
Example
DECLARE
TYPE dept_table_type IS TABLE OF dept%ROWTYPE
INDEX BY BINARY_INTEGER;
dept_table dept_table_type;
-- Each element of dept_table is a record
497
Using PL/SQL Table Methods
498
Summary
499
Practice Overview
500
Writing Explicit Cursors
Objectives
502
About Cursors
503
Explicit Cursor Functions
Result Set
504
Controlling Explicit Cursors
No
Yes
DECLARE OPEN FETCH EMPTY? CLOSE
505
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
506
Declaring the Cursor
Syntax
CURSOR cursor_name IS
select_statement;
507
Declaring the Cursor
Example
DECLARE
CURSOR c1 IS
SELECT empno, ename
FROM emp;
CURSOR c2 IS
SELECT *
FROM dept
WHERE deptno = 10;
BEGIN
...
508
Opening the Cursor
Syntax
OPEN cursor_name;
509
Fetching Data from the Cursor
Syntax
FETCH cursor_name INTO [variable1, variable2, ...]
| record_name];
Examples
FETCH c1 INTO v_empno, v_ename;
...
OPEN defined_cursor;
LOOP
FETCH defined_cursor INTO defined_variables
EXIT WHEN ...;
...
-- Process the retrieved data
...
END;
511
Closing the Cursor
Syntax
CLOSE cursor_name;
512
Explicit Cursor Attributes
Obtain status information about a cursor.
Attribute Type Description
%ISOPEN Boolean Evaluates to TRUE if the cursor
is open
%NOTFOUND Boolean Evaluates to TRUE if the most
recent fetch does not return a row
%FOUND Boolean Evaluates to TRUE if the most
recent fetch returns a row;
complement of %NOTFOUND
%ROWCOUNT Number Evaluates to the total number of
rows returned so far
513
Controlling Multiple Fetches
514
The %ISOPEN Attribute
• Fetch rows only when the cursor is
open.
• Use the %ISOPEN cursor attribute
before performing a fetch to test
whether the cursor is open.
Example
IF NOT c1%ISOPEN THEN
OPEN c1;
END IF;
LOOP
FETCH c1...
515
The %NOTFOUND and
%ROWCOUNT Attributes
516
Cursors and Records
Process the rows of the active set
conveniently by fetching values into a
PL/SQL RECORD.
Example
...
CURSOR c1 IS
SELECT empno, ename
FROM emp;
emp_record c1%ROWTYPE;
BEGIN
OPEN c1;
. . .
FETCH c1 INTO emp_record;
517
Cursor FOR Loops
Syntax
FOR record_name IN cursor_name LOOP
statement1;
statement2;
. . .
END LOOP;
519
Cursor FOR Loops Using
Subqueries
No Need to declare the cursor.
Example
BEGIN
FOR emp_record IN ( SELECT empno, ename
FROM emp) LOOP
-- implicit open and implicit fetch occur
IF emp_record.empno = 7839 THEN
...
END LOOP; -- implicit close occurs
END;
520
Summary
• Cursor types:
– Implicit cursors: Used for all DML
statements and single-row queries.
– Explicit cursors: Used for queries of
zero, one, or more rows.
• Manipulate explicit cursors.
• Evaluate the cursor status by using
cursor attributes.
• Use cursor FOR loops.
521
Cursors
522
Explicit cursors
523
Can process beyond the first row returned
by the query row by row
Keep track of which row is currently being
processed
Allow the programmer to manually control
these explicit cursors in the pl/sql block
524
Controlling Ecplicit cursors
525
Open the cursor
The open statement executes the query
associated with the cursor identifies the result
set and positions the cursor before the row
Fetch statement retrieves the current row and
advances the cursor to the next row until
either there are no more rows or until specified
condition is met
526
Close the cursor when the last row is
being processed
Declaring
Cursor cur_name is select_statement
-don’t use into clause its IS
-if processing in specific sequence you can use order by
527
Declare
declare
cursor emp_cursor is select ename,empno from
emp;
…..
…...
Declare
Cursor dept_cursor is select
Deptno,dname from dept;
528
Example
declare
v_empno emp.empno%type;
v_ename emp.ename%type;
cursor emp_cursor is select empno,ename from emp;
begin
open emp_curso
for i in 1..10 loop
fetch emp_cursor into v_empno,v_ename;
dbms_output.put_line(to_char(v_empno)||'...'||v_ename);
end loop;
End;
529
Output
7369...SMITH
7499...ALLEN
7521...WARD
7566...JONES
7654...MARTIN
7698...BLAKE
7782...CLARK
7788...SCOTT
7839...KING
7844…TURNER
530
Close cursor
declare
v_empno emp.empno%type;
v_ename emp.ename%type;
cursor emp_cursor is select empno,ename from emp;
begin
open emp_cursor
;
for i in 1..10 loop
fetch emp_cursor into v_empno,v_ename;
dbms_output.put_line(to_char(v_empno)||'...'||v_ename);
end loop;
close emp_cursor;
end;
/
531
Cursor attributes
532
%isopen
declare
v_empno emp.empno%type
v_ename emp.ename%type
cursor emp_cursor is select empno,ename from emp
begin
if not emp_cursor%isopen then
open emp_cursor
for i in 1..10 loop
fetch emp_cursor into v_empno,v_ename
dbms_output.put_line(to_char(v_empno)||'...'||v_ename)
end loop
end if
close emp_cursor
End;
533
Controlling multiple fetches
534
%rowcount
declare
v_empno emp.empno%type;
v_ename emp.ename%type;
cursor emp_cursor is select empno,ename from emp;
begin
if not emp_cursor%isopen then
open emp_cursor;
loop
fetch emp_cursor into v_empno,v_ename;
exit when emp_cursor%rowcount> 10;
dbms_output.put_line(to_char(v_empno)||'...'||v_ename);
end loop;
end if;
close emp_cursor;
535 end;
/
%notfound
declare
v_empno emp.empno%type;
v_ename emp.ename%type;
cursor emp_cursor is select empno,ename from emp;
begin
if not emp_cursor%isopen then
open emp_cursor;
loop
fetch emp_cursor into v_empno,v_ename;
exit when emp_cursor%notfound;
dbms_output.put_line(to_char(v_empno)||'...'||v_ename);
end loop;
end if; close emp_cursor;
536 end;
Cursors and records using for loop
declare
cursor emp_cursor is select empno,ename from emp;
begin
for emp_record in emp_cursor loop
if emp_record.empno=7369 then
dbms_output.put_line(to_char(emp_record.empno)||'...'||
emp_record.ename);
end if; end loop; end;
537
Practice Overview
538
Advanced Explicit Cursor
Concepts
Objectives
540
Cursors with Parameters
Syntax
CURSOR cursor_name
[(parameter_name datatype, ...)]
IS
select_statement;
541
Cursors with Parameters
542
The FOR UPDATE Clause
Syntax
SELECT ...
FROM ...
FOR UPDATE [OF column_reference][NOWAIT]
543
The FOR UPDATE Clause
544
The WHERE CURRENT OF
Clause
Syntax
WHERE CURRENT OF cursor
546
Cursors with Subqueries
Example
DECLARE
CURSOR my_cursor IS
SELECT t1.deptno, dname, STAFF
FROM dept t1, (SELECT deptno,
count(*) STAFF
FROM emp
GROUP BY deptno) t2
WHERE t1.deptno = t2.deptno
AND STAFF >= 5;
547
Summary
548
Practice Overview
549
Handling Exceptions
Objectives
• Define PL/SQL exceptions
• Recognize unhandled exceptions
• List and use different types of PL/SQL
exception handlers
• Trap unanticipated errors
• Describe the effect of exception
propagation in nested blocks
• Customize PL/SQL exception messages
551
Handling Exceptions with PL/SQL
• What is an exception?
– Identifier in PL/SQL that is raised during
execution.
• How is it raised?
– An Oracle error occurs.
– You raise it explicitly.
• How do you handle it?
– Trap it with a handler.
– Propagate it to the calling environment.
552
Handling Exceptions
BEGIN BEGIN
Exception Exception
is raised is raised
EXCEPTION EXCEPTION
Exception Exception is
is trapped END; END; not trapped
Exception
propagates to calling
environment
553
Exception Types
554
Trapping Exceptions
Syntax
EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
statement2;
. . .
[WHEN exception3 [OR exception4 . . .] THEN
statement1;
statement2;
. . .]
[WHEN OTHERS THEN
statement1;
statement2;
. . .]
555
Trapping Exceptions Guidelines
556
Trapping Predefined Oracle
Server Errors
• Reference the standard name in the
exception-handling routine.
• Sample predefined exceptions:
– NO_DATA_FOUND
– TOO_MANY_ROWS
– INVALID_CURSOR
– ZERO_DIVIDE
– DUP_VAL_ON_INDEX
557
Predefined Exception
Syntax
BEGIN SELECT ... COMMIT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
statement1;
statement2;
558
Trapping Non-Predefined Oracle
Server Errors
559
Non-Predefined Error Ex:1
Trap for Oracle Server error number
-2292 an integrity constraint violation
DECLARE
e_products_invalid
e_products_invalid EXCEPTION;
EXCEPTION; 1
PRAGMA EXCEPTION_INIT
PRAGMA EXCEPTION_INIT ((
e_products_invalid, -2292); 2
v_message VARCHAR2(50);
BEGIN
. . .
EXCEPTION
WHEN e_products_invalid THEN 3
:g_message := 'Product code
specified is not valid.';
. . .
END;
560
Non-Predefined Error Ex:2
Trap for Oracle Server error number
-20001 for an invalid date of birth
Declare
en_too_young CONSTANT NUMBER: = -20001;
Min_years CONSTANT PLS_INTEGER := 18;
exc_too_young EXCEPTION;
PRAGMA EXCEPTION_INIT (exc_too_young, -20001);
BEGIN
…….
IF ADD_MONTHS(SYSDATE, min_years * 12 * -1) < birthdate_in
THEN RAISE APPLICATION_ERROR
(en_too_young,’Employee must be atleast ‘||min_years||’ old);
END IF;
………..
END;
561
Trapping User-Defined
Exceptions
562
User-Defined Exception
Example
[DECLARE]
e_amount_remaining EXCEPTION;
e_amount_remaining EXCEPTION; 1
. . .
BEGIN
. . .
RAISE
RAISEe_amount_remaining;
e_amount_remaining;
. . . 2
EXCEPTION
e_amount_remaining THEN
WHEN e_amount_remaining
:g_message := 'There is still an amount 3
in stock.';
. . .
END;
563
Functions for Trapping
Exceptions
• SQLCODE
Returns the numeric value for the error
code
• SQLERRM
Returns the message associated with the
error number
564
Functions for Trapping Exceptions
Example
DECLARE
v_error_code NUMBER;
v_error_message VARCHAR2(255);
BEGIN
...
EXCEPTION
...
WHEN OTHERS THEN
ROLLBACK;
v_error_code := SQLCODE ;
v_error_message := SQLERRM ;
INSERT INTO errors VALUES(v_error_code,
v_error_message);
END;
565
Calling Environments
SQL*Plus Displays error number and message
to screen
Procedure Displays error number and message
Builder to screen
Accesses error number and message
Developer/2000
Forms in a trigger by means of the
ERROR_CODE and ERROR_TEXT
packaged functions
Precompiler Accesses exception number through
application
the SQLCA data structure
An enclosing
PL/SQL block Traps exception in exception-
566 handling routine of enclosing block
Propagating Exceptions
DECLARE
. . .
e_no_rows exception;
e_integrity exception;
PRAGMA EXCEPTION_INIT (e_integrity, -2292);
BEGIN
FOR c_record IN emp_cursor LOOP
BEGIN
SELECT ...
Subblocks can handle UPDATE ...
IF SQL%NOTFOUND THEN
an exception or pass RAISE e_no_rows;
END IF;
the exception to the EXCEPTION
WHEN e_integrity THEN ...
enclosing block. WHEN e_no_rows THEN ...
END;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN . . .
WHEN TOO_MANY_ROWS THEN . . .
END;
567
RAISE_APPLICATION_ERROR
Syntax
raise_application_error (error_number,
message[, {TRUE | FALSE}]);
568
RAISE_APPLICATION_ERROR
569
Summary
• Exception types:
– Predefined Oracle Server error
– Non-predefined Oracle Server error
– User-defined error
• Trap exceptions
• Handle exceptions:
– Trap the exception within the PL/SQL
block
– Propagate the exception
570
Practice Overview
571
Practice Overview
572
Exceptions
Predefined exception
No_data_found
Too_many_rows
Invalid_cursor
Zero_divide
Dup_val_on_index
Acces_into_null
Case_no_found
574
User defined exception example
Declare
invalid_dept EXCEPTION;
Begin
update dept set dname='&dname' where deptno=&deptno;
if sql%notfound then
raise invalid_dept;
end if;
commit;
Exception
When invalid_dept then
Dbms_output.put_line('cannot update');
End;
/
575
Raise_an_application_error example
Declare
V_msg varchar2(50):= ’data not found’;
begin
delete from dept where deptno=300;
If sql%notfound then
Raise_application_error(-20045,v_msg);
end if;
End;
576
subprograms
577
syntax
578
In parameters
579
Create or replace procedure raise_salary(p_id in
emp.empno%type)
Is
Begin
Update emp set sal=sal*10 where empno=p_id;
End raise_salary;
/
execute raise_salary(7369);
580
Out parameter
582
How will you see them?
Execute
query_emp(7369, :g_name,:g_sal,:g_com
m);
583
SQL> print g_name
G_NAME
--------------------------------
SMITH
G_SAL
----------
80000
584
G_COMM
INOUT parameters
585
How to view
variable g_phone;
begin
:g_phone :='9885038859';
end;
/
SQL> Print g_phone
G_PHONE
--------------------------------
9885038859
586
Execute the procedure
Execute format_phone(:g_phone)
SQL> Execute format_phone(:g_phone)
PL/SQL procedure successfully completed.
SQL> print g_phone
G_PHONE
--------------------------------
(988)503-8859
587
Procedure in procedure
589
Functions
590
Syntax
591
Function example
function edbdor (in_dob IN date, in_desgcode IN
number)
return date is
out_dor date;
begin
select last_day(add_months(in_dob-1,retage*12))
into out_dor from sdb.mast_desg where
desgcode = in_desgcode;
return out_dor;
end edbdor;
592
Function example
593
SQL> Create or replace function get_sal(
2 p_id in emp.empno%type)
3 return number
4 Is
5 v_sal emp.sal%type:=0;
6 Begin
7 Select sal into v_sal from emp where empno=p_id;
8 Return v_sal;
9 End get_sal;
10 /
Function created.
594
How to execute
595
output
596
Invoking functions
Function created.
597
Now use this function in your
expressions
SQL> Select empno,tax(sal),sal from emp
EMPNO TAX(SAL) SAL
---------- ---------- ----------
7499 16000 1600
7521 12500 1250
7566 29750 2975
7654 12500 1250
7698 28500 2850
7782 24500 2450
598
Functions and procedures
Improved performance
Right once run n times
Data security
Data integrity
Code clarity
Can be reusable
599
differences
Procedure Function
Execute as a pl/sql Invoke as a part of an
statement expression
Do not return clause in Contains return clause in
header header
Can return none one or Must return a single value
many values
Can contain return Must contain return
statement statement
600
Triggers
A Trigger is a
PL/BLOCK or a PL/SQL procedure associated
with a table or view, schema or database
Executes implicitly whenever particular event
takes place
Can be either application trigger :fires when an
event occurs for a particular application
Database trigger fires whenever data event or
system event occurs on a schema or database
601
Trigger
Inserting in a table
Deleting from a table
Update a table
602
Trigger components (DML)
603
When should a trigger Fire
Before
After
Instead of for views which cannot be
modified
604
example
1 create or replace trigger secure_emp
2 before insert on emp
3 begin
4 if
5 (to_char(sysdate,'DY') in ('SAT','SUN') )or
6 (to_char(sysdate,'hh24:mi') not between '08:00' and '18:00')
7 then raise_application_error(-20500,'you may not update on
holidays');
8 end if;
9* end;
605
Running
606
DML Triggers Example2
607
Try to update emp
608
Packages
609
Simple Package Example
Package created.
610
Execute a Package
611
Thank You
612
ADDITIONAL SLIDES
613
614
Oracle 9i New Features
Quick Overview
MERGE Statement
616
MERGE Syntax
617
MERGE Clauses
ON (condition)
UPDATE SET column = expr, column =
expr...
INSERT (column, column) = (expr, expr)
618
MERGE Example (from doc)
ON (D.employee_id = S.employee_id)
WHEN MATCHED THEN UPDATE SET D.bonus =
D.bonus + S.salary*.01
WHEN NOT MATCHED THEN INSERT
(D.employee_id, D.bonus) VALUES
(S.employee_id, S.salary*0.1);
619
Multi-Table Insert
620
Multi-Table Insert (2)
621
Pipelined Table Functions
PIPELINED keyword
• FUNCTION extract RETURN
t_input_table PIPELINED IS
Return a defined type
PIPE/ PIPE ROW statements
Reference the function in a SELECT,
INSERT, UPDATE, DELETE statement
623
PTF Example (1)
624
PTF Example (2)
625
Pipelined Table Function
Restrictions
You can only perform DML or DDL in a PTF if the
function is declared as AUTONOMOUS
TRANSACTION
You cannot perform DML on a PTF – natively.
You can create a view on the PTF with an
INSTEAD OF trigger.
You cannot have fan-out. w/o a staging table
FUNC1--+FUNC2
|
+FUNC3
626
Parallel PTF
627
Parallel PTF Restrictions
628
External Tables
629
External Tables -- Benefits
630
External Tables -- Operations
631
External Tables -- Limitations
Read only
You cannot index an External Table
632
External Tables --
Implemenation
1. You must use the CREATE DIRECTORY
command to specify an alias for the OS
directory where the data file (and log file and
bad files) is located.
2. You must grant appropriate read/write
permissions on the directories that the files
are located in to the user that is going to
create the External Table
3. Create the External Table using the
CREATE TABLE ... ORGANIZATION
EXTERNAL command.
633
Native Compiled PL/SQL
634
Native Complied PL/SQL
Implementation
Set up a bunch of init.ora parameters
• PLSQL_COMPILER_FLAGS
– DEBUG|NON_DEBUG, INTERPRETED|
NATIVE
• PLSQL_NATIVE_C_COMPILER
• PLSQL_NATIVE_LIBRARY_DIR
• PLSQL_NATIVE_LIBRARY_SUBDIR_COUNT
• PLSQL_NATIVE_LINKER
• PLSQL_NATIVE_MAKE_FILE_NAME
• PLSQL_NATIVE_MAKE_UTILITY
635
Native Complied PL/SQL
Implementation (2)
Once the parameters are setup all you
have to do is recompile all of the database
objects
• utlirp.sql script provided by oracle (run
during your install or upgrade)
636
Native Compiled PL/SQL
Limitations
Only speeds up computation-intensive
PL/SQL
May slow down DML intensive code
637
ANSI Standard Joins
638
Nested Collections
639
Index Skip-Scans
640
Index Skip-Scans (2)
641
Implementing Index Skip-Scans
642
Bitmap Join Indexes
643
Bitmap Join Index -- Why
644
Bitmap Join Index v.s. M Views
645
Bitmap Join Indexes
Restrictions
Must be created on one table in the join (call it
the fact table)
T The bitmap join index must be local parititoned
with the fact table (or unpartitioned if the fact
table is not partitioned)
No table can appear twice in the FROM clause
All joins are equi-joins and are connected by
ANDs only (no ORs)
646
Bitmap Join Index Restrictions
(2)
All restictions on regular Bitmap Indexes are in
force (for example: They cannot be UNIQUE
indexes)
The fact table may not be an INDEX-BY table (but
can reference them)
Each column in a composite key must be in the
join index
Function-based bitmap join indexes are not
permitted.
Temporary bitmap join indexes are not permitted.
647
iSQL*Plus
648
For DBAs
Automatic UNDO Management
650
Automatic UNDO Management
Implementation -- Upgrades
Drop your rollback segments
Create at least one UNDO tablespace
• You must have at least one UNDO
tablespace (otherwise SYSTEM tablespace
is used.
• The UNDO tablespace must be locally
managed.
• You can have multiple UNDO tablespaces,
but it is recommended that you have only
1, if possible.
Delete the ROLLBACK_SEGMENTS parameter
from the init.ora file
651
Shutdown and restart the database.
Automatic UNDO Management
Implementation – New Install
When creating the database, use the
UNDO TABLESPACE syntax of the
CREATE DATABASE command.
652
Automatic UNDO Management
Installation -- Common
Add “UNDO_MANAGEMENT = auto” to
your init.ora file
Add the UNDO_TABLESPACE parameter
to your init.ora file
653
UNDO_RETENTION
654
Automatic UNDO and Recovery
655
Quotas on UNDO Tablespaces
657
UNDO Dangers (2)
658
UNDO Benefits
661
Resumable Conditions
Out of Space
• ORA-1650 unable to extend rollback segment ... in
tablespace ...
• ORA-1653 unable to extend table ... in tablespace
• ORA-1654 unable to extend index ... in tablespace
Maximum Extents Reached
• ORA-1628 max # extents ... reached for rollback
segment ...
• ORA-1631 max # extents ... reached in table ...
• ORA-1654 max # extents ... reached in index ...
Space Quota Exceeded
• ORA-1536 space quote exceeded for tablespace
string
662
Resumable Operations (1)
663
Resumable Operations (2)
665
Resumable Implementation
666
OEM Improvements
Significantly Faster
Improved interface
Improved integration of tools
667
Index Operations
668
Online Table Reorganizations
669
DBMS_METADATA
670
DBMS_METADATA (2)
671
DBMS_METADATA (2)
673
... but there are many more new features in
Oracle 9i
674
Fundamentals of Relational
Database Design and
Database Planning
Outline
Definitions
Selecting a dbms
Selecting an application layer
Relational Design
Planning
A very few words about Replication
Space
676
Definitions
What is a database?
A database is the implementation of freeware or
commercial software that provides a means to
organize and retrieve data. The database is
the set of physical files in which all the objects
and database metadata are stored. These files
can usually be seen at the operating system
level. This talk will focus on the organize
aspect of data storage and retrieval.
Commercial vendors include MicroSoft and
Oracle.
Freeware products include mysql and postgres.
For this discussion, all points/issues apply to
both commercial and freeware products.
677
Definitions
Instance
A database instance, or an ‘instance’ is
made up of the background processes
needed by the database software.
These processes usually include a
process monitor, session monitor, lock
monitor, etc. They will vary from database
vendor to database vendor.
678
Definitions
What is a schema?
A SCHEMA IS NOT A DATABASE, AND A DATABASE IS NOT A
SCHEMA.
A database instance controls 0 or more databases.
A database contains 0 or more database application schemas.
A database application schema is the set of database objects that
apply to a specific application. These objects are relational in
nature, and are related to each other, within a database to serve
a specific functionality. For example payroll, purchasing,
calibration, trigger, etc. A database application schema not a
database. Usually several schemas coexist in a database.
A database application is the code base to manipulate and retrieve
the data stored in the database application schema.
679
Definitions Cont.
Primary Definitions
Table, a set of columns that contain data. In the
old days, a table was called a file.
Row, a set of columns from a table reflecting a
record.
Index, an object that allows for fast retrieval of
table rows. Every primary key and foreign key
should have an index for retrieval speed.
Primary key, often designated pk, is 1 or more
columns in a table that makes a record unique.
680
Definitions Cont.
Primary Definitions
Foreign key, often designated fk, is a common
column common between 2 tables that define
the relationship between those 2 tables.
Foreign keys are either mandatory or optional.
Mandatory forces a child to have a parent by
creating a not null column at the child.
Optional allows a child to exist without a
parent, allowing a nullable column at the child
table (not a common circumstance).
681
Definitions Cont.
Primary Definitions
Entity Relationship Diagram or ER is a
pictorial representation of the application
schema.
682
Er Example
MODULE REVISION
STATUS # MODULE_ID # REV_ID
# STAT_ID may have
describes * MODULE_NAME o REV_NAME
o STATUS_NAME * REV_DATE
* CREATE_DATE
* CREATE_DATE associated with
has * CREATE_USER * CREATE_DATE
* CREATE_USER ... * CREATE_USER
... o UPDATE_DATE
o UPDATE_USER
associated with
have
own part of
PARAMETER
OWNER # PAR_ID
# OWNER_ID
* PAR_NAME
* FIRST_NAME
* TEXT UNIT
* LAST_NAME # UNIT_ID
* VALUE
* PASSWORD
o UPPER_LIMIT have * UNIT_NAME
* EMAIL * CREATE_DATE
o LOWER_LIMIT describes
* USERNAME * CREATE_USER
* SRC
* CREATE_DATE * UPDATE_DATE
* DOCUMENTATION
* CREATE_USER o UPDATE_USER
o DRAWINGS
...
* CREATE_DATE
* CREATE_USER
creates
...
has
has describes
HISTORY
# HIST_ID
* DATE_CHANGED
* REASON
* CREATE_DATE
683 * CREATE_USER
o UPDATE_DATE
o UPDATE_USER
Definitions Cont.
Primary Definitions
Constraints are rules residing in the
database’s data dictionary governing
relationships and dictating the ways
records are manipulated, what is a
legal move vs. what is an illegal
move. These are of the utmost
importance for a secure and
consistent set of data.
684
Definitions Cont.
Primary Definitions
Data Manipulation Language or DML, sql
statements that insert, update or delete
database in a database.
Data Definition Language or DDL, sql used
to create and modify database objects
used in an application schema.
685
Definitions Cont.
Primary Definitions
A transaction is a logical unit of work that
contains one or more SQL statements. A
transaction is an atomic unit. The effects
of all the SQL statements in a transaction
can be either all committed (applied to the
database) or all rolled back (undone from
the database), insuring data consistency.
686
Definitions Cont.
Primary Definitions
A view is a selective presentation of the
structure of, and data in, one or more
tables (or other views). A view is a ‘virtual
table’, having predefined columns and
joins to one or more tables, reflecting a
specific facet of information.
687
Definitions Cont.
Primary Definitions
Database triggers are PL/SQL, Java, or C
procedures that run implicitly whenever a table
or view is modified or when some user actions
or database system actions occur. Database
triggers can be used in a variety of ways for
managing your database. For example, they
can automate data generation, audit data
modifications, enforce complex integrity
constraints, and customize complex security
authorizations. Trigger methodology differs
between databases.
688
Definitions Cont.
Primary Definitions
689
Definitions Cont.
691
Definitions Cont.
692
Selecting a DBMS
693
Selecting a DBMS
How do I Choose?
Which database product is appropriate for my
application? You must make a requirements
assessment.
Does you database need 24x7 availability?
Is your database mission critical, and no data loss
can be tolerated?
Is your database large? (backup recovery methods)
What data types do I need? (binary, large objects?)
Do I need replication? What level of replication is
required? Read only? Read/Write? Read/Write is
very expensive, so can I justify it?
694
Selecting a DBMS
How do I Choose? Cont.
If your answer to any of the above is ‘yes’, I would
strongly suggest purchasing and using a
commercial database with support. Support
includes:
24x7 assistance with technical issues
Patches for bugs and security
The ability to report bugs, and get them resolved in a
timely manner.
Priority for production issues
Upgrades/new releases
Assistance with and use of proven backup/recovery
methods
695
Selecting a DBMS
The Freeware Choice
Freeware is an alternative for applications.
However, be fore warned, support for
these databases is done via email to a ad
hoc support group. The level of support
via these groups may vary over the life of
your database. Be prepared. Also expect
less functionality than any commercial
product. See
http://www-css.fnal.gov/dsg/external/free
ware/
696
Selecting a DBMS
The Freeware Choice
Freeware is free.
Freeware is open source.
Freeware functionality is improving.
Freeware is good for smaller non-mission
critical applications.
697
Selecting an Application Layer
698
Selecting an Application Layer
699
Selecting an Application Layer Cont.
701
Relational Design
702
Relational Design
The Setup
The database group has a standard 3 tier
infrastructure for developing and deploying
production databases and applications. This
infrastructure provides 3 database instances,
development, integration and production.
This infrastructure is applicable to any
application schema, mission critical or not.
It is designed to insure development,
testing, feedback, signoff, and an protected
production environment.
Each of these instances contain 1 or more
applications.
703
Relational Design
The Setup
The 3 instances are used as follows:
Development instance. Developers
playground. Small in size compared to
production. Much of the data is
‘invented’ and input by the developers.
Usually there is not enough disk space
to ever ‘refresh’ with production data.
704
Relational Design Cont.
The Setup
2. The integration instance is used for
moving what is thought to be
‘complete’ functionality to a pre
production implementation. Power
users and developers work in concert
in integration to make sure the specs
were followed. The users should use
integration as their sign off area. Cuts
from dev to int are frequent and
common to maintain the newest
releases in int for user testing.
705
Relational Design Cont.
The Setup
3. The production instance, real data.
Needs to be kept pure. NO testing
allowed. Very few logons. The optimal
setup of a production database server
machine has ~3 operating system
logons, root, the database logon (ie
oracle), and a monitoring tool. In a
critical 24x7 supported database,
developers, development tools, web
servers, log files, all should be kept off
the production database server.
706
Relational Design Cont.
The Setup
Let’s talk about mission critical & 24x7 a bit.
To optimize a mission critical 24/7 database, the database
server machine should be dedicated to running the
database, nothing else.
All software products need maintenance and downtime.
Resist putting software products on the db server
machine so that their maintenance does not inhibit the
running of the database. Further, if the product breaks,
it could inhibit access to the database for a long
period. Example, a logging application, monitoring
users on the db goes wild, fills all available space and
halts the database. If this logging app. were not on the
dbserver machine, the db would be unaffected by the
malfunction.
707
Relational Design Cont.
The Setup
3. All database applications and database software require
modifications. Most times these modification require
down time because the schema or data modifications
need to lock entire tables exclusively. If you are sharing
your database instance with other many other
applications, and 1 of those applications needs the
database for an upgrade, all apps may have to take the
down time. Avoid this by insuring your 24/7 database
application is segregated from all other software that is
not absolutely needed. In that way you insure any down
times are specific to your cause.
708
A cpu can
Our 1st relational example
house
1 or more
databases Databases schema
on d0ora2 applications in
CPU d0ofprd1
(d0ofprd1,
(d0ora2) (sam, runs, calib)
d0ofint1)
An database can
accommodate 1 or
schema
more instances An instance may applications in
contain 1 or more
application d0ofint1
schemas
709 (sam, runs, calib)
What is a schema?
It is It is not
Tables (columns/datatypes) having •The environment (servers, OS)
Constraints (not null, unique, foreign & •The results of queries, I.e objects
primary keys)
•Application Code
Triggers
Indexes
etc.
Accounts
Privileges & Roles
Server side processes
710
Relational Design
Getting Started
Using your design tool, you will begin by relating objects that will
eventually become tables. All the other schema objects will
fall out of this design.
You will spend LOADS of time in your design tool, honing,
redoing, reacting to modifications, etc.
The end users and the designers need to be working almost at the
same desk for this process. If the end user is the designer, the
end user should involve additional users to insure an
unbiased and general design.
It is highly suggested that the design be kept up to date for future
documentation and maintainers.
Tables are related, most frequently in a 0 to many relationship.
Example, 1 run will result in 0 or more events. Analyzing and
defining these relationships results in an application schema.
711
What will a good schema design buy
you?
I am afraid the 80% planning 20% implementation
rule applies. Gather requirements.
Discovery of data that needs to be gathered.
Fast query results
Limited application code maintenance
Data flexibility
Less painful turnover of application to new
maintainers.
Fewer long term maintenance issues.
712
Relational Design
Let’s get started
Write a requirements document.
You will not be able to anticipate all
requirements, but a document will be a start. A
well designed schema naturally allows for
additional functionality.
Who are the users? What is their mission?
Identify objects that need to be stored/tracked.
Think about how objects relate to each other.
Do not be afraid to argue/debate the
relationships with others.
713
Relational Design
So how do you get there?
Design tools are available, however, they do not think for
you. They will give you a clue that you are doing
something stupid, but it won’t stop you. It is highly
recommended you use a design tool.
A picture says 1000 words. Create ER, entity relationship,
diagrams.
Get a commitment from the developer(s) to see the
application through to implementation. We have seen
several applications redone multiple times. A string of
developers tried, left the project, and left a mess. A new
developer started from scratch because there was no
documentation or design.
714
Relational Design
How do I get there?
Adhere to the recommendations of your database
vendor for setup and architecture.
Don’t be afraid to ask for help or to see other
examples.
Don’t be afraid to pilfer others design work, if it is
good, if it closely fits your requirements, then use
it.
Ask questions, schedule reviews with experts and
users.
Work with your hardware system administrators to
insure you have the hardware you need for the
proposed job to be done.
715
Relational Design
Common Mistakes
Mistakes we see ALL the time
Do not design your schema around your favorite
query. A relational design will enable all
queries to be speedy, not only your favorite.
Don’t design the schema around your narrow
view of the application. Get other users
involved from the start, ask for input and
review.
716
Relational Design
Common Mistakes
Create a relational structure, not a
hierarchical structure. The ER
diagram should not necessarily
resemble a tree or a circle. It is the
logical building of relationships
between data. Relationships flow
between subsets of data. The
resulting ER diagram’s ‘look’ is not
a standard by which one can judge
the quality of the design.
717
Relational Design
Common Mistakes
Do not create 1 huge table to hold 99% of
the data. We have seen a table with 1100+
columns…unusable, unqueryable,
required an entire application rewrite,
took over a year, made 80 tables from the
1 table.
Do not create separate schemas for the
same application or functions within an
application.
Use indices and constraints, this is a
MUST!
718
Relational Design
Examples of Common Mistakes
Using timestamp as the primary key assumes
that within a second, no other record will be
inserted. Actually this was not the case, and an
insert operation failed. Use database
generated sequences as primary keys and
NON-UNIQUE index on timestamp.
A table with more than 900 columns. Such design
will cause chaining since each record is not
going to fit in one block. One record spanning
many blocks, thus chaining, hence bad
performance.
719
Relational Design
Examples of Common Mistakes
Do not let the application control a generated
sequence. Have seen locking issues, and
duplicate values issues when the application
increments the sequence. Have the database
increment/lock/constrain the sequence/primary
key. That is why the databases have sequence
mechanisms, use them.
Use indices! An Atlas table with 200,000 rows,
halted during a query. Reason? No indices.
Added a primary key index, instantaneous
query response. Indices are not wasted space!
720
Relational Design
Examples of Common Mistakes
USE DATABASE CONSTRAINTS!!!!!!
Have examples where constraints were not used,
but ‘implemented’ via the api. Bugs in the api
allowed data to be deleted that should not
have been deleted, and constraints would have
prevented the error. Have also seen apis error
with ‘cannot delete’ errors. They were trying to
force an invalid delete, luckily the database
constraints saved the data.
721
Entity Relationship Diagrams
1 to many
PARENT have CHILD
# PARENT_ID belong to # CHILD_ID
A have B
# A_ID # B_ID
belong to
C have D
# C_ID # D_ID
belong to
E have F
# E_ID # F_ID
belong to
722
Entity Relationship Diagrams
many to many
define H
G
# G_ID # H_ID
owned by
define
I J
# I_ID relate to # J_ID
I2 define map to
I2J2 J2
# I2_ID # J2_ID
map to define
723
Entity Relationship Diagrams
1 to 1
K define L
# K_ID # L_ID
relate to
M define
N
# M_ID # N_ID
relate to
O define
# O_ID
P
relate to # P_ID
724
Relational Design
The Good
CALIB_TYPE CALIBRATION
# CALIB_TYPE_ID # CALIBRATION_ID
* DESCRIPTION define * TSTART
o TEND
be defined by
You have now created 3 different children, all reporting the same information, when 1 child would
suffice. Code will have to be written, tested, and maintained for 4 tables now instead of 2.
726
Relational Design
The Ugly
CALIBRATION CALIBRATION(2) CALIBRATION(3)
# CALIBRATION_ID # CALIBRATION_ID # CALIBRATION_ID
* TSTART * TSTART * TSTART
o TEND o TEND o TEND
defines defines
defines
Now you have created 3 different applications, using 6 tables. All of which could be managed with 2 tables.
Extra code, extra testing, extra maintenance.
727
Relational Design
The Good…let’s recap
CALIB_TYPE CALIBRATION
# CALIB_TYPE_ID # CALIBRATION_ID
* DESCRIPTION define * TSTART
o TEND
be defined by
728
Relational Design
What to expect from a design tool
An entity relationship diagram
The ability to create the ddl (data
definition language) needed
The ability to project disk space usage
Ddl in a format to allow you to enter the
code into a code library (cvs), and that will
allow you to run against your database
729
Relational Design Why bother?
Experience from RunII
TO SAVE TIME AND PRECIOUS PEOPLE
RESOURCES!
Personnel consistency does not exist. Application
developers come and go regularly. The
documentation that a design product provides will
the next developer an immediate understanding of
the application in picture format.
Application sharing is enhanced when others can
look at your design and determine whether the
application is reusable in their environment. Sam is
a good example of an application that 3
experiments are now using.
730
Relational Design
Why bother? Cont.
When an application is under
construction, the ER diagram goes to
every application meeting, and quite
possibly the wallet of the application
leader. It is the pictorial answer to many
issues.
Planning for disk space has been an
issue, the designer tool should assist with
this task.
731
Planning
Overall
What do I need to plan for?
People, hardware, software, obsolescence,
maintenance, emergencies.
How far out do I need to plan?
Initially 2-4 years.
How often do I need to review the plans?
Annually.
What if my plan fails or looks undoable?
Nip it in the bud, be proactive, come up with
options.
732
Planning
Overall
Disk space requirements. My experience is all the
wags, (wild guesses) fall short of what is needed. It
is hard to predict the number of rows in a table. It
would be easier if we knew the amount and results
of the science ahead of time! Remember, 10x what
you think the data will take.
Hardware requirements. Experience tells us that the
database machine should serve 1 master (if it is a
large database or mission critical), the database,
nothing else. Ideally there will be root, a database
monitor user and a database user, oracle for
example. No apache, no log file areas, no
applications, etc.
733
Planning
Overall
Growth and obsolesce. Plan for 3-4 years before
needing to replace hardware. Hardware and
software become obsolete. New/upgraded software
gives addition functionality that you will want/need.
Maintenance. Do you change the oil in your car? Plan
on 1 morning per month downtime for caring for
the hardware and software. Security patches could
mandate additional stoppages. I cannot stress how
important this is. Fire walling will not protect you
from bugs and obsolescence. If the downtime is
not needed, it will not be taken. Planning
maintenance time is as important as planning to
buy disks.
734
Planning
User Requirements
Will user requirements influence your
hardware & software decisions?
Do you need replication?
What architecture is your api going to be?
How many users will be loading the
database and hardware?
735
Planning
Maintenance
Database/Operating system software need
upgrades. One always hopes one can get
on a stable version of something and not
upgrade. That is a fallacy. Major version
upgrades provide needed and new
functionality. Bug patches and security
patches are a never ending fact of life.
736
Planning
Backup and Recovery
Backup and recovery procedures of vldb
(very large databases) are difficult at best.
Vldb is normally defined as mulitple Gig
or tera byte databases. This is probably
the most sensitive area when choosing a
freeware database.
Hardware plays a part here as well. Insure
when planning for hardware there is plan
for backup and recovery. Disk and tape
may be needed.
737
Planning
Good Practices with a Hammer
Make a standards document and enforce
its use. When dbas and developers are
always on the same page, life is easier for
both. Expectations are clear and defined.
Anger and disappointment are lessened.
System as well as database standards
need to be followed and enforced.
738
Planning
Failover
Yikes, we are down!
Everyone always wants 24x7 scheduled uptime.
Until they see the cost.
Make anyone who insists on real 100% uptime to
justify it (and pay for it?). 98-99% uptime can
be realized at a much lower cost.
Uptime requirements will influence, possibly
dictate, database choices, hardware choices,
fte requirements.
739
Planning
Failover
The cheapest method of addressing a failure is proactive
planning.
Make sure your database and database software are backed
up. Unless you are using a commercial database with
roll forward recovery, assume you will lose all dml since
your last backup if you need to recover. This should
dictate your backup schedule.
Do not forget tape backups as a catastrophic recovery
method.
Practice recovery on your integration and development
databases. Practice different scenarios, delete a datafile,
delete the entire database.
740
Replication
741
Replication Cont.
743
Replication cont.
745
Lost in Space
746
Lost In Space cont.
N Gb 8 x N Gb Unexpected?
748