Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 740

Oracle 9i

Oracle 9i Course - Objectives


• Introduction to the Object Relational Database
Technology

• Acquaintance with Oracle 9i environment

• Understanding SQL and PL-SQL

• Ability to write SQL queries and PL-SQL programs to


achieve a desired action.

• Familiarity with some of the advanced features in


Oracle 9i

• Awareness of the path for continued learning

2
Oracle 9i Course – Target Audience
• Officers from any of the streams:

 Engineering
 Accounts
 Administration

• Prior knowledge of any of the


following:
 A database such as
MS-Access, d-Base,
FoxPro.
 Any Programming
language such as C,
3 C++ , Java
Introduction to Database
Technology
Objectives
After completing this lesson, you should be
able to do the following:
• Discuss the theoretical and physical aspects
of a relational database
• Describe the Oracle implementation of the
RDBMS and ORDBMS
• Describe how SQL and PL/SQL are used in
the Oracle product set
• Describe the use and benefits of PL/SQL

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

Electronic Filing cabinet


spreadsheet
8
Relational Database Concept

• Dr. E. F. Codd proposed the relational model


for database systems in 1970.
• It is the basis for the relational database
management system (RDBMS).
• The relational model consists of the following:
– Collection of objects or relations
– Set of operators to act on the relations
– Data integrity for accuracy and consistency

9
Relational Database Definition
A relational database is a collection of
relations or two-dimensional tables.
Database

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

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

EMPLOYEE assigned to DEPARTMENT


#* number #* number
* name * name
composed of
o job title o location

• 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”

EMPLOYEE assigned to DEPARTMENT


#* number #* number
* name * name
composed of
o job title o location

Unique Identifier (UID)


Primary marked with “#”
Secondary marked with “(#)”
13
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”

EMPLOYEE assigned to DEPARTMENT


#* number #* number
* name * name
composed of
o job title o location

Unique Identifier (UID)


Primary marked with “#”
Secondary marked with “(#)”
14
Relational Database Terminology
2 3 4
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
6
------------- ------------ --------------------- -------- ---------------- ----------- -------------- -----------
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 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 5 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
1 7934 MILLER CLERK 7782 23-JAN-82 1300 10

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

Primary key Foreign key Primary key


16
Relational Database Properties

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

User tables Data


dictionary
19
Object Relational Database
Management System
• User-defined data types and objects
• Fully relational compatible
• Support of multimedia and large objects
• High-quality database server features

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

SQL PL/SQL SQL* Plus Java

Oracle 7.3 / 8 / 8i / 9i / 10g

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

GRANT Data control language (DCL)


REVOKE
26
About PL/SQL

• PL/SQL is an extension to SQL with


design features of programming
languages.
• Data manipulation and query statements
of SQL are included within procedural
units of code.

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

SQL Statement Executor

Oracle Server

28
Benefits of PL/SQL

Integration

Application

Shared Oracle Server


library

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

• To return the minimum and maximum salaries


for the clerks in each department, issue the
following statement:
SELECT department_id, MIN(salary),
MAX (salary)
FROM employees
WHERE job_id = 'PU_CLERK'
GROUP BY department_id;
35
PL-SQL Example: Task

• 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

PLACE LAT LONG


PLACE LAT LONG
ADILABAD 0.343 1.371
NALGONDA 0.298 1.385
ANANTAPUR 0.256 1.355
NELLORE 0.244 1.397
CHITTOOR 0.231 1.381
CUDDAPAH 0.253 1.376 NIZAMABAD 0.326 1.364
GUNTUR 0.285 1.404 SRIKAKULAM 0.320 1.466
HYDERABAD 0.300 1.368 TIRUPATI 0.239 1.385
KAKINADA 0.296 1.436
VIJAYAWADA 0.289 1.407
KARIMNAGAR 0.322 1.380
VISAKHAPATNAM 0.309 1.455
KHAMMAM 0.301 1.399
VIZIANAGARAM 0.316 1.457
KURNOOL 0.276 1.363
MAHBUBNAGAR 0.292 1.361 WARANGAL 0.314 1.391

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

After completing this lesson, you should


be able to do the following:
• List the capabilities of SQL SELECT
statements
• Execute a basic SELECT statement
• Differentiate between SQL statements
and SQL*Plus commands

42
Capabilities of SQL SELECT
Statements
Selection Projection

Table 1 Table 1
Join

Table 1 Table 2
43
Basic SELECT Statement

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


FROM table;

• SELECT identifies what columns


• FROM identifies which table

44
Writing SQL Statements

• SQL statements are not case sensitive.


• SQL statements can be on one or
more lines.
• Keywords cannot be abbreviated or split
across lines.
• Clauses are usually placed on
separate lines.
• Tabs and indents are used to enhance
readability.
45
Selecting All Columns

SQL> SELECT *
2 FROM dept;

DEPTNO DNAME LOC


--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

46
Selecting Specific Columns

SQL> SELECT deptno, loc


2 FROM dept;

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

SQL> SELECT ename, sal, sal+300


2 FROM emp;

ENAME SAL SAL+300


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

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

SQL> SELECT ename, sal, 12*sal+100


2 FROM emp;

ENAME SAL 12*SAL+100


---------- --------- ----------
KING 5000 60100
BLAKE 2850 34300
CLARK 2450 29500
JONES 2975 35800
MARTIN 1250 15100
ALLEN 1600 19300
...
14 rows selected.

52
Using Parentheses

SQL> SELECT ename, sal, 12*(sal+100)


2 FROM emp;

ENAME SAL 12*(SAL+100)


---------- --------- -----------
KING 5000 61200
BLAKE 2850 35400
CLARK 2450 30600
JONES 2975 36900
MARTIN 1250 16200
...
14 rows selected.

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;

ENAME JOB COMM


---------- --------- ---------
KING PRESIDENT
BLAKE MANAGER
...
TURNER SALESMAN 0
...
14 rows selected.
54
Null Values in Arithmetic
Expressions
Arithmetic expressions containing a null
value evaluate to null.

SQL> select ename NAME, 12*sal+comm


2 from emp
3 WHERE ename='KING';

NAME 12*SAL+COMM
---------- -----------
KING

55
Defining a Column Alias

• Renames a column heading


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

56
Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM emp;

NAME SALARY
------------- ---------
...

SQL> SELECT ename "Name",


2 sal*12 "Annual Salary"
3 FROM emp;

Name Annual Salary


------------- -------------
...
57
Concatenation Operator

• Concatenates columns or character


strings to other columns
• Is represented by two vertical bars (||)
• Creates a resultant column that is a
character expression

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

• A literal is a character, expression, or


number included in the SELECT list.
• Date and character literal values must
be enclosed within single quotation
marks.
• Each character string is output once for
each row returned.

60
Using Literal Character Strings

SQL> SELECT ename ||' '||'is a'||' '||job


2 AS "Employee Details"
3 FROM emp;

Employee Details
-------------------------
KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
MARTIN is a SALESMAN
...
14 rows selected.

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

SQL*Plus Query Results


Commands
Formatted Report

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

SQL SQL SQL*Plus SQL*Plus


statements buffer commands buffer

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:

• From command line:


sqlplus [username[/password
[@database]]]
67
Displaying Table Structure

Use the SQL*Plus DESCRIBE command to


display the structure of a table.

DESC[RIBE] tablename

68
Displaying Table Structure

SQL> DESCRIBE dept

Name Null? Type


----------------- -------- ------------
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

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

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


FROM table;

Use SQL*Plus as an environment to:


• Execute SQL statements
• Edit SQL statements

73
Practice Overview

• Selecting all data from different tables


• Describing the structure of tables
• Performing arithmetic calculations and
specifying column names
• Using SQL*Plus editor

74
Restricting and Sorting Data
Objectives

After completing this lesson, you should


be able to do the following:
• Limit the rows retrieved by a query
• Sort the rows retrieved by a query

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

7839 KING PRESIDENT 10


7782 CLARK MANAGER 10
7934 MILLER CLERK 10

78
Limiting Rows Selected
• Restrict the rows returned by using the
WHERE clause.

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


FROM table
[WHERE condition(s)];

• The WHERE clause follows the FROM


clause.

79
Using the WHERE Clause

SQL> SELECT ename, job, deptno


2 FROM emp
3 WHERE job='CLERK';

ENAME JOB DEPTNO


---------- --------- ---------
JAMES CLERK 30
SMITH CLERK 20
ADAMS CLERK 20
MILLER CLERK 10

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'

SQL> SELECT ename, job, deptno


2 FROM emp
3 WHERE ename = 'JAMES';

81
Comparison Operators

Operator Meaning

= Equal to

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<> Not equal to

82
Using the Comparison
Operators

SQL> SELECT ename, sal, comm


2 FROM emp
3 WHERE sal<=comm;

ENAME SAL COMM


---------- --------- ---------
MARTIN 1250 1400

83
Other Comparison Operators

Operator Meaning

BETWEEN Between two values (inclusive)


...AND...

IN(list) Match any of a list of values

LIKE Match a character pattern

IS NULL Is a null value

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.

SQL> SELECT empno, ename, sal, mgr


2 FROM emp
3 WHERE mgr IN (7902, 7566, 7788);

EMPNO ENAME SAL MGR


--------- ---------- --------- ---------
7902 FORD 3000 7566
7369 SMITH 800 7902
7788 SCOTT 3000 7566
7876 ADAMS 1100 7788

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

SQL> SELECT ename


2 FROM emp
3 WHERE ename LIKE 'S%';

87
Using the LIKE Operator

• You can combine pattern matching


characters.
SQL> SELECT ename
2 FROM emp
3 WHERE ename LIKE '_A%';

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

• You can use the ESCAPE identifier to


search for "%" or "_".
88
Using the IS NULL Operator

Test for null values with the IS NULL


operator

SQL> SELECT ename, mgr


2 FROM emp
3 WHERE mgr IS NULL;

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

89
Logical Operators

Operator Meaning

AND Returns TRUE if both component


conditions are TRUE
OR Returns TRUE if either component
condition is TRUE

NOT Returns TRUE if the following


condition is FALSE

90
Using the AND Operator
AND requires both conditions to be TRUE.

SQL> SELECT empno, ename, job, sal


2 FROM emp
3 WHERE sal>=1100
4 AND job='CLERK';

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7876 ADAMS CLERK 1100
7934 MILLER CLERK 1300

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';

EMPNO ENAME JOB SAL


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

7839 KING PRESIDENT 5000


7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7566 JONES MANAGER 2975
7654 MARTIN SALESMAN 1250
...
14 rows selected.
92
Using the NOT Operator

SQL> SELECT ename, job


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

ENAME JOB
---------- ---------
KING PRESIDENT
MARTIN SALESMAN
ALLEN SALESMAN
TURNER SALESMAN
WARD SALESMAN

93
Rules of Precedence

Order Evaluated Operator


1 All comparison
operators
2 NOT
3 AND
4 OR

Override rules of precedence by using


parentheses.

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

ENAME JOB SAL


---------- --------- ---------
KING PRESIDENT 5000
MARTIN SALESMAN 1250
ALLEN SALESMAN 1600
TURNER SALESMAN 1500
WARD SALESMAN 1250

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;

ENAME JOB SAL


---------- --------- ---------
KING PRESIDENT 5000
ALLEN SALESMAN 1600

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;

ENAME JOB DEPTNO HIREDATE


---------- --------- --------- ---------
SMITH CLERK 20 17-DEC-80
ALLEN SALESMAN 30 20-FEB-81
...
14 rows selected.
97
Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate DESC;

ENAME JOB DEPTNO HIREDATE


---------- --------- --------- ---------
ADAMS CLERK 20 12-JAN-83
SCOTT ANALYST 20 09-DEC-82
MILLER CLERK 10 23-JAN-82
JAMES CLERK 30 03-DEC-81
FORD ANALYST 20 03-DEC-81
KING PRESIDENT 10 17-NOV-81
MARTIN SALESMAN 30 28-SEP-81
...
14 rows selected.

98
Sorting by Column Alias
SQL> SELECT empno, ename, sal*12 annsal
2 FROM emp
3 ORDER BY annsal;

EMPNO ENAME ANNSAL


--------- ---------- ---------
7369 SMITH 9600
7900 JAMES 11400
7876 ADAMS 13200
7654 MARTIN 15000
7521 WARD 15000
7934 MILLER 15600
7844 TURNER 18000
...
14 rows selected.

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;

ENAME DEPTNO SAL


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

• You can sort by a column that is not in the


SELECT list.
100
Summary

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


FROM table
[WHERE condition(s)]
[ORDER BY {column, expr, alias} [ASC|DESC]];

101
Practice Overview

• Selecting data and changing the order


of rows displayed
• Restricting rows by using the WHERE
clause
• Using the double-quotation-marks in
column aliases

102
Single-Row Functions
Objectives

After completing this lesson, you should


be able to do the following:
• Describe various types of functions
available in SQL
• Use character, number, and date
functions in SELECT statements
• Describe the use of conversion
functions

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

Case conversion Character manipulation


functions functions
LOWER CONCAT
UPPER SUBSTR
INITCAP LENGTH
INSTR
LPAD
110
Case Conversion Functions

Convert case for character strings


Function Result
LOWER('SQL Course') sql course
UPPER('SQL Course') SQL COURSE
INITCAP('SQLCourse') Sql Course

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

SQL> SELECT empno, ename, deptno


2 FROM emp
3 WHERE LOWER(ename) = 'blake';

EMPNO ENAME DEPTNO


--------- ---------- ---------
7698 BLAKE 30

112
Character Manipulation Functions

Manipulate character strings


Function Result
CONCAT('Good', 'String') GoodString
SUBSTR('String',1,3) Str
LENGTH('String') 6
INSTR('String', 'r') 3
LPAD(sal,10,'*') ******5000

113
Using the Character
Manipulation Functions

SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename),


2 INSTR(ename, 'A')
3 FROM emp
4 WHERE SUBSTR(job,1,5) = 'SALES';

ENAME CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A')


---------- ------------------- ------------- ----------------
MARTIN MARTINSALESMAN 6 2
ALLEN ALLENSALESMAN 5 1
TURNER TURNERSALESMAN 6 0
WARD WARDSALESMAN 4 2

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

• MOD: Returns remainder of division


MOD(1600, 300) 100

115
Using the ROUND Function

SQL> SELECT ROUND(45.923,2), ROUND(45.923,0),


2 ROUND(45.923,-1)
3 FROM DUAL;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)


--------------- -------------- -----------------
45.92 46 50

116
Using the TRUNC Function

SQL> SELECT TRUNC(45.923,2), TRUNC(45.923),


2 TRUNC(45.923,-1)
3 FROM DUAL;

TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)


--------------- ------------- ---------------
45.92 45 40

117
Using the MOD Function
Calculate the remainder of the ratio of
salary to commission for all employees
whose job title is a salesman.

SQL> SELECT ename, sal, comm, MOD(sal, comm)


2 FROM emp
3 WHERE job = 'SALESMAN';

ENAME SAL COMM MOD(SAL,COMM)


---------- --------- --------- -------------
MARTIN 1250 1400 1250
ALLEN 1600 300 100
TURNER 1500 0 1500
WARD 1250 500 250

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

• Add or subtract a number to or from a


date for a resultant date value.
• Subtract two dates to find the number of
days between those dates.
• Add hours to a date by dividing the
number of hours by 24.

120
Using Arithmetic Operators
with Dates

SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS


2 FROM emp
3 WHERE deptno = 10;

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

LAST_DAY Last day of the month

ROUND Round date

TRUNC Truncate date

122
Using Date Functions
• MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')
19.6774194

• ADD_MONTHS ('11-JAN-94',6) '11-JUL-94'

• NEXT_DAY ('01-SEP-95','FRIDAY') '08-SEP-95'

• 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

Implicit datatype Explicit datatype


conversion conversion

125
Implicit Datatype Conversion

For assignments, Oracle can automatically


convert
From To
VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE

NUMBER VARCHAR2

DATE VARCHAR2

126
Implicit Datatype Conversion

For expression evaluation, Oracle can


automatically convert
From To
VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE

127
Explicit Datatype Conversion
TO_NUMBER TO_DATE

NUMBER CHARACTER DATE

TO_CHAR TO_CHAR

128
TO_CHAR Function with Dates

TO_CHAR(date, 'fmt')

The format model:


• Must be enclosed in single quotation marks
and is case sensitive
• Can include any valid date format element
• Has an fm element to remove padded
blanks or suppress leading zeros
• Is separated from the date value by a
comma
129
Date Format Model Elements

YYYY Full year in numbers

YEAR Year spelled out

MM 2-digit value for month

MONTH Full name of the month


3-letter abbreviation of the day
DY
of the week
DAY Full name of the day

130
Date Format Model Elements

• Time elements format the time portion of


the date.
HH24:MI:SS AM 15:45:32 PM
• Add character strings by enclosing them
in double quotation marks.
DD "of" MONTH 12 of OCTOBER
• Number suffixes spell out numbers.
ddspth fourteenth

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')

Use these formats with the TO_CHAR


function to display a number value as a
character.
9 Represents a number
0 Forces a zero to be displayed
$ Places a floating dollar sign
L Uses the floating local currency symbol
. Prints a decimal point
, Prints a thousand indicator
133
Using TO_CHAR Function
with Numbers

SQL> SELECT TO_CHAR(sal,'$99,999') SALARY


2 FROM emp
3 WHERE ename = 'SCOTT';

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)

• Convert a character string to a date


format using the TO_DATE function

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

If the specified two-digit year is

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

Converts null to an actual value


• Datatypes that can be used are date,
character, and number.
• Datatypes must match
– NVL(comm,0)
– NVL(hiredate,'01-JAN-97')
– NVL(job,'No Job Yet')

137
Using the NVL Function

SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)


2 FROM emp;

ENAME SAL COMM (SAL*12)+NVL(COMM,0)


---------- --------- --------- --------------------
KING 5000 60000
BLAKE 2850 34200
CLARK 2450 29400
JONES 2975 35700
MARTIN 1250 1400 16400
ALLEN 1600 300 19500
...
14 rows selected.

138
DECODE Function

Facilitates conditional inquiries by doing


the work of a CASE or IF-THEN-ELSE
statement
DECODE(col/expression, search1, result1
[, search2, result2,...,]
[, default])

139
Using the DECODE Function

SQL> SELECT job, sal,


2 DECODE(job, 'ANALYST', SAL*1.1,
3 'CLERK', SAL*1.15,
4 'MANAGER', SAL*1.20,
5 SAL)
6 REVISED_SALARY
7 FROM emp;

JOB SAL REVISED_SALARY


--------- --------- --------------
PRESIDENT 5000 5000
MANAGER 2850 3420
MANAGER 2450 2940
...
14 rows selected.

140
Nesting Functions

• Single-row functions can be nested to


any level.
• Nested functions are evaluated from
deepest level to the least deep level.
F3(F2(F1(col,arg1),arg2),arg3)

Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3

141
Nesting Functions

SQL> SELECT ename,


2 NVL(TO_CHAR(mgr),'No Manager')
3 FROM emp
4 WHERE mgr IS NULL;

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

142
Summary

Use functions to:


• Perform calculations on data
• Modify individual data items
• Manipulate output for groups of rows
• Alter date formats for display
• Convert column datatypes

143
Practice Overview

• Creating queries that require the use of


numeric, character, and date functions
• Using concatenation with functions
• Writing case-insensitive queries to test
the usefulness of character functions
• Performing calculations of years and
months of service for an employee
• Determining the review date for an
employee
144
End of Class-4

145
Displaying Data
from Multiple Tables
Objectives

After completing this lesson, you should


be able to do the following:
• Write SELECT statements to access
data from more than one table using
equality and nonequality joins
• View data that generally does not meet a
join condition by using outer joins
• Join a table to itself

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

EMPNO DEPTNO LOC


----- ------- --------
7839 10 NEW YORK
7698 30 CHICAGO
7782 10 NEW YORK
7566 20 DALLAS
7654 30 CHICAGO
7499 30 CHICAGO
...
14 rows selected.

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;

• Write the join condition in the WHERE


clause.
• Prefix the column name with the table
name when the same column name
appears in more than one table.
149
Cartesian Product

• A Cartesian product is formed when:


– A join condition is omitted
– A join condition is invalid
– All rows in the first table are joined to
all rows in the second table
• To avoid a Cartesian product, always
include a valid join condition in a
WHERE clause.

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

Equijoin Non-equijoin Outer join Self join

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.

Primary key Foreign key


153
Retrieving Records
with Equijoins
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;

EMPNO ENAME DEPTNO DEPTNO LOC


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

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;

SQL> SELECT e.empno, e.ename, e.deptno,


2 d.deptno, d.loc
3 FROM emp e, dept d
4 WHERE e.deptno=d.deptno;

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;

ENAME SAL GRADE


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

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;

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;

ENAME DEPTNO DNAME


---------- --------- -------------
KING 10 ACCOUNTING
CLARK 10 ACCOUNTING
...
40 OPERATIONS
15 rows selected.

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

"MGR in the WORKER table is equal to EMPNO in the


MANAGER table"

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

SELECT table1.column, table2.column


FROM table1, table2
WHERE table1.column1 = table2.column2;

Equijoin Non-equijoin Outer join Self join

166
Practice Overview

• Joining tables using an equijoin


• Performing outer and self joins
• Adding additional conditions

167
Aggregating Data
Using Group Functions
Objectives

After completing this lesson, you should


be able to do the following:
• Identify the available group functions
• Describe the use of group functions
• Group data using the GROUP BY clause
• Include or exclude grouped rows by
using the HAVING clause

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%';

AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL)


-------- --------- --------- ---------
1400 1600 1250 5600

174
Using MIN and MAX Functions
You can use MIN and MAX for any datatype.

SQL> SELECT MIN(hiredate), MAX(hiredate)


2 FROM emp;

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.

SQL> SELECT AVG(NVL(comm,0))


2 FROM emp;

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

SELECT column, group_function(column)


FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];

Divide rows in a table into smaller groups


by using the 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;

DEPTNO JOB SUM(SAL)


--------- --------- ---------
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
...
9 rows selected.

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

SQL> SELECT deptno, max(sal)


2 FROM emp
3 GROUP BY deptno
4 HAVING max(sal)>2900;

DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000

190
Using the HAVING Clause

SQL> SELECT job, SUM(sal) PAYROLL


2 FROM emp
3 WHERE job NOT LIKE 'SALES%'
4 GROUP BY job
5 HAVING SUM(sal)>5000
6 ORDER BY SUM(sal);

JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275

191
Nesting Group Functions
Display the maximum average salary.

SQL> SELECT max(avg(sal))


2 FROM emp
3 GROUP BY deptno;

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];

Order of evaluation of the clauses:


• WHERE clause
• GROUP BY clause
• HAVING clause

193
Practice Overview

• Showing different queries that use


group functions
• Grouping by rows to achieve more than
one result
• Excluding groups by using the HAVING
clause

194
Oracle 9i SQL
PPT: 2/3 & 3/3
Subqueries
Objectives

After completing this lesson, you should


be able to do the following:
• Describe the types of problems that
subqueries can solve
• Define subqueries
• List the types of subqueries
• Write single-row and multiple-row
subqueries

198
Using a Subquery
to Solve a Problem
“Who has a salary greater than Jones’s?”

Main Query

“Which employees have a salary greater


? than Jones’s salary?”

Subquery

?
“What is Jones’s salary?”

199
Subqueries
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);

• The subquery (inner query) executes once


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

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

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<> Not 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);

ENAME JOB SAL


---------- --------- ---------
SMITH CLERK 800

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?

SQL> SELECT ename, job


2 FROM emp
3 WHERE job =
4 (SELECT job e s s
5 FROM emp a lu
v
6 WHERE o
ename='SMYTHE');
n
n s
u r
no rows selected e t
r
r y
ue
bq
Su

209
Multiple-Row Subqueries
• Return more than one row
• Use multiple-row comparison operators
Operator Meaning

IN Equal to any member in the list

ANY Compare value to each value returned by


the subquery

Compare value to every value returned by


ALL
the subquery

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';

EMPNO ENAME JOB


--------- ---------- ---------
7654 MARTIN SALESMAN
7521 WARD SALESMAN

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);

EMPNO ENAME JOB


--------- ---------- ---------
7839 KING PRESIDENT
7566 JONES MANAGER
7902 FORD ANALYST
7788 SCOTT ANALYST

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

• Creating subqueries to query values based on


unknown criteria
• Using subqueries to find out what values exist
in one set of data and not in another

214
Producing Readable Output
with SQL*Plus
Objectives

After completing this lesson, you should


be able to do the following:
• Produce queries that require an input
variable
• Customize the SQL*Plus environment
• Produce more readable output
• Create and execute script files
• Save customizations

216
Interactive Reports

I want to input query


...sal = ? … values at runtime.
… deptno = ? …
.. ename = ? ...

User

217
Substitution Variables

• Use SQL*Plus substitution variables to


temporarily store values
– Single ampersand (&)
– Double ampersand (&&)
– DEFINE and ACCEPT commands
• Pass variable values between SQL
statements
• Dynamically alter headers and footers

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;

Enter value for employee_num: 7369

EMPNO ENAME SAL DEPTNO


--------- ---------- --------- ---------
7369 SMITH 800 20

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;

Enter value for employee_num: 7369


old 3: WHERE empno = &employee_num
new 3: WHERE empno = 7369

...

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';

Enter value for job_title: ANALYST

ENAME DEPTNO SAL*12


---------- --------- ---------
SCOTT 20 36000
FORD 20 36000

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;

Enter value for column_name: sal


Enter value for condition: sal>=3000
Enter value for order_column: ename

EMPNO ENAME JOB SAL


--------- ---------- --------- ---------
7902 FORD ANALYST 3000
7839 KING PRESIDENT 5000
7788 SCOTT ANALYST 3000

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;

Enter value for column_name: deptno


EMPNO ENAME JOB DEPTNO
--------- ---------- --------- ---------
7839 KING PRESIDENT 10
7782 CLARK MANAGER 10
7934 MILLER CLERK 10
...
14 rows selected.
224
Defining User Variables
• You can predefine variables using one
of two SQL*Plus commands:
– DEFINE: Create a CHAR datatype user
variable
– ACCEPT: Read user input and store it
in a variable
• If you need to use a single space when
using the DEFINE command, you must
enclose the space within single
quotation marks.
225
The ACCEPT Command

• Creates a customized prompt when


accepting user input
• Explicitly defines a NUMBER or DATE
datatype variable
• Hides user input for security reasons

ACCEPT variable [datatype] [FORMAT format]


[PROMPT text] {HIDE}

226
Using the ACCEPT Command

ACCEPT dept PROMPT 'Provide the department name: '


SELECT *
FROM dept
WHERE dname = UPPER('&dept')
/

Provide the department name: Sales

DEPTNO DNAME LOC


--------- -------------- -------------
30 SALES CHICAGO

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

DEFINE DEPTNAME = "sales" (CHAR)

• Use the variable as you would any other


variable.
SQL> SELECT *
2 FROM dept
3 WHERE dname = UPPER('&deptname');

229
Customizing the SQL*Plus
Environment
• Use SET commands to control current
session.
SET system_variable value

• Verify what you have set by using the


SHOW command.
SQL> SET ECHO ON

SQL> SHOW ECHO


echo ON

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

• COLUMN [column option]


• TTITLE [text | OFF | ON]
• BTITLE [text | OFF | ON]
• BREAK [ON report_element]

233
The COLUMN Command
Controls display of a column
COL[UMN] [{column|alias} [option]]

• CLE[AR]: Clears any column formats


• FOR[MAT] format: Changes the display
of the column using a format model
• HEA[DING] text: Sets the column
heading
• JUS[TIFY] {align}: Aligns the column
heading to be left, center, or right
234
Using the COLUMN Command
• Create column headings.
COLUMN ename HEADING 'Employee|Name' FORMAT A15
COLUMN sal JUSTIFY LEFT FORMAT $99,990.00
COLUMN mgr FORMAT 999999999 NULL 'No manager'

• Display the current setting for the ENAME


column.
COLUMN ename

• Clear settings for the ENAME column.


COLUMN ename CLEAR

235
COLUMN Format Models

Element Description Example Result

An Sets a display width of n N/A N/A

9 Single zero-suppression 999999 1234


digit

0 Enforces leading zero 099999 01234

$ Floating dollar sign $9999 $1234

L Local currency L9999 L1234

. Position of decimal point 9999.99 1234.00

, Thousand separator 9,999 1,234

236
Using the BREAK Command
Suppresses duplicates and sections rows
• To suppress duplicates
SQL> BREAK ON ename ON job

• To produce grand totals


SQL> BREAK ON report

• To section out rows at break values


SQL> BREAK ON ename SKIP 4 ON job SKIP2

237
Using the TTITLE and BTITLE
Commands
Display headers and footers
TTI[TLE] [text|OFF|ON]

• Set the report header


SQL> TTITLE 'Salary|Report'

• Set the report footer


SQL> BTITLE 'Confidential'

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

• Creating a query to display values using


substitution variables
• Starting a command file containing variables
• Using the ACCEPT command

243
Manipulating Data
Objectives

After completing this lesson, you should


be able to do the following:
• Describe each DML statement
• Insert rows into a table
• Update rows in a table
• Delete rows from a table
• Control transactions

245
Data Manipulation Language

• A DML statement is executed when you:


– Add new rows to a table
– Modify existing rows in a table
– Remove existing rows from a table
• A transaction consists of a collection of
DML statements that form a logical unit
of work.

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

• Add new rows to a table by using the


INSERT statement.

INSERT INTO table [(column [, column...])]


VALUES (value [, value...]);

• Only one row is inserted at a time with


this syntax.

248
Inserting New Rows

• Insert a new row containing values for


each column.
• List values in the default order of the
columns in the table.
• Optionally list the columns in the
INSERT clause.
SQL> INSERT INTO dept (deptno, dname, loc)
2 VALUES (50, 'DEVELOPMENT', 'DETROIT');
1 row created.

• Enclose character and date values


within single quotation marks.
249
Inserting Rows with Null Values
• Implicit method: Omit the column from
the column list.
SQL> INSERT INTO dept (deptno, dname )
2 VALUES (60, 'MIS');
1 row created.

• Explicit method: Specify the NULL


keyword.
SQL> INSERT INTO dept
2 VALUES (70, 'FINANCE', NULL);
1 row created.

250
Inserting Special Values
The SYSDATE function records the
current date and time.

SQL> INSERT INTO emp (empno, ename, job,


2 mgr, hiredate, sal, comm,
3 deptno)
4 VALUES (7196, 'GREEN', 'SALESMAN',
5 7782, SYSDATE, 2000, NULL,
6 10);
1 row created.

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.

• Verify your addition.


EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- -------- ---- --------- ---- ---- ------
2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10

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');

Enter value for department_id: 80


Enter value for department_name: EDUCATION
Enter value for location: ATLANTA

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.

• Do not use the VALUES clause.


• Match the number of columns in the
INSERT clause to those in the subquery.
255
Changing Data in a Table
EMP
EMPNO ENAME JOB ... DEPTNO
“…update a row
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30 in EMP table…”
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...

EMP
EMPNO ENAME JOB ... DEPTNO

7839 KING PRESIDENT 10


7698 BLAKE MANAGER 30
7782 CLARK MANAGER 20
10
7566 JONES MANAGER 20
...

256
The UPDATE Statement

• Modify existing rows with the UPDATE


statement.
UPDATE table
SET column = value [, column = value]
[WHERE condition];

• Update more than one row at a time, if


required.

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.

• All rows in the table are modified if you


omit the WHERE clause.
SQL> UPDATE employee
2 SET deptno = 20;
14 rows 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

SQL> UPDATE emp i s t


2 SET deptno = 55 ex
3 WHERE deptno = 10; o t
s n
oe
5 d
r 5
b e
UPDATE emp m
* nut
ERROR at line 1: e
n
r tm
ORA-02291: integrity constraint (USR.EMP_DEPTNO_FK)
pa
violated - eparent key not found
D

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

You can remove existing rows from a


table by using the DELETE statement.
DELETE [FROM] table
[WHERE condition];

263
Deleting Rows from a Table
• Specific row or rows are deleted when
you specify the WHERE clause.

SQL> DELETE FROM department


2 WHERE dname = 'DEVELOPMENT';
1 row deleted.

• All rows in the table are deleted if you


omit the WHERE clause.
SQL> DELETE FROM department;
4 rows deleted.

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

Consist of one of the following


statements:
• DML statements that make up one
consistent change to the data
• One DDL statement
• One DCL statement

267
Database Transactions

• Begin when the first executable SQL


statement is executed
• End with one of the following events:
– COMMIT or ROLLBACK
– DDL or DCL statement executes
(automatic commit)
– User exits
– System crashes

268
Advantages of COMMIT
and ROLLBACK
• Ensure data consistency
• Preview data changes before making
changes permanent
• Group logically related operations

269
Controlling Transactions
Transaction

INSERT UPDATE INSERT DELETE

COMMIT Savepoint A Savepoint B

ROLLBACK to Savepoint B

ROLLBACK to Savepoint A

ROLLBACK
270
Implicit Transaction Processing

• An automatic commit occurs under the


following circumstances:
– A DDL statement is issued
– A DCL statement is issued
– A normal exit from SQL*Plus, without
explicitly issuing COMMIT or
ROLLBACK
• An automatic rollback occurs under an
abnormal termination of SQL*Plus or a
system failure
271
State of the Data Before
COMMIT or ROLLBACK
• The previous state of the data can be
recovered.
• The current user can review the results of
the DML operations by using the SELECT
statement.
• Other users cannot view the results of the
DML statements by the current user.
• The affected rows are locked; other users
cannot change the data within the affected
rows.
272
State of the Data After COMMIT

• Data changes are made permanent in the


database.
• The previous state of the data is
permanently lost.
• All users can view the results.
• Locks on the affected rows are released;
those rows are available for other users to
manipulate.
• All savepoints are erased.
273
Committing Data

• Make the changes.


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

• Commit the changes.


SQL> COMMIT;
Commit complete.

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

• If a single DML statement fails during


execution, only that statement is rolled
back.
• Oracle Server implements an implicit
savepoint.
• All other changes are retained.
• The user should terminate transactions
explicitly by executing a COMMIT or
ROLLBACK statement.
277
Read Consistency
• Read consistency guarantees a
consistent view of the data at all times.
• Changes made by one user do not
conflict with changes made by another
user.
• Ensures that on the same data:
– Readers do not wait for writers
– Writers do not wait for readers

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

INSERT Adds a new row to the table

UPDATE Modifies existing rows in the table

DELETE Removes existing rows from the table

COMMIT Makes all pending changes permanent

SAVEPOINT Allows a rollback to the savepoint marker

ROLLBACK Discards all pending data changes

281
Practice Overview

• Inserting rows into the tables


• Updating and deleting rows in the table
• Controlling transactions

282
Creating and Managing
Tables
Objectives

After completing this lesson, you should


be able to do the following:
• Describe the main database objects
• Create tables
• Describe the datatypes that can be used
when specifying column definition
• Alter table definitions
• Drop, rename, and truncate tables

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

• Must begin with a letter


• Can be 1–30 characters long
• Must contain only A–Z, a–z, 0–9, _, $,
and #
• Must not duplicate the name of another
object owned by the same user
• Must not be an Oracle Server reserved
word

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.

… hiredate DATE DEFAULT SYSDATE, …

• Legal values are literal value, expression,


or SQL function.
• Illegal values are another column’s name or
pseudocolumn.
• The default datatype must match the
column datatype.
289
Creating Tables
• Create the table.
SQL> CREATE TABLE dept
2 (deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13));
Table created.

• Confirm table creation.


SQL> DESCRIBE dept

Name Null? Type


--------------------------- -------- ---------
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)

290
Querying the Data Dictionary
• Describe tables owned by the user.
SQL> SELECT *
2 FROM user_tables;

• View distinct object types owned by the


user.
SQL> SELECT DISTINCT object_type
2 FROM user_objects;

• View tables, views, synonyms, and


sequences owned by the user.
SQL> SELECT *
2 FROM user_catalog;

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;

• Match the number of specified columns


to the number of subquery columns.
• Define columns with column names and
default values.
293
Creating a Table
by Using a Subquery
SQL> CREATE TABLE dept30
2 AS
3 SELECT empno, ename, sal*12 ANNSAL, hiredate
4 FROM emp
5 WHERE deptno = 30;
Table created.

SQL> DESCRIBE dept30

Name Null? Type


---------------------------- -------- -----
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2(10)
ANNSAL NUMBER
HIREDATE DATE

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]...);

ALTER TABLE table


MODIFY (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

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


7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
296
Adding a Column
• You use the ADD clause to add columns.
SQL> ALTER TABLE dept30
2 ADD (job VARCHAR2(9));
Table altered.

• The new column becomes the last column.


EMPNO ENAME ANNSAL HIREDATE JOB
--------- ---------- --------- --------- ----
7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
6 rows selected.

297
Modifying a Column
• You can change a column's datatype,
size, and default value.
ALTER TABLE dept30
MODIFY (ename VARCHAR2(15));
Table altered.

• A change to the default value affects


only subsequent insertions to the table.

298
Dropping a Table

• All data and structure in the table is


deleted.
• Any pending transactions are
committed.
• All indexes are dropped.
• You cannot roll back this statement.
SQL> DROP TABLE dept30;
Table dropped.

299
Changing the Name of an Object

• To change the name of a table, view,


sequence, or synonym, you execute the
RENAME statement.
SQL> RENAME dept TO department;
Table renamed.

• You must be the owner of the 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.

• Cannot roll back row removal when


using TRUNCATE
• Alternatively, remove rows by using the
DELETE statement
301
Adding Comments to a Table
• You can add comments to a table or
column by using the COMMENT
statement.
SQL> COMMENT ON TABLE emp
2 IS 'Employee Information';
Comment created.

• Comments can be viewed through the


data dictionary views.
– ALL_COL_COMMENTS
– USER_COL_COMMENTS
– ALL_TAB_COMMENTS
– USER_TAB_COMMENTS
302
Summary

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

• Creating new tables


• Creating a new table by using the CREATE
TABLE AS syntax
• Modifying column definitions
• Verifying that the tables exist
• Adding comments to a tables
• Dropping tables
• Altering tables

304
Including Constraints
Objectives

After completing this lesson, you should


be able to do the following:
• Describe constraints
• Create and maintain constraints

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]);

CREATE TABLE emp(


empno NUMBER(4),
ename VARCHAR2(10),

deptno NUMBER(7,2) NOT NULL,
CONSTRAINT emp_empno_pk
PRIMARY KEY (EMPNO));

309
Defining Constraints

• Column constraint level


column [CONSTRAINT constraint_name] constraint_type,

• Table constraint level


column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),

310
The NOT NULL Constraint
Ensures that null values are not permitted
for the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO

7839 KING PRESIDENT 10


7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...

NOT NULL constraint Absence of NOT NULL NOT NULL constraint


(no row may contain constraint
a null value for (any row can contain
this column) null for this column)

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

Insert into Not allowed


50 SALES DETROIT (DNAMESALES
(DNAME
already exists)
60 BOSTON Allowed

313
The UNIQUE Key Constraint
Defined at either the table level or the column
level

SQL> CREATE TABLE dept(


2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE(dname));

314
The PRIMARY KEY Constraint
PRIMARY KEY
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into Not allowed


20 MARKETING DALLAS (DEPTNO
(DEPTNO 20 already
exists)
FINANCE NEW YORK Not allowed
(DEPTNO is null)

315
The PRIMARY KEY Constraint
Defined at either the table level or the column
level

SQL> CREATE TABLE dept(


2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE (dname),
6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));

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

ALTER TABLE table


ADD [CONSTRAINT constraint] type (column);

• Add or drop, but not modify, a


constraint
• Enable or disable constraints
• Add a NOT NULL constraint by using
the MODIFY clause

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.

• Remove the PRIMARY KEY constraint


on the DEPT table and drop the
associated FOREIGN KEY constraint on
the EMP.DEPTNO column.
SQL> ALTER TABLE dept
2 DROP PRIMARY KEY CASCADE;
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.

• A UNIQUE or PRIMARY KEY index is


automatically created if you enable a
UNIQUE key or PRIMARY KEY
constraint.

325
Viewing Constraints

Query the USER_CONSTRAINTS table to


view all constraint definitions and names.
SQL> SELECT constraint_name, constraint_type,
2 search_condition
3 FROM user_constraints
4 WHERE table_name = 'EMP';

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

• Adding constraints to existing tables


• Adding additional columns to a table
• Displaying information in data dictionary views

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

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 Alternative name for an object

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?

• To restrict database access


• To make complex queries easy
• To allow data independence
• To present different views of the same
data

334
Simple Views
and Complex Views
Feature Simple Views Complex Views

Number of tables One One or more

Contain functions No Yes

Contain groups of data No Yes

DML through view Yes Not always

335
Creating a View
• You embed a subquery within the CREATE
VIEW statement.

CREATE [OR REPLACE] [FORCE|NOFORCE] VIEW view


[(alias[, alias]...)]
AS subquery
[WITH CHECK OPTION [CONSTRAINT constraint]]
• TheREAD
[WITH subquery
ONLY] can contain complex SELECT
syntax.
• The subquery cannot contain an ORDER BY
clause.

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.

• Describe the structure of the view by


using the SQL*Plus DESCRIBE
command.
SQL> DESCRIBE empvu10

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.

• Select the columns from this view by


the given alias names.

338
Retrieving Data from a View

SQL> SELECT *
2 FROM salvu30;

EMPLOYEE_NUMBER NAME SALARY


--------------- ---------- ---------
7698 BLAKE 2850
7654 MARTIN 1250
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
7521 WARD 1250

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.

• Column aliases in the CREATE VIEW


clause are listed in the same order as the
columns in the subquery.

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.

• Any attempt to change the department


number for any row in the view will fail
because it violates the WITH CHECK OPTION
constraint.
345
Denying DML Operations
• You can ensure that no DML operations
occur by adding the WITH READ ONLY
option to your view definition.
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
6 WITH READ ONLY;
View created.

• Any attempt to perform a DML on any


row in the view will result in Oracle
Server error ORA-01752.
346
Removing a View

Remove a view without losing data


because a view is based on underlying
tables in the database.
DROP VIEW view;

SQL> DROP VIEW empvu10;


View dropped.

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

• Creating a simple view


• Creating a complex view
• Creating a view with a check constraint
• Attempting to modify data in the view
• Displaying view definitions
• Removing views

349
Controlling User Access
Objectives

After completing this lesson, you should


be able to do the following:
• Create users
• Create roles to ease setup and
maintenance of the security model
• GRANT and REVOKE object privileges

351
Controlling User Access

Database
administrator

Username and password


privileges
Users

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

The DBA creates users by using the


CREATE USER statement.
CREATE USER user
IDENTIFIED BY password;

SQL> CREATE USER scott


2 IDENTIFIED BY tiger;
User created.

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...];

• An application developer may have the


following system privileges:
– CREATE SESSION
– CREATE TABLE
– CREATE SEQUENCE
– CREATE VIEW
– CREATE PROCEDURE
356
Granting System Privileges
The DBA can grant a user specific system
privileges.

SQL> GRANT create table, create sequence, create view


2 TO scott;
Grant succeeded.

357
What Is a Role?

Users

Manager

Privileges

Allocating privileges Allocating privileges


without a role with a role

358
Creating and Granting Privileges
to a Role
SQL> CREATE ROLE manager;
Role created.

SQL> GRANT create table, create view


2 to manager;
Grant succeeded.

SQL> GRANT manager to BLAKE, CLARK;


Grant succeeded.

359
Changing Your Password

• When the user account is created, a


password is initialized.
• Users can change their password by
using the ALTER USER statement.

SQL> ALTER USER scott


2 IDENTIFIED BY lion;
User altered.

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.

GRANT object_priv [(columns)]


ON object
TO {user|role|PUBLIC}
[WITH GRANT OPTION];

362
Granting Object Privileges
• Grant query privileges on the EMP table.
SQL> GRANT select
2 ON emp
3 TO sue, rich;
Grant succeeded.

• Grant privileges to update specific


columns to users and roles.
SQL> GRANT update (dname, loc)
2 ON dept
3 TO scott, manager;
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.

• Allow all users on the system to query


data from Alice’s DEPT table.
SQL> GRANT select
2 ON alice.dept
3 TO PUBLIC;
Grant succeeded.
364
Confirming Privileges Granted
Data Dictionary Table Description
ROLE_SYS_PRIVS System privileges granted to roles
ROLE_TAB_PRIVS Table privileges granted to roles
USER_ROLE_PRIVS Roles accessible by the user
USER_TAB_PRIVS_MADE Object privileges granted on the
user's objects
USER_TAB_PRIVS_RECD Object privileges granted to the
user
USER_COL_PRIVS_MADE Object privileges granted on the
columns of the user's objects
USER_COL_PRIVS_RECD Object privileges granted to the
user on specific columns

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

As user Alice, revoke the SELECT and


INSERT privileges given to user Scott on
the DEPT table.
SQL> REVOKE select, insert
2 ON dept
3 FROM scott;
Revoke succeeded.

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

• Granting other users privileges to your table


• Modify another user’s table through the
privileges granted to you
• Creating a synonym
• Querying the data dictionary views related to
privileges

369
Oracle PL/SQL
About PL/SQL

• PL/SQL is an extension to SQL with


design features of programming
languages.
• Data manipulation and query statements
of SQL are included within procedural
units of code.

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

SQL Statement Executor

Oracle Server

372
Benefits of PL/SQL

Integration

Application

Shared Oracle Server


library

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

PLACE LAT LONG


PLACE LAT LONG
ADILABAD 0.343 1.371
NALGONDA 0.298 1.385
ANANTAPUR 0.256 1.355
NELLORE 0.244 1.397
CHITTOOR 0.231 1.381
CUDDAPAH 0.253 1.376 NIZAMABAD 0.326 1.364
GUNTUR 0.285 1.404 SRIKAKULAM 0.320 1.466
HYDERABAD 0.300 1.368 TIRUPATI 0.239 1.385
KAKINADA 0.296 1.436
VIJAYAWADA 0.289 1.407
KARIMNAGAR 0.322 1.380
VISAKHAPATNAM 0.309 1.455
KHAMMAM 0.301 1.399
VIZIANAGARAM 0.316 1.457
KURNOOL 0.276 1.363
MAHBUBNAGAR 0.292 1.361 WARANGAL 0.314 1.391

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]

END; END; END;

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

Use variables for:


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

388
Handling Variables in PL/SQL

• Declare and initialize variables within


the declaration section.
• Assign new values to variables within
the executable section.
• Pass values into PL/SQL blocks through
parameters.
• View results through output variables.

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';

Set the employee name to “Maduro.”


v_ename := ‘Vijay';

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

256120.08 LIBERTY, and dedicated to


the proposition that all men
are created equal.”
Hyderabad
397
Base Scalar Datatypes
• VARCHAR2 (maximum_length)
• NUMBER [(precision, scale)]
• DATE
• CHAR [(maximum_length)]
• LONG
• LONG RAW
• BOOLEAN
• BINARY_INTEGER
• PLS_INTEGER
398
Scalar Variable Declarations

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

Store the annual salary into a SQL*Plus


host variable.
:g_monthly_sal := v_sal / 12;

• Reference non-PL/SQL variables as host


variables.
• Prefix the references with a colon (:).

406
Summary

• PL/SQL blocks are composed of


the following sections:
DECLARE
– Declarative (optional)
BEGIN
– Executable (required) EXCEPTION

– Exception handling (optional) END;

• A PL/SQL block can be an


anonymous block, procedure, or
function.

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

• Determining validity of declarations


• Developing a simple PL/SQL block

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';

• Numbers can be simple values or


scientific notation.

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;

• Convert the employee name to lowercase.


v_ename := LOWER(v_ename);

417
Datatype Conversion

• Convert data to comparable datatypes.


• Mixed datatypes can result in an error
and affect performance.
• Conversion functions:
– TO_CHAR BEGIN
SELECT TO_CHAR(hiredate,
– TO_DATE 'MON. DD, YYYY')
FROM emp;
– TO_NUMBER END;

418
Datatype Conversion

This statement produces a compile error.


v_comment := USER||': '||SYSDATE;

To correct the error, the TO_CHAR


conversion function is used.
v_comment := USER||': '||TO_CHAR(SYSDATE);

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;

• Set the value of a Boolean flag.


v_equal := (v_n1 = v_n2);

• Validate an employee number if it


contains a value.
v_valid := (v_empno IS NOT NULL);

424
Using Bind Variables

To reference a bind variable in PL/SQL,


you must prefix its name with a colon (:).
Example
DECLARE
v_sal emp.sal%TYPE;
BEGIN
SELECT sal
INTO v_sal
FROM emp
WHERE empno = 7369;
:salary := v_sal;
END;

425
Programming Guidelines

Make code maintenance easier by:


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

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

– Bind variables END;

– Conventions and guidelines


430
Practice Overview

• Reviewing scoping and nesting rules


• Developing and testing PL/SQL blocks

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

• Extract a row of data from the database


by using the SELECT command. Only a
single set of values can be returned.
• Make changes to rows in the database
by using DML commands.
• Control a transaction with the COMMIT,
ROLLBACK, or SAVEPOINT command.
• Determine DML outcome with implicit
cursors.
434
SELECT Statements in PL/SQL

Retrieve data from the database with


SELECT.
Syntax
SELECT select_list
INTO {variable_name[, variable_name]...
| record_name}
FROM table
WHERE condition;

435
SELECT Statements in PL/SQL

INTO clause is required.


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

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

Make changes to database tables by using


DML commands:
• INSERT
• UPDATE INSERT
• DELETE
UPDATE

DELETE

439
Inserting Data

Add new employee information to the emp


table.
Example
DECLARE
v_empno emp.empno%TYPE;
BEGIN
SELECT empno_sequence.NEXTVAL
INTO v_empno
FROM dual;
INSERT INTO emp(empno, ename, job, deptno)
VALUES(v_empno, 'HARDING', 'CLERK', 10);
END;

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

Delete rows that have belong to


department 10 from the emp table.
Example
DECLARE
v_deptno emp.deptno%TYPE := 10;
BEGIN
DELETE FROM emp
WHERE deptno = v_deptno;
END;

442
Naming Conventions

• Use a naming convention to avoid


ambiguity in the WHERE clause.
• Database columns and identifiers
should have distinct names.
• Syntax errors can arise because PL/SQL
checks the database first for a column
in the table.

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

• Initiate a transaction with the first DML


command to follow a COMMIT or
ROLLBACK.
• Use COMMIT and ROLLBACK SQL
statements to terminate a transaction
explicitly.

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

• Embed SQL in the PL/SQL block:


– SELECT, INSERT, UPDATE, DELETE.
• Embed transaction control statements
in a PL/SQL block:
– COMMIT, ROLLBACK, SAVEPOINT.

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

• Creating a PL/SQL block to select data


from a table
• Creating a PL/SQL block to insert data
into a table
• Creating a PL/SQL block to update data
in a table
• Creating a PL/SQL block to delete a
record from a table

451
Writing Control Structures
Objectives

• Identify the uses and types of control


structures
• Construct an IF statement
• Construct and identify different loop
statements
• Use logic tables
• Control block flow using nested loops
and labels

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

THEN Actions ELSE actions


(including further IFs) (including further IFs)

458
IF-THEN-ELSE Statements

Set a flag for orders where there are fewer


than 5 days between order date and ship
date.
Example
...
IF v_shipdate - v_orderdate < 5 THEN
v_ship_flag := ‘Unacceptable';
ELSE
v_ship_flag := ‘Acceptable';
END IF;
...

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

For a given value entered, return a


calculated value.
Example
. . .
IF v_start > 100 THEN
v_start := 2 * v_start;
ELSIF v_start >= 50 THEN
v_start := .5 * v_start;
ELSE
v_start := .1 * v_start;
END IF;
. . .

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

• You can handle null values with the IS


NULL operator.
• Any expression containing a null value
evaluates to NULL.
• Concatenated expressions with null
values treat null values as an empty
string.

465
Logic Tables

Build a simple Boolean condition with a


comparison operator.
AND TRUE FALSE NULL OR TRUE FALSE NULL NOT

TRUE TRUE FALSE NULL TRUE TRUE TRUE TRUE TRUE FALSE

FALSE FALSE FALSE FALSE FALSE TRUE FALSE NULL FALSE TRUE

NULL NULL FALSE NULL NULL TRUE NULL NULL NULL NULL

466
Boolean Conditions

What is the value of V_FLAG in each case?

v_flag := v_reorder_flag AND v_available_flag;

V_REORDER_FLAG V_AVAILABLE_FLAG V_FLAG


TRUE TRUE TRUE
TRUE FALSE FALSE
NULL TRUE NULL
NULL FALSE FALSE

467
Iterative Control: LOOP
Statements

• Loops repeat a statement or sequence


of statements multiple times.
• There are three loop types:
– Basic loop
– FOR loop
– WHILE loop

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

where: condition is a Boolean variable or


expression (TRUE, FALSE,
or NULL);

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;

• Use a FOR loop to shortcut the test for


the number of iterations.
• Do not declare the index; it is declared
implicitly.

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;

Use the WHILE loop to repeat statements


while a condition is TRUE.

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

• Nest loops to multiple levels.


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

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

Change the logical flow of statements by


using control structures.
• Conditional (IF statement)
• Loops
– Basic loop
– FOR loop
– WHILE loop
– EXIT statement
481
Practice Overview

• Performing conditional actions using


the IF statement
• Performing iterative steps using the
loop structure

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;

Where field_declaration stands for


field_name {field_type | variable%TYPE
| table.column%TYPE | table%ROWTYPE}
[[NOT NULL] {:= | DEFAULT} expr]

487
Creating a PL/SQL Record

Declare variables to store the name, job,


and salary of a new employee.
Example
...
TYPE emp_record_type IS RECORD
(ename VARCHAR2(10),
job VARCHAR2(9),
sal NUMBER(7,2));
emp_record emp_record_type;
...

488
PL/SQL Record Structure

Field1 (datatype) Field2 (datatype) Field3 (datatype)

Example

Field1 (datatype) Field2 (datatype) Field3 (datatype)


empno number(4) ename varchar2(10) job varchar2(9)

489
The %ROWTYPE Attribute

• Declare a variable according to a


collection of columns in a database
table or view.
• Prefix %ROWTYPE with the database
table.
• Fields in the record take their names
and datatypes from the columns of the
table or view.

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;

Declare a variable to store the same


information about a employee as it is
stored in the EMP table.
emp_record emp%ROWTYPE;

492
PL/SQL Tables

• Are composed of two components:


– Primary key of data type
BINARY_INTEGER
– Column of scalar or record data type
• Increase dynamically because they are
unconstrained

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;

Declare a PL/SQL variable to store a name.


Example
...
TYPE ename_table_type IS TABLE OF emp.ename%TYPE
INDEX BY BINARY_INTEGER;
ename_table ename_table_type;
...

494
PL/SQL Table Structure

Primary Key Column


... ...

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

To make PL/SQL Table easier to use:


• EXISTS • NEXT
• COUNT • EXTEND
• FIRST and LAST • TRIM
• PRIOR • DELETE

498
Summary

• Define and reference PL/SQL variables


of composite datatypes:
– PL/SQL Records
– PL/SQL Tables
– PL/SQL Table of Records
• Define a PL/SQL Record using the
%ROWTYPE attribute.

499
Practice Overview

• Declaring PL/SQL tables


• Processing data using PL/SQL tables

500
Writing Explicit Cursors
Objectives

• Distinguish between an implicit and an


explicit cursor
• Use a PL/SQL record variable
• Write a Cursor FOR loop

502
About Cursors

Every SQL statement executed by the


Oracle Server has an individual cursor
associated with it:
• Implicit cursors: Declared for all DML
and PL/SQL SELECT statements.
• Explicit cursors: Declared and named
by the programmer.

503
Explicit Cursor Functions

Result Set

7369 SMITH CLERK


7566 JONES MANAGER
Cursor 7788 SCOTT ANALYST Current Row
7876 ADAMS CLERK
7902 FORD ANALYST

504
Controlling Explicit Cursors

No

Yes
DECLARE OPEN FETCH EMPTY? CLOSE

• Create a • Identify • Load the • Test for • Release


named the active current existing the active
SQL area set row into rows set
variables • Return to
FETCH if
rows
found

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;

• Do not include the INTO clause in the cursor


declaration.
• If processing rows in a specific sequence is
required use the ORDER BY clause in the
query.

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;

• Open the cursor to execute the query


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

509
Fetching Data from the Cursor
Syntax
FETCH cursor_name INTO [variable1, variable2, ...]
| record_name];

• Retrieve the current row values into


output variables.
• Include the same number of variables.
• Match each variable to correspond to
the columns positionally.
• Test to see if the cursor contains rows.
510
Fetching Data from the Cursor

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;

• Close the cursor after completing the


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

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

• Process several rows from an explicit


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

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

• Use the %ROWCOUNT cursor attribute


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

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;

• Shortcut to process explicit cursors.


• Implicit open, fetch, and close occur.
• Do not declare the record; it is
implicitly declared.
518
Cursor FOR Loops
Retrieve employees one by one until there
are no more left.
Example
DECLARE
CURSOR c1 IS
SELECT empno, ename
FROM emp;
BEGIN
FOR emp_record IN c1 LOOP
-- implicit open and implicit fetch occur
IF emp_record.empno = 7839 THEN
...
END LOOP; -- implicit close occurs
END;

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

Implicit and Explicit


Implicit cursors are declared by PL/SQL
implicitly for all DML operation and
PL/SQL select statements including
queries that returns only one row
Implicit cursors are not defined by
programmer

522
Explicit cursors

Explicit cursors are named SQL areas this


area is defined by programmer
Use Explicit cursors to individually
process each row returned by a multiple-
row select statement
The set of rows returned by multiple-row
query is called the active set

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

Declare –create aname to SQL area


open –identify the active set
Fetch-load current row into variable
Empty if not empty go back to fetch
Else close cursor

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

%isopen true if cursor is open


%notfound evaluates true if the most
recent fetch doesn’t return a row
%found evaluates true if the most recent
fetch returns row
%rowcount is a number returns total
number of rows returned so far

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

Process several rows from an explicit


cursors using loop
Fetch row with each iteration
Use explicit cursor attribute to test the
success of each fetch

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

• Declaring and using explicit cursors to


query rows of a table
• Using a cursor FOR loop
• Applying cursor attributes to test the
cursor status

538
Advanced Explicit Cursor
Concepts
Objectives

• Write a cursor that uses parameters


• Determine when a FOR UPDATE clause
in a cursor is required
• Determine when to use the WHERE
CURRENT OF clause
• Write a cursor that uses a subquery

540
Cursors with Parameters
Syntax
CURSOR cursor_name
[(parameter_name datatype, ...)]
IS
select_statement;

• Pass parameter values to a cursor when


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

541
Cursors with Parameters

Pass the department number and job title


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

542
The FOR UPDATE Clause

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

• Explicit locking lets you deny access for


the duration of a transaction.
• Lock the rows before the update or
delete.

543
The FOR UPDATE Clause

Retrieve the orders for amounts over


$1000 that were processed today.
Example
DECLARE
CURSOR c1 IS
SELECT empno, ename
FROM emp
FOR UPDATE NOWAIT;

544
The WHERE CURRENT OF
Clause
Syntax
WHERE CURRENT OF cursor

• Use cursors to update or delete the


current row.
• Include the FOR UPDATE clause in the
cursor query to lock the rows first.
• Use the WHERE CURRENT OF clause to
reference the current row from an
explicit cursor.
545
The WHERE CURRENT OF Clause
Example
DECLARE
CURSOR c1 IS
SELECT ...
FOR UPDATE NOWAIT;
BEGIN
...
FOR emp_record IN c1 LOOP
UPDATE ...
WHERE CURRENT OF c1;
...
END LOOP;
COMMIT;
END;

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

• Return different results sets using


cursors with parameters.
• Define cursors with subqueries and
correlated subqueries.
• Manipulate explicit cursors with
commands:
– FOR UPDATE Clause
– WHERE CURRENT OF Clause

548
Practice Overview

• Declaring and using explicit cursors


with parameters
• Using a cursor FOR UPDATE

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

Trap the Exception Propagate the Exception


DECLARE DECLARE

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

• Predefined Oracle Server


• Non-predefined Oracle Server } Implicitly
raised
• User-defined Explicitly raised

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

• WHEN OTHERS is the last clause.


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

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;

WHEN TOO_MANY_ROWS THEN


statement1;
WHEN OTHERS THEN
statement1;
statement2;
statement3;
END;

558
Trapping Non-Predefined Oracle
Server Errors

Declare Associate Reference

Declarative Section Exception-Handling


Section

• Name the • Code the PRAGMA • Handle the


exception EXCEPTION_INIT raised
exception

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

Declare Raise Reference

Declarative Executable Exception-Handling


Section Section Section

• Name the • Explicitly raise • Handle the


exception the exception by raised
using the RAISE exception
statement

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}]);

• A procedure that lets you issue user-


defined error messages from stored
subprograms.
• Called only from an executing stored
subprogram.

568
RAISE_APPLICATION_ERROR

• Used in two different places:


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

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

• Handling named exceptions


• Creating and invoking user-defined
exceptions

571
Practice Overview

• Handling named exceptions


• Creating and invoking user-defined
exceptions

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

Is a named pl/sql block that can accept


parameters and be invoked from a calling
environment
Is of two types
-a procedure that performs an action
-funtion that computes a value
Is based on standard pl/sql block structure
Provide modularity reusability extensibility and
mainatainability

577
syntax

Create or replace procedure


procedure_name (arguments)
Is/as
Pl/sql block

578
In parameters

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;

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

Create or replace procedure query_emp(


P_id in emp.empno%type,
P_name out emp.ename%type,
P_sal out emp.sal%type,
P_comm out emp.comm%type)
Is begin
Select ename,sal,comm into
P_name ,P_sal,P_comm from emp where
empno=P_id
End query_emp;
581
Create or replace procedure query_emp(
P_id in emp.empno%type,
P_name out emp.ename%type,
P_sal out emp.sal%type,
P_comm out emp.comm%type)
Is
begin
Select ename,sal,comm into P_name ,P_sal,P_comm from emp
where empno=P_id;
End query_emp;
/

582
How will you see them?

Variable g_name varchar2(25)


Variable g_sal number
Variable g_comm number

Execute
query_emp(7369, :g_name,:g_sal,:g_com
m);

583
SQL> print g_name

G_NAME
--------------------------------
SMITH

SQL> print g_sal

G_SAL
----------
80000

SQL> print g_comm

584
G_COMM
INOUT parameters

Create or replace procedure


format_phone(P_phone in out varchar2)
Is
Begin
P_phone :='('||substr(P_phone,1,3)||')'||
substr(P_phone ,4,3)||'-'||substr(P_phone ,7);
end format_phone ;

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

create or replace procedure del_emp(


p_id in emp.empno%type)
is
procedure mdisplay (msg varchar2(1000))
is
begin
dbms_output.put_line (msg);
end mdisplay;
begin
delete from emp where empno=p_id;
if SQL%FOUND then mdisplay(‘Employee Deleted’);
else mdisplay(‘Employee not found’);
end del_emp;
588
output

SQL> execute leave_for_emp(7369);

PL/SQL procedure successfully


completed.

589
Functions

A function is a named pl/sql block that


returns a value
A function can be stored in a database as
a schema object
A function is called as part of an
expression

590
Syntax

Create or replace funtion functionname


(paremetrs)
Is/ as
Pl sql blck

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

Create or replace function get_sal(


p_id in emp.empno%type)
return number
Is
v_sal emp.sal%type:=0;
Begin
Select sal into v_sal from emp where empno=p_id;
Return v_sal;
End get_sal;

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

Variable g_salary number


Execute :g_salary :=get_sal(7934)
Print g_salary

595
output

SQL> Variable g_salary number


SQL> Execute :g_salary :=get_sal(7934)
PL/SQL procedure successfully completed.
SQL> Print g_salary
G_SALARY
----------
1300

596
Invoking functions

1 create or replace function tax(p_value in number)


2 return number
3 is
4 begin
5 return(10*p_value);
6* end tax;
SQL> /

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

Can be specified when

 Inserting in a table
 Deleting from a table
 Update a table

602
Trigger components (DML)

 For view or table


 Triggering events are insert, delete or
update
 Scope: may be row level or statement
level
 When clause to restrict condition
 Trigger body

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

SQL> insert into emp


(empno,ename,sal,hiredate)
values(100,'venu',3000,sysdate);
insert into emp (empno,ename,sal,hiredate)
values(100,'venu',3000,sysdate) *
ERROR at line 1:
ORA-20500: you may not update on holidays
ORA-06512: at "SCOTT.SECURE_EMP", line 5
ORA-04088: error during execution of trigger
'SCOTT.SECURE_EMP'

606
DML Triggers Example2

Create or replace trigger restrict_salary


before insert or update of sal on emp
For each row
Begin
if not (:new.job in(‘CMD',‘DIRECTOR'))
and :new.sal > 50000 then
Raise_application_error(-20202,‘No Employee can
earn this amount in the organization');
End if;
End;

607
Try to update emp

SQL> Update emp set sal=50001 where


empid=7369;
Update emp set sal=50001 where empid=7369;
ERROR at line 1:
ORA-20202: No Employee can earn this amount
in the organization
ORA-06512: at "SCOTT.RESTRICT_SALARY",
line 4
ORA-04088: error during execution of trigger
'SCOTT.RESTRICT_SALARY'

608
Packages

Group logically related pl/sql types,items


and subprograms
Consists of two parts
Sepecification and body
Cannot be invoked,prameterised or
nested
Allow oracle server to read multiple
objects into memory once

609
Simple Package Example

create or replace package bike is


brand varchar2(30) := ‘HH Splendour’;
cc number(5,2) := 97.00;
end bike;
SQL> /

Package created.

610
Execute a Package

SQL> exec dbms_output.put_line(' The


bike is '||bike.brand||' '||bike.cc||' CC');
The bike is HH Splendour 97 CC
PL/SQL procedure successfully completed.

611
Thank You

612
ADDITIONAL SLIDES

613
614
Oracle 9i New Features
Quick Overview
MERGE Statement

Merges the data from a SELECT statement


into a table.
You decide when data is updated/inserted
via the “ON ()” clause
You decide what columns are updated
You decide what data is inserted

616
MERGE Syntax

MERGE INTO target_table


USING table/view/subquery
ON (condition)
WHEN MATCHED THEN
update_merge_clause
WHEN UNMATCHED THEN
insert_merge_clause ;

617
MERGE Clauses

ON (condition)
UPDATE SET column = expr, column =
expr...
INSERT (column, column) = (expr, expr)

618
MERGE Example (from doc)

MERGE INTO bonuses D


USING (SELECT employee_id, salary, department_id
FROM employees WHERE department_id = 80) S

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

With one statement, you can now insert


into multiple tables (or multiple rows into
1 table)
One use of the multi-table insert is during
the ETL process to perform a “rotate” on
a table

620
Multi-Table Insert (2)

Can be unconditional or conditional or a


combination of both.
No example available.

621
Pipelined Table Functions

Table functions are functions that return a


set of data. In Oracle 7.x you could return
a REF CURSOR or a PL/SQL collection
O9i enhances this by adding:
• Accepting REF CURSORS as an IN
parameter
• Iterative returning of values (enabling
pipelining)
• Enabling parallizing
622
Pipelining

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)

CREATE FUNCTION extract RETURN t_input_table PIPELINED IS


or t_input_table
  CURSOR c_read_table IS
SELECT * FROM external_table
WHERE load_date < SYSDATE;
BEGIN
FOR r_rec IN c_read_table LOOP
or.id := r_rec.id;
or.load_date := r_rec.load_date;
or.load_value := r_rec.load_value;
  PIPE ROW(r_output_rec);
END LOOP;
END extract;

624
PTF Example (2)

SELECT * FROM TABLE(load(


CURSOR(SELECT * FROM
TABLE(transform(
CURSOR(SELECT * FROM
TABLE(extract()
)))))));

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

Can be done automatically without code


changes.
Done by adding a clause to the
PROCEDURE heading
• PARALLEL_ENABLE(PARTITION p BY
[{HASH | RANGE} (column list) |
ANY

627
Parallel PTF Restrictions

The function must accept a REF CURSOR


as an input parameter
The REF CURSOR must be strongly typed
unless you PARTITION BY ANY

628
External Tables

Oracle can read any external file as long


as you can define its structure with a
SQL*Loader control file
An API is provided by Oracle so that other
vendors can define their own external
table interfaces

629
External Tables -- Benefits

Eliminate the SQL*Load time – the file can


be read natively by Oracle
• reads can be done in parallel
Reduced space requirements – only one
copy of the data is kept.

630
External Tables -- Operations

1.      You can create statistics using


DBMS_STATS (but not analyze)
2.      SELECT, join or sort.
3.      Create Views and Synonyms.
4.      Parallel Query
5.      You can alter the External Table to point to
a different file.
6.      SQL, PL/SQL and Java operations are
permitted on the table.

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

With Oracle 9i PL/SQL can be compiled to


native object code
• PL/SQL is first converted to C code –
which is then compiled using any C
compiler available for the platform

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

SELECT e.name, d.name


FROM employee e
INNER JOIN department d
ON (e.dept_id = d.id)
WHERE e.salary >= 50000;

638
Nested Collections

I don’t have much on this – I just know it


exists.
In O9i you can nest collections – just like
multi-dimensional arrays

639
Index Skip-Scans

Index skip scans improve index scans by non-


prefix columns.
Skip scanning lets a composite index be logically
split into smaller sub-indexes. For example,
table emp (sex, empno, address) with a
composite index on (sex, empno).
The number of logical sub-indexes is determined by
the number of distinct values in the initial column.

640
Index Skip-Scans (2)

Skip scanning is useful when the initial


column of the composite index is not
specified in the query. In other words, it is
"skipped."
Skip scanning is advantageous if there
are few distinct values of the leading
column of the composite index and many
values of the non-leading key of the index.

641
Implementing Index Skip-Scans

Have B*-Tree indexes with not very


selective leading columns
Write queries that don’t reference the
leading column
Set the optimizer_features_enable to at
least 9.0.0

642
Bitmap Join Indexes

A bitmap join index is a Bitmap Index on


one table (usually the FACT) table that
references columns in other tables
(usually the Dimension tables)
A BJI is a pre-computed join!

643
Bitmap Join Index -- Why

Speed Query performance by using the


pre-computed join.

644
Bitmap Join Index v.s. M Views

A BJI is a pre-computed join that is stored


in an index
A MVIEW stores the pre-computed join in
a table – which you then have to index.

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

Run SQL*Plus commands from your browser.


The browser connects to a web server (apache)
Middle tier is only supported on MS Windows
NT/2000
Security is via standard HTTPS/SSL browser
security
Supports a subset of standard SQLPLUS
commands

648
For DBAs
Automatic UNDO Management

Oracle manages UNDO segments rather


than DBAs sizing and managing REDO
segments
Enables Query Flashback

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

Tells Oracle how many seconds Oracle


should try to keep “historic” UNDO
information in the UNDO tablespace.

654
Automatic UNDO and Recovery

Using automatic UNDO speeds crash


recovery
• Oracle first looks at the UNDO
tablespace to recover crashed
transactions.
• If the data is not there, Oracle then
looks at the Online and archived redo
logs.

655
Quotas on UNDO Tablespaces

By default, users are allowed to use unlimited


space in the UNDO tablespace. In order to
restrict the amount of space that users are
allowed to use, you have to use the
UNDO_POOL feature of Oracle’s Database
Resource Manager.
The space quota is by consumer group, not by
user. That means if the group has a 10Meg
limit on UNDO space and 1 user uses all of that
quota no other users in that group can do
updates to the database until the first user
frees the space (via a commit, rollback or
transaction erroring out.)
656
UNDO Dangers

DO NOT, UNDER ANY CIRCUMSTANCES


USE AUTOMATIC UNDO MANAGEMENT
WITH ORACLE 9.0.1.0.0
Can cause database corruption forcing a
complete database recovery.
Install the 9.0.1.1.0 (or later) patch set and
you should be fine

657
UNDO Dangers (2)

One user may be able to prevent all other


users from executing DML
• Enable quotas and this is restricted to
users in the current consumer group

658
UNDO Benefits

Reduce number of ORA-01555 Errors


• If an active transaction requires undo
space and the undo tablespace does not
have available space, the system starts
reusing unexpired undo space. Such
action can potentially cause some
queries to fail with the "snapshot too
old" error.
Don’t have to worry about having correct
number of rollback segments.
659
Default Temporary Tablespace

In Oracle 9i a user’s temporary tablespace must


be either SYSTEM or a tablespace as type
TEMPORARY
You can have multiple TEMPORARY tablespaces
You can declare one temp tablespace to be the
system default temporary tablespace
• You don’t have to remember to create a user
with a temporary tablespace
• You don’t have to worry about a user
unintentionally having the SYSTEM
tablespace as their temp ts
660
Resumable Space Allocation

If certain operations run out of space,


Oracle can automatically pause (rather
than fail) them until the space issue is
resolved.

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)

SELECT statements that run out of TEMP


space
DML: All INSERT, UPDATE, DELETE
statements. Including INSERT INTO ...
SELECT FROM ...
• Import/Export
• SQL*Loader

663
Resumable Operations (2)

The following DDL Statements


• CREATE TABLE ... AS SELECT
• CREATE INDEX
• ALTER INDEX ... REBUILD
• ALTER TABLE ... MOVE PARTITION
• ALTER TABLE ... SPLIT PARTITION
• ALTER INDEX ... REBUILD PARTITION
• ALTER INDEX ... SPLIT PARTITION
• CREATE MATERIALIZED VIEW
• CREATE MATERIALIZED VIEW LOG
664
Resumable Implementation

The error is reported in the alert log.


If the user registered a trigger on the AFTER
SUSPEND system event, the user trigger is
executed. A user supplied PL/SQL procedure
can access the error message data using the
DBMS_RESUMABLE package and
DBA/USER_RESUMABLE view.
Suspending a statement automatically results in
suspending the transaction. Thus all
transactional resources are held through a
statement suspend and resume.

665
Resumable Implementation

When the error condition disappears (for


example, as a result of user intervention
or perhaps sort space released by other
queries), the suspended statement
automatically resumes execution.

666
OEM Improvements

Significantly Faster
Improved interface
Improved integration of tools

667
Index Operations

All index operations can be completed


online
• CREATE
• ALTER INDEX ... REBUILD
This is all types of indexes

668
Online Table Reorganizations

Many table reorganizations can be


performed online.
• ALTER TABLE ... MOVE
• Rename columns
• etc
Implemented as materialized view
operation

669
DBMS_METADATA

With the DBMS_METADATA package you


can dump the definitions for most objects
in the database.
The definitions can be dumped as DDL or
XML

670
DBMS_METADATA (2)

Supported Object Types


• Most schema-objects
• Some non-schema objects
• INDEXTYPEs

671
DBMS_METADATA (2)

Things not supported


• CLUSTER
• CONSUMER_GROUP
• CONTEXT
• INDEX PARTITION
• LIBRARY
• OPERATOR
• QUEUE
• RESOURCE PLAN
• SYNONYM
672
DBMS_METADATA (3)

If you attempt to export the SYS schema


(9.0.1.1.0, Sun SOLARIS) you will get a
bunch of errors and will have to exit your
session before you can continue.

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

Replication is the process of copying and maintaining


database objects, such as tables, in multiple
databases that make up a distributed database
system.
Backups are copies of the database data in a format
specific to the database. Backups are used to
recover one or more files that have been physically
damaged as the result of a disk failure. Media
recovery requires the restoration of the damaged
files from the most recent operating system backup
of a database. It is of the utmost importance to
perform regularly scheduled backups.

689
Definitions Cont.

Mission Critical Applications


An application is defined as mission critical,
imho, if
1. there are legal implications or financial loss
to the institution if the data is lost or
unavailable.
2. there are safety issues if the data is lost or
unavailable.
3. no data loss can be tolerated.
4. uptime must be maximized (98%+).
690
Definitions Cont.

‘large’ or ‘very large’ or ‘a lot’


Seems odd, but ‘large’ is a hard definition to
determine. Vldb is an acronym for very large
databases. Its definition varies depending on
the database software one selects. Very large
normally indicates data that is reaching the
limits of capacity for the database software, or
data that needs extraordinary measures need
to be taken for operations such as backup,
recovery, storage, etc.

691
Definitions Cont.

Commercial databases do not a have a practical


limit to the size of the load. Issues will be
backup strategies for large databases.
Freeware does limit the size of the databases,
and the number of users. Documentation on
these issues vary widely from the freeware
sites to the user sites. Mysql supposedly can
support 8T and 100 users. However, you will
find arguments on the users lists that these
numbers cannot be met.

692
Selecting a DBMS

Many options, many decisions, planning,


costs, criticality.
For lots of good information, please refer
to the urls on the last slides. Many
examples of people choosing product.

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

Again, planning takes center stage. In the end


you want stability and dependability.
How many users need access?
What will the security requirements be?
Are there software licensing issues that need
consideration?
Is platform portability a requirement?
Two tier or three tier architecture?

698
Selecting an Application Layer

Direct access to the database layer? (probably


should be avoided)
Are you replicating? How? Where? With what?
There are no utilities that will port data from 1
database to another (i.e., postgres to mysql). if
database portability is a requirement, an
independent code must be written to satisfy
this requirement.

699
Selecting an Application Layer Cont.

Application maintenance issues


People availability, working with users as a team, talent,
and turnover? (historically a huge issue)
A ‘known’ or ‘common’ language?
Freeware? Bug fixes, patches…are they important and
timely?
Documentation? Set standards, procedures, code reviews
making sure the documentation exists and is clear.
Is the application flexible enough to easily accommodate
business rule changes that mandate modifications?
The availability of an ER diagram at this stage is invaluable.
We consider it a must have.
There are no utilities to port data from 1 type of db to
another. This lack of portability means a method to
move data between databases
700 must be written independently.
Selecting an Application Layer

Misc. application definitions…


This presentation is not an application
presentation, but I will mention a few terms
you may hear.
Sql the query language for relational databases.
A must learn.
ODBC, open database connectivity. The software
that allows a database to talk to an application.
JDBC, java database connectivity.

701
Relational Design

The design of the application schema will


determine the usability and query ability
of the application. Done incorrectly, the
application and users will suffer until
someone else is forced to rewrite it.

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

One implements a schema by running scripts. These


scripts can be run against multiple servers and
should be archived.

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 G2H2 map to


G2 H2
# G2_ID map to # H2_ID
define

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

Calibration type might have 3 Each calibration record will be


rows, drift, pedestal, & gain Defined by drift, pedestal or
gain.
This is a parent table.
In addition to start and end
times.
This is a child table.
725
Relational Design
The Bad
CALIBRATION
# CALIBRATION_ID
* TSTART
o TEND

define define define

relate to relate to relate to

DRIFT_CALIB PEDESTAL_CALIB GAIN_CALIB


# DRIFT_CALIB_ID # PEDESTAL_CALIB_ID # GAIN_CALIB_ID
* TSTART * TSTART * TSTART
o TEND o TEND o TEND

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

relate to relate to relate to

PEDESTAL_CALIB DRIFT_CALIB GAIN_CALIB


# PEDESTAL_CALIB_ID # DRIFT_CALIB_ID # GAIN_CALIB_ID
* TSTART * TSTART * TSTART
o TEND o TEND o TEND

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

AHHH, back to normal, or normalization as we refer to it.

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

Replication is the process of copying and


maintaining database objects in multiple
databases that make up a distributed
database system. Replication can improve
the performance and protect the
availability of applications because
alternate data access options exist.

741
Replication Cont.

Oracle Supports 3 types of replication  READ ONLY


Snapshots (Materialized views), Advanced Replication
and streams based replication.
Streams allows ddl modifications made to the master
automatically.
Streams can be configured in uni-directional ( Single
Source and one or more than targets) or master to
master where updates can happen to any participant
database. 
Advanced replication also supports master to master . But
streams based replication is recommended.

READ ONLY Snapshots replication from a Sun box to a Sun


& Linux box(s) is being done in CDF.  When a replica is
under maintenance there is failover to another replica. 
The replicas are up and running in read only mode if the
742 master is down for maintenance.
Replication cont.

Oracle master to master replication allows for


updates on both the master and replica sides.
Master to master is a complex and a high
maintenance replication. It seems to be the 1st
option the unwitting opt for. Both Cern and
Fermi dbas have requested firm justification
before considering this type of replication
request.
Every link in the multi master would be required
to be a fully staffed, as downtime will be
critical.

743
Replication cont.

Disk Space for Archives. If receiving site is down for extended


period of time, then source db should be tuned enough to hold
the archives logs, otherwise, one has to reinstantiate the
replication. Reasonable downtime for target depends upon
archive area being generated on source. Space, space and
more space.
Conflict Resolution In Master to Master, conflict resolution may be
challenge. Rules should be well defined to resolve the data
conflicts.
Design of Data Model if Primary Keys are populated by
sequences , there is very much chance of overlapping the
sequences and will cause integrity constraints. Data Model
should be designed very carefully.
DB Support In Master to Master Replication, all master sites
should be in 24*7 support mode. Otherwise , sync up of data
will be challenge or one may lead to reinstantiation of
replication. Reinstantiation is not unplug and play type of
744 situation.
Freeware Replication

MySQL has replication in the last stable


version (3.23.32, v4.1 is out). It is master-
slave replication using binary log of
operations on the server side. It is
possible to build star or chain type
structures.
There is a PostgreSQL replication tool.
We have not tested it yet.

745
Lost in Space

Space is the 1 area consistently under estimated


in every application I have seen. Imho,
consistently, data volume initial estimates
were undersized by a factor of 2 or 3. For
example, RunII events were estimated at 1
billion rows. This estimate was surpassed
Feb. 2004. We will probably end up with 4-5
billion event rows. That is a lot of disk space.
Disk hardware becomes unsupported, and
obsolete in what seems to be a blink of an eye.

746
Lost In Space cont.

N Gb 8 x N Gb Unexpected?

All databases use disk to store data.


Data Index Redo Rollback

Data Index Backup Replication


mirror mirror

Good rule of thumb:


You need 10x the disk to hold a given amount of data in an RDB.
Operate in 2 year cycles:
• First 2 years storage available on day 1.
747
• Evaluate growth at end of year 1, begin prep of next 2 yr.
Lost in Space, cont.

You will use as much disk space as you


purchase, and then some.
Database indices will take MINIMALLY at
least as much space as the tables,
probably considerably more.
Give WIDE lead time to purchase disk
storage. New disks are not installed
and configured over night. They require
planning, downtime and $.

748

You might also like